@inkeep/open-knowledge 0.39.0-beta.7 → 0.39.0-beta.8

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 (104) hide show
  1. package/dist/{acp-harness-probe-CUYWrorr.mjs → acp-harness-probe-DjTv5e1A.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/cli.mjs +7 -7
  5. package/dist/constants-DtCru_h4.mjs +2 -0
  6. package/dist/git-handle-BGt8xT_1.mjs +1 -0
  7. package/dist/{git-handle-B30Z3S49.mjs → git-handle-YzX39hWc.mjs} +2 -2
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-DVJ8qrbD.mjs → init-B_KvF9QQ.mjs} +3 -3
  10. package/dist/init-C_Z3gBHj.mjs +1 -0
  11. package/dist/{launch-json-removal-CNHYRUOC.mjs → launch-json-removal-DaC6MWYi.mjs} +2 -2
  12. package/dist/loader-Aakvd0a9.mjs +1 -0
  13. package/dist/{loader-oy_NkWUH.mjs → loader-DkorwqUF.mjs} +2 -2
  14. package/dist/md-manager-DPNbV4Up.mjs +2 -0
  15. package/dist/{open-browser-f7NgugNK.mjs → open-browser-kdF24mgk.mjs} +2 -2
  16. package/dist/parse-worker.mjs +1 -1
  17. package/dist/preview-8ufWS_Yg.mjs +1 -0
  18. package/dist/{preview-D1NzVj36.mjs → preview-Bce8FXXe.mjs} +2 -2
  19. package/dist/public/assets/{ActivityModeContent-D57-Ku1o.js → ActivityModeContent-But5j0lr.js} +1 -1
  20. package/dist/public/assets/{AgentDiffPane-B3C8d_Bj.js → AgentDiffPane-oydx_GOA.js} +1 -1
  21. package/dist/public/assets/{AgentThreadClientBinder-D7HU2baf.js → AgentThreadClientBinder-BKKe4a6D.js} +1 -1
  22. package/dist/public/assets/CodeMirrorPropInput-Sjp30pzp.js +3 -0
  23. package/dist/public/assets/DocumentContext-DN3M8p0h.js +38 -0
  24. package/dist/public/assets/{EnableSyncConfirmDialog-B8E3XigY.js → EnableSyncConfirmDialog-CbuJxerH.js} +1 -1
  25. package/dist/public/assets/FeedbackForm-MFOBrkxc.js +1 -0
  26. package/dist/public/assets/{GraphPanel-CWQeoE13.js → GraphPanel-CDzcx7vs.js} +1 -1
  27. package/dist/public/assets/{ManagedArtifactProperties-C2c-xiZv.js → ManagedArtifactProperties-BB3-9OBw.js} +1 -1
  28. package/dist/public/assets/{McpConsentDialogBody-_E-zSZcr.js → McpConsentDialogBody-OqDOF7x4.js} +1 -1
  29. package/dist/public/assets/{MermaidDocEditor-BDEw6KhX.js → MermaidDocEditor-B6KK6qX2.js} +1 -1
  30. package/dist/public/assets/PropertyPanel-CinI1G1g.js +2 -0
  31. package/dist/public/assets/{ReportBugDialogBody-Vatcwx0j.js → ReportBugDialogBody-BMOl6KV7.js} +1 -1
  32. package/dist/public/assets/{SettingsDialogBody-C0UQEFXZ.js → SettingsDialogBody-Gk5e3niv.js} +3 -3
  33. package/dist/public/assets/{ShareBranchSwitchDialog-yPDcRbbF.js → ShareBranchSwitchDialog-CzeHnBZ6.js} +1 -1
  34. package/dist/public/assets/{ShareReceiveDialog-XPxnPaw4.js → ShareReceiveDialog-DGTKtAY6.js} +1 -1
  35. package/dist/public/assets/{ShareReceiveMissDialog-BSTotnwx.js → ShareReceiveMissDialog-BS5BCjjQ.js} +1 -1
  36. package/dist/public/assets/{SkillEditorActions-Cf43hAWR.js → SkillEditorActions-ZkQKiOQc.js} +1 -1
  37. package/dist/public/assets/{SourceEditor-fTWc_1_N.js → SourceEditor-4CJXi9kJ.js} +1 -1
  38. package/dist/public/assets/{TerminalPanel-DNjptZAR.js → TerminalPanel-DyJkPAsZ.js} +3 -3
  39. package/dist/public/assets/{TerminalSessionsHost-BTaTW1V9.js → TerminalSessionsHost-CaOjEcgq.js} +2 -2
  40. package/dist/public/assets/{TerminalWindowApp-Bo25OrtB.js → TerminalWindowApp-C2al62bW.js} +1 -1
  41. package/dist/public/assets/{ThreadView-aWrnhxjd.js → ThreadView-CXI_J3i2.js} +1 -1
  42. package/dist/public/assets/{TimelineDiffPane-DW_Ed369.js → TimelineDiffPane-C8Qnc4zA.js} +1 -1
  43. package/dist/public/assets/{agent-diff-store-Bd0NDaYd.js → agent-diff-store-D5yp573E.js} +1 -1
  44. package/dist/public/assets/{agent-visibility-bo7-lQPw.js → agent-visibility-BUmsS0vL.js} +1 -1
  45. package/dist/public/assets/{auth-state-cache-DKRhUdiz.js → auth-state-cache-CPrBjd7m.js} +3 -3
  46. package/dist/public/assets/{client-version-Hh5K6Ltl.js → client-version-CNNfEvD2.js} +1 -1
  47. package/dist/public/assets/{config-provider-BBWoBQ3A.js → config-provider-BvPGEDTw.js} +2 -2
  48. package/dist/public/assets/{dist-df-v6kvy.js → dist-CDKZLcnD.js} +68 -68
  49. package/dist/public/assets/{dist-Cju6fxq6.js → dist-DRspkp5n.js} +1 -1
  50. package/dist/public/assets/{doc-hash-NyLrtNo2.js → doc-hash-r2oc1gt-.js} +1 -1
  51. package/dist/public/assets/{documents-events-BHJB8gGz.js → documents-events-DNDUkpJM.js} +1 -1
  52. package/dist/public/assets/{file-tree-adapter-BnZwo5Ls.js → file-tree-adapter-DOr3Nip1.js} +1 -1
  53. package/dist/public/assets/{index-JMW0Wfy-.js → index-Lsv_5pDn.js} +13 -13
  54. package/dist/public/assets/{keyboard-shortcuts-Ctc7xams.js → keyboard-shortcuts-maIyJzSw.js} +1 -1
  55. package/dist/public/assets/{lint-config-client-BwIg_Zty.js → lint-config-client-C7TVN28Z.js} +1 -1
  56. package/dist/public/assets/{navigation-targets-D1rdXyAI.js → navigation-targets-DhXblHdl.js} +1 -1
  57. package/dist/public/assets/{open-managed-artifact-tab-MjzvjrV8.js → open-managed-artifact-tab-DokRsPIe.js} +1 -1
  58. package/dist/public/assets/{pending-receive-nav-store-DIZcm2qX.js → pending-receive-nav-store-DYgvjLiq.js} +1 -1
  59. package/dist/public/assets/{prop-types-C0wWXvTx.js → prop-types-IOhQSrD8.js} +1 -1
  60. package/dist/public/assets/{receive-store-B3ygF-LA.js → receive-store-BwEPjiP1.js} +1 -1
  61. package/dist/public/assets/{selection-context-ZUAPQrO2.js → selection-context-TzGfTWCl.js} +1 -1
  62. package/dist/public/assets/{skill-actions-DeZSwOo7.js → skill-actions-CzuWC1X5.js} +1 -1
  63. package/dist/public/assets/{skills-api-vt4KnCX6.js → skills-api-CGbwE9vp.js} +1 -1
  64. package/dist/public/assets/{src-C6qvZbZl.js → src-4ThOx6_s.js} +1 -1
  65. package/dist/public/assets/{target-navigation-intent-DNrmu8Sx.js → target-navigation-intent-Beex9QTj.js} +1 -1
  66. package/dist/public/assets/{terminal-launch-events-vDhBoD8w.js → terminal-launch-events-C2tfnQr1.js} +1 -1
  67. package/dist/public/assets/{terminal-telemetry-D1lMQO11.js → terminal-telemetry-zqEIM46I.js} +1 -1
  68. package/dist/public/assets/{typing-burst-detector-CjccvkIX.js → typing-burst-detector-D-Tl1w8f.js} +1 -1
  69. package/dist/public/assets/{use-activity-panel-CI9yTIc5.js → use-activity-panel-Dth1RWbL.js} +1 -1
  70. package/dist/public/assets/{use-apply-config-color-theme-R1RZkk5a.js → use-apply-config-color-theme-Ccfxcl-K.js} +1 -1
  71. package/dist/public/assets/{use-collab-url-B-LUA0g9.js → use-collab-url-Cf1srbbW.js} +1 -1
  72. package/dist/public/assets/{use-live-xterm-theme-DW54zfIk.js → use-live-xterm-theme-BpGfJKio.js} +1 -1
  73. package/dist/public/assets/{use-terminal-enabled-Yhee4_eR.js → use-terminal-enabled-BEEp7vb7.js} +1 -1
  74. package/dist/public/assets/{use-timeline-entry-diff-8_46BlQG.js → use-timeline-entry-diff-CJ-IHgH7.js} +4 -4
  75. package/dist/public/assets/{use-workspace-0T1cdRp3.js → use-workspace-C1D_I03G.js} +1 -1
  76. package/dist/public/assets/{workspace-paths-nkXut9sM.js → workspace-paths-CDfRQ5qH.js} +1 -1
  77. package/dist/public/index.html +34 -34
  78. package/dist/{repair-launch-json-BxVkRYZG.mjs → repair-launch-json-BDfwi9-9.mjs} +2 -2
  79. package/dist/{repair-mcp-configs-D6R0toAP.mjs → repair-mcp-configs-kCwuW5Ze.mjs} +2 -2
  80. package/dist/{repair-skills-DnkpKCSB.mjs → repair-skills-BaZcFu4I.mjs} +2 -2
  81. package/dist/repair-skills-BunyY3Wb.mjs +1 -0
  82. package/dist/{server-lock-1KyShewk.mjs → server-lock-BiAmhJ19.mjs} +2 -2
  83. package/dist/server-lock-BwO1WEYX.mjs +1 -0
  84. package/dist/{src-CytrG8h8.mjs → src-BQhUreu4.mjs} +2 -2
  85. package/dist/{src-FuRMJntf.mjs → src-BTo9m5ju.mjs} +82 -82
  86. package/dist/{src-DKa-TnuV.mjs → src-DhzHOoTy.mjs} +1 -1
  87. package/dist/{src-DO_fYaAw.mjs → src-YSGKFci8.mjs} +4 -4
  88. package/dist/{start-x5T6R5Vy.mjs → start-CmXhmoqo.mjs} +2 -2
  89. package/dist/start-Dw3sT0mB.mjs +1 -0
  90. package/dist/{write-project-skill-gbFVJJ2C.mjs → write-project-skill-Dt58S1kj.mjs} +2 -2
  91. package/package.json +4 -4
  92. package/dist/constants-Lo6qvo2O.mjs +0 -2
  93. package/dist/git-handle-RhB108wn.mjs +0 -1
  94. package/dist/init-D5VPQ7rN.mjs +0 -1
  95. package/dist/loader-CSw2bCSB.mjs +0 -1
  96. package/dist/md-manager-DqdW_K1F.mjs +0 -2
  97. package/dist/preview-BxQH5EQ-.mjs +0 -1
  98. package/dist/public/assets/CodeMirrorPropInput-BNR51IWy.js +0 -3
  99. package/dist/public/assets/DocumentContext-Y1Gu1DW-.js +0 -38
  100. package/dist/public/assets/FeedbackForm-C_cZqAfF.js +0 -1
  101. package/dist/public/assets/PropertyPanel-Cd0IOo2B.js +0 -2
  102. package/dist/repair-skills-B8sCkCSw.mjs +0 -1
  103. package/dist/server-lock-CmiibuTm.mjs +0 -1
  104. package/dist/start-Dbzf81GV.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$n as i,$r as a,$t as o,A as s,Aa as c,Ai as l,An as u,Ar as d,At as f,B as p,Ba as m,Bi as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Cr as S,Ct as C,D as w,Da as T,Di as ee,Dn as te,Dr as ne,Dt as E,E as re,Ea as ie,Ei as ae,En as oe,Er as se,Et as ce,F as le,Fa as ue,Fi as de,Fn as D,Fr as fe,Ft as pe,G as me,Ga as he,Gi as ge,Gn as _e,Gr as ve,Gt as ye,H as be,Ha as xe,Hn as Se,Hr as Ce,Ht as we,Ia as Te,Ii as Ee,In as De,Ir as Oe,It as ke,J as Ae,Ja as je,Jn as Me,Jr as Ne,Jt as Pe,K as Fe,Kn as Ie,Kr as Le,Kt as Re,La as ze,Li as Be,Ln as Ve,Lr as He,Lt as Ue,M as We,Ma as Ge,Mi as Ke,Mn as qe,Mr as Je,Mt as Ye,N as Xe,Na as Ze,Ni as Qe,Nn as $e,Nr as et,Nt as tt,O as nt,Oa as rt,Oi as it,On as at,Or as ot,Ot as st,Pa as ct,Pi as lt,Pn as ut,Pr as dt,Pt as ft,Q as pt,Qi as mt,Qn as ht,Qr as gt,Qt as _t,R as vt,Ra as yt,Ri as bt,Rn as xt,Rr as St,Rt as Ct,S as wt,Sa as Tt,Si as Et,Sn as Dt,Sr as Ot,St as kt,T as At,Ti as jt,Tn as Mt,Tr as Nt,Tt as Pt,U as Ft,Ua as It,Ui as Lt,Un as Rt,Ur as zt,Ut as Bt,V as Vt,Va as Ht,Vi as Ut,Vn as Wt,Vr as Gt,Vt as Kt,W as qt,Wa as Jt,Wi as Yt,Wn as eee,Wr as tee,Wt as nee,X as Xt,Xi as Zt,Xn as Qt,Xr as $t,Xt as en,Y as tn,Yi as nn,Yn as rn,Yr as an,Yt as on,Z as sn,Zi as cn,Zn as ln,Zr as un,Zt as dn,_ as fn,_a as pn,_i as mn,_n as hn,_r as gn,_t as _n,a as vn,aa as yn,ai as bn,an as xn,ar as Sn,at as Cn,b as wn,ba as Tn,bi as En,bn as Dn,br as On,bt as kn,c as An,ca as jn,ci as ree,cn as iee,cr as Mn,d as Nn,da as Pn,di as Fn,dn as In,dr as Ln,dt as Rn,ea as zn,ei as Bn,en as aee,er as oee,et as Vn,f as Hn,fi as Un,fn as Wn,fr as Gn,ft as Kn,g as qn,ga as Jn,gi as Yn,gn as Xn,gr as Zn,gt as Qn,h as $n,hn as er,hr as tr,ht as nr,i as rr,ia as ir,ii as ar,in as or,ir as sr,it as cr,j as lr,ja as ur,ji as dr,jn as fr,jr as pr,jt as mr,k as hr,ka as gr,ki as _r,kn as vr,kr as yr,kt as br,l as xr,la as Sr,li as Cr,ln as wr,lr as Tr,lt as Er,m as Dr,mi as Or,mn as kr,mr as Ar,mt as jr,n as Mr,ni as Nr,nn as Pr,nr as Fr,nt as Ir,o as Lr,oa as Rr,oi as zr,on as Br,or as Vr,ot as Hr,pa as Ur,pi as Wr,pn as Gr,pr as Kr,pt as qr,q as Jr,qn as Yr,qr as Xr,qt as Zr,r as Qr,ri as $r,rn as ei,rr as ti,rt as ni,s as ri,sa as ii,si as ai,sn as see,sr as cee,t as oi,ta as si,ti as ci,tn as lee,tr as uee,tt as dee,u as li,ui,un as di,ur as fi,ut as pi,v as mi,vi as hi,vn as gi,vr as _i,vt as vi,w as fee,wa as yi,wi as bi,wn as xi,wr as Si,wt as Ci,x as wi,xa as Ti,xi as Ei,xn as Di,xr as Oi,xt as ki,y as Ai,ya as ji,yi as Mi,yn as pee,yr as Ni,yt as Pi,z as Fi,za as Ii,zi as mee,zn as Li,zr as Ri,zt as zi}from"./src-FuRMJntf.mjs";import{$ as Bi,A as Vi,C as Hi,Ct as Ui,Dt as Wi,Et as Gi,G as Ki,H as qi,I as Ji,K as Yi,L as Xi,N as Zi,Ot as Qi,Q as $i,R as ea,S as ta,St as na,T as ra,Tt as ia,U as aa,V as oa,X as O,Y as k,Z as sa,_ as ca,_t as la,at as A,bt as ua,ct as j,dt as M,et as da,ft as fa,g as pa,h as ma,i as ha,it as N,l as ga,lt as P,m as _a,mt as va,n as ya,nt as F,ot as ba,pt as xa,q as Sa,r as Ca,rt as wa,st as Ta,t as Ea,u as Da,ut as Oa,vt as ka,w as Aa,wt as ja,xt as Ma,yt as Na,z as Pa}from"./sleep-DcENuR74.mjs";import{c as Fa,i as Ia,l as La,n as Ra,s as za}from"./esm-CItKw7Y6.mjs";import{n as Ba,t as Va}from"./md-manager-DqdW_K1F.mjs";import{A as Ha,C as Ua,D as Wa,E as Ga,N as Ka,O as qa,S as Ja,T as Ya,_ as Xa,a as Za,b as Qa,c as $a,d as eo,f as to,g as no,h as ro,i as io,j as ao,k as oo,l as so,m as co,n as lo,o as uo,p as fo,r as po,s as mo,t as ho,u as go,v as _o,w as vo,x as yo,y as bo}from"./fs-traced-vMO6kYgZ.mjs";import{D as xo,E as hee,S as So,T as gee,a as Co,b as wo,l as To,p as Eo,r as I,s as Do,x as Oo,y as ko}from"./logger-B7Z8XO-z.mjs";import{a as Ao,i as jo,o as Mo,r as No,s as Po,t as Fo}from"./git-handle-B30Z3S49.mjs";import{t as Io}from"./libesm-CG75CrN9.mjs";import{n as Lo,t as Ro}from"./build-fAc55Z_L.mjs";import{S as _ee,a as zo,c as Bo,d as Vo,f as Ho,g as Uo,h as Wo,i as Go,l as Ko,m as qo,n as Jo,r as Yo,v as Xo,x as Zo,y as Qo}from"./server-lock-1KyShewk.mjs";import{t as $o}from"./yazl-BafwB467.mjs";import{t as es}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as ts,c as ns,d as rs,f as is,h as as,i as os,l as ss,m as cs,n as ls,o as us,p as ds,r as fs,s as ps,t as ms,u as hs}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as gs,B as _s,C as vs,D as ys,E as bs,F as xs,H as Ss,I as Cs,L as ws,M as Ts,N as Es,O as Ds,P as Os,S as ks,T as As,V as js,_ as Ms,a as Ns,b as Ps,c as Fs,d as Is,f as Ls,g as Rs,h as zs,i as Bs,j as Vs,k as Hs,l as Us,m as Ws,n as Gs,o as Ks,p as qs,r as Js,s as Ys,t as Xs,u as Zs,v as Qs,w as $s,x as ec,y as tc,z as nc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as rc,c as ic,d as ac,i as oc,l as sc,n as cc,o as lc,r as uc,s as dc,t as fc,u as pc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as mc,r as hc,t as gc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as _c}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as vc}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as yc,t as bc}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as xc,t as Sc}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Cc,r as wc,t as Tc}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ec,t as Dc}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Oc}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as kc}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Ac}from"./wrapper-BcpqREsI.mjs";import{createRequire as jc}from"node:module";import{execFile as Mc,spawn as Nc,spawnSync as Pc}from"node:child_process";import*as Fc from"node:path";import{basename as Ic,delimiter as Lc,dirname as Rc,extname as zc,isAbsolute as Bc,join as L,normalize as Vc,posix as Hc,relative as R,resolve as z,sep as Uc,win32 as Wc}from"node:path";import*as Gc from"node:fs";import{appendFileSync as Kc,chmodSync as qc,closeSync as Jc,constants as Yc,createReadStream as Xc,createWriteStream as Zc,existsSync as B,lstatSync as Qc,mkdirSync as $c,mkdtempSync as el,openSync as tl,readFile as nl,readFileSync as V,readSync as rl,readdirSync as il,readlinkSync as al,realpathSync as ol,renameSync as sl,rmSync as cl,rmdirSync as ll,statSync as ul,unlinkSync as dl,writeFileSync as fl}from"node:fs";import{arch as pl,availableParallelism as ml,homedir as hl,hostname as gl,platform as _l,tmpdir as vl}from"node:os";import{access as yl,chmod as bl,constants as xl,lstat as Sl,readFile as Cl,readdir as wl,realpath as Tl,stat as El,writeFile as Dl}from"node:fs/promises";import{Readable as Ol,Transform as kl,Writable as Al}from"node:stream";import{URLSearchParams as jl,fileURLToPath as Ml,pathToFileURL as Nl}from"node:url";import Pl,{createHash as Fl,randomUUID as Il,webcrypto as Ll}from"node:crypto";import vee from"crypto";import{Readable as Rl}from"stream";import{Worker as yee}from"node:worker_threads";import{monitorEventLoopDelay as bee,performance as zl}from"node:perf_hooks";import{createInterface as xee}from"node:readline";import{pipeline as Bl}from"node:stream/promises";import{setTimeout as Vl}from"node:timers/promises";import{promisify as Hl}from"node:util";import{lookup as See}from"node:dns/promises";import{request as Cee}from"node:http";import{request as wee}from"node:https";import{createBrotliDecompress as Tee,createGunzip as Eee,createInflate as Dee}from"node:zlib";import{Http2ServerRequest as Ul,constants as Oee}from"http2";import{AsyncLocalStorage as kee}from"node:async_hooks";import{lookup as Aee}from"node:dns";import jee from"node:tls";var Wl=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=Bc(t)?t:z(this.gitDir,t))}catch(e){if(!Jl(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 Jl(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]}:Xl(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 Jl(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Mee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Yl(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(`..`)||Bc(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Fee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Jl(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return Jl(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 Xl(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Gl(e){return ql(z(e),``)}function Kl(e){let t=z(e),n=z(hl());if(t===n)return{kind:`absent`};let r=ql(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=Rc(i);if(e===i||e===n)return{kind:`absent`};let r=ql(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function ql(e,t){let n=L(e,`.git`),r;try{r=ul(n)}catch(e){return Jl(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Wl(`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=Bc(o)?o:z(e,o);try{if(!ul(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 Wl(`linked`,e,t,n,s)}}function Mee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Nee(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=Pee(i[1]);if(a.length>0)return a}return null}function Nee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Pee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Jl(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Yl(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Fee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Yl(t[1])?{kind:`symbolic`,target:t[1]}:null:Xl(e)?{kind:`oid`,oid:e}:null}function Xl(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Iee(e){return`git-author-${je(e.trim().toLowerCase())}`}const Lee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Zl(e){let t=Kl(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 Ql(e){let t=Zl(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function $l(e){let t=Zl(e);switch(t.kind){case`directory`:return z(t.path,eu(t.projectSubPath));case`linked`:if(!B(t.path))throw new tu(t.gitPath,t.path);return z(t.path,eu(t.projectSubPath));case`malformed-pointer`:throw new tu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new nu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function eu(e){return e===``?`ok`:`ok-${Ree(e)}`}function Ree(e){let t=e.split(Uc).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=zee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function zee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var tu=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}},nu=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 Bee(e){let t;try{t=$l(e)}catch(e){if(e instanceof tu||e instanceof nu)return null;throw e}return B(z(t,`HEAD`))?t:null}function ru(e){return`refs/wip/${e}/`}function Vee(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,$n as i,$r as a,$t as o,A as s,Aa as c,Ai as l,An as u,Ar as d,At as f,B as p,Ba as m,Bi as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Cr as S,Ct as C,D as w,Da as T,Di as ee,Dn as te,Dr as ne,Dt as E,E as re,Ea as ie,Ei as ae,En as oe,Er as se,Et as ce,F as le,Fa as ue,Fi as de,Fn as D,Fr as fe,Ft as pe,G as me,Ga as he,Gi as ge,Gn as _e,Gr as ve,Gt as ye,H as be,Ha as xe,Hn as Se,Hr as Ce,Ht as we,Ia as Te,Ii as Ee,In as De,Ir as Oe,It as ke,J as Ae,Ja as je,Jn as Me,Jr as Ne,Jt as Pe,K as Fe,Kn as Ie,Kr as Le,Kt as Re,La as ze,Li as Be,Ln as Ve,Lr as He,Lt as Ue,M as We,Ma as Ge,Mi as Ke,Mn as qe,Mr as Je,Mt as Ye,N as Xe,Na as Ze,Ni as Qe,Nn as $e,Nr as et,Nt as tt,O as nt,Oa as rt,Oi as it,On as at,Or as ot,Ot as st,Pa as ct,Pi as lt,Pn as ut,Pr as dt,Pt as ft,Q as pt,Qi as mt,Qn as ht,Qr as gt,Qt as _t,R as vt,Ra as yt,Ri as bt,Rn as xt,Rr as St,Rt as Ct,S as wt,Sa as Tt,Si as Et,Sn as Dt,Sr as Ot,St as kt,T as At,Ti as jt,Tn as Mt,Tr as Nt,Tt as Pt,U as Ft,Ua as It,Ui as Lt,Un as Rt,Ur as zt,Ut as Bt,V as Vt,Va as Ht,Vi as Ut,Vn as Wt,Vr as Gt,Vt as Kt,W as qt,Wa as Jt,Wi as Yt,Wn as eee,Wr as tee,Wt as nee,X as Xt,Xi as Zt,Xn as Qt,Xr as $t,Xt as en,Y as tn,Yi as nn,Yn as rn,Yr as an,Yt as on,Z as sn,Zi as cn,Zn as ln,Zr as un,Zt as dn,_ as fn,_a as pn,_i as mn,_n as hn,_r as gn,_t as _n,a as vn,aa as yn,ai as bn,an as xn,ar as Sn,at as Cn,b as wn,ba as Tn,bi as En,bn as Dn,br as On,bt as kn,c as An,ca as jn,ci as ree,cn as iee,cr as Mn,d as Nn,da as Pn,di as Fn,dn as In,dr as Ln,dt as Rn,ea as zn,ei as Bn,en as aee,er as oee,et as Vn,f as Hn,fi as Un,fn as Wn,fr as Gn,ft as Kn,g as qn,ga as Jn,gi as Yn,gn as Xn,gr as Zn,gt as Qn,h as $n,hn as er,hr as tr,ht as nr,i as rr,ia as ir,ii as ar,in as or,ir as sr,it as cr,j as lr,ja as ur,ji as dr,jn as fr,jr as pr,jt as mr,k as hr,ka as gr,ki as _r,kn as vr,kr as yr,kt as br,l as xr,la as Sr,li as Cr,ln as wr,lr as Tr,lt as Er,m as Dr,mi as Or,mn as kr,mr as Ar,mt as jr,n as Mr,ni as Nr,nn as Pr,nr as Fr,nt as Ir,o as Lr,oa as Rr,oi as zr,on as Br,or as Vr,ot as Hr,pa as Ur,pi as Wr,pn as Gr,pr as Kr,pt as qr,q as Jr,qn as Yr,qr as Xr,qt as Zr,r as Qr,ri as $r,rn as ei,rr as ti,rt as ni,s as ri,sa as ii,si as ai,sn as see,sr as cee,t as oi,ta as si,ti as ci,tn as lee,tr as uee,tt as dee,u as li,ui,un as di,ur as fi,ut as pi,v as mi,vi as hi,vn as gi,vr as _i,vt as vi,w as fee,wa as yi,wi as bi,wn as xi,wr as Si,wt as Ci,x as wi,xa as Ti,xi as Ei,xn as Di,xr as Oi,xt as ki,y as Ai,ya as ji,yi as Mi,yn as pee,yr as Ni,yt as Pi,z as Fi,za as Ii,zi as mee,zn as Li,zr as Ri,zt as zi}from"./src-BTo9m5ju.mjs";import{$ as Bi,A as Vi,C as Hi,Ct as Ui,Dt as Wi,Et as Gi,G as Ki,H as qi,I as Ji,K as Yi,L as Xi,N as Zi,Ot as Qi,Q as $i,R as ea,S as ta,St as na,T as ra,Tt as ia,U as aa,V as oa,X as O,Y as k,Z as sa,_ as ca,_t as la,at as A,bt as ua,ct as j,dt as M,et as da,ft as fa,g as pa,h as ma,i as ha,it as N,l as ga,lt as P,m as _a,mt as va,n as ya,nt as F,ot as ba,pt as xa,q as Sa,r as Ca,rt as wa,st as Ta,t as Ea,u as Da,ut as Oa,vt as ka,w as Aa,wt as ja,xt as Ma,yt as Na,z as Pa}from"./sleep-DcENuR74.mjs";import{c as Fa,i as Ia,l as La,n as Ra,s as za}from"./esm-CItKw7Y6.mjs";import{n as Ba,t as Va}from"./md-manager-DPNbV4Up.mjs";import{A as Ha,C as Ua,D as Wa,E as Ga,N as Ka,O as qa,S as Ja,T as Ya,_ as Xa,a as Za,b as Qa,c as $a,d as eo,f as to,g as no,h as ro,i as io,j as ao,k as oo,l as so,m as co,n as lo,o as uo,p as fo,r as po,s as mo,t as ho,u as go,v as _o,w as vo,x as yo,y as bo}from"./fs-traced-vMO6kYgZ.mjs";import{D as xo,E as hee,S as So,T as gee,a as Co,b as wo,l as To,p as Eo,r as I,s as Do,x as Oo,y as ko}from"./logger-B7Z8XO-z.mjs";import{a as Ao,i as jo,o as Mo,r as No,s as Po,t as Fo}from"./git-handle-YzX39hWc.mjs";import{t as Io}from"./libesm-CG75CrN9.mjs";import{n as Lo,t as Ro}from"./build-fAc55Z_L.mjs";import{S as _ee,a as zo,c as Bo,d as Vo,f as Ho,g as Uo,h as Wo,i as Go,l as Ko,m as qo,n as Jo,r as Yo,v as Xo,x as Zo,y as Qo}from"./server-lock-BiAmhJ19.mjs";import{t as $o}from"./yazl-BafwB467.mjs";import{t as es}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as ts,c as ns,d as rs,f as is,h as as,i as os,l as ss,m as cs,n as ls,o as us,p as ds,r as fs,s as ps,t as ms,u as hs}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as gs,B as _s,C as vs,D as ys,E as bs,F as xs,H as Ss,I as Cs,L as ws,M as Ts,N as Es,O as Ds,P as Os,S as ks,T as As,V as js,_ as Ms,a as Ns,b as Ps,c as Fs,d as Is,f as Ls,g as Rs,h as zs,i as Bs,j as Vs,k as Hs,l as Us,m as Ws,n as Gs,o as Ks,p as qs,r as Js,s as Ys,t as Xs,u as Zs,v as Qs,w as $s,x as ec,y as tc,z as nc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as rc,c as ic,d as ac,i as oc,l as sc,n as cc,o as lc,r as uc,s as dc,t as fc,u as pc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as mc,r as hc,t as gc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as _c}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as vc}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as yc,t as bc}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as xc,t as Sc}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Cc,r as wc,t as Tc}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ec,t as Dc}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Oc}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as kc}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Ac}from"./wrapper-BcpqREsI.mjs";import{createRequire as jc}from"node:module";import{execFile as Mc,spawn as Nc,spawnSync as Pc}from"node:child_process";import*as Fc from"node:path";import{basename as Ic,delimiter as Lc,dirname as Rc,extname as zc,isAbsolute as Bc,join as L,normalize as Vc,posix as Hc,relative as R,resolve as z,sep as Uc,win32 as Wc}from"node:path";import*as Gc from"node:fs";import{appendFileSync as Kc,chmodSync as qc,closeSync as Jc,constants as Yc,createReadStream as Xc,createWriteStream as Zc,existsSync as B,lstatSync as Qc,mkdirSync as $c,mkdtempSync as el,openSync as tl,readFile as nl,readFileSync as V,readSync as rl,readdirSync as il,readlinkSync as al,realpathSync as ol,renameSync as sl,rmSync as cl,rmdirSync as ll,statSync as ul,unlinkSync as dl,writeFileSync as fl}from"node:fs";import{arch as pl,availableParallelism as ml,homedir as hl,hostname as gl,platform as _l,tmpdir as vl}from"node:os";import{access as yl,chmod as bl,constants as xl,lstat as Sl,readFile as Cl,readdir as wl,realpath as Tl,stat as El,writeFile as Dl}from"node:fs/promises";import{Readable as Ol,Transform as kl,Writable as Al}from"node:stream";import{URLSearchParams as jl,fileURLToPath as Ml,pathToFileURL as Nl}from"node:url";import Pl,{createHash as Fl,randomUUID as Il,webcrypto as Ll}from"node:crypto";import vee from"crypto";import{Readable as Rl}from"stream";import{Worker as yee}from"node:worker_threads";import{monitorEventLoopDelay as bee,performance as zl}from"node:perf_hooks";import{createInterface as xee}from"node:readline";import{pipeline as Bl}from"node:stream/promises";import{setTimeout as Vl}from"node:timers/promises";import{promisify as Hl}from"node:util";import{lookup as See}from"node:dns/promises";import{request as Cee}from"node:http";import{request as wee}from"node:https";import{createBrotliDecompress as Tee,createGunzip as Eee,createInflate as Dee}from"node:zlib";import{Http2ServerRequest as Ul,constants as Oee}from"http2";import{AsyncLocalStorage as kee}from"node:async_hooks";import{lookup as Aee}from"node:dns";import jee from"node:tls";var Wl=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=Bc(t)?t:z(this.gitDir,t))}catch(e){if(!Jl(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 Jl(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]}:Xl(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 Jl(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Mee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Yl(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(`..`)||Bc(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Fee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Jl(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return Jl(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 Xl(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Gl(e){return ql(z(e),``)}function Kl(e){let t=z(e),n=z(hl());if(t===n)return{kind:`absent`};let r=ql(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=Rc(i);if(e===i||e===n)return{kind:`absent`};let r=ql(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function ql(e,t){let n=L(e,`.git`),r;try{r=ul(n)}catch(e){return Jl(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Wl(`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=Bc(o)?o:z(e,o);try{if(!ul(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 Wl(`linked`,e,t,n,s)}}function Mee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Nee(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=Pee(i[1]);if(a.length>0)return a}return null}function Nee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Pee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Jl(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Yl(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Fee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Yl(t[1])?{kind:`symbolic`,target:t[1]}:null:Xl(e)?{kind:`oid`,oid:e}:null}function Xl(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Iee(e){return`git-author-${je(e.trim().toLowerCase())}`}const Lee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Zl(e){let t=Kl(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 Ql(e){let t=Zl(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function $l(e){let t=Zl(e);switch(t.kind){case`directory`:return z(t.path,eu(t.projectSubPath));case`linked`:if(!B(t.path))throw new tu(t.gitPath,t.path);return z(t.path,eu(t.projectSubPath));case`malformed-pointer`:throw new tu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new nu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function eu(e){return e===``?`ok`:`ok-${Ree(e)}`}function Ree(e){let t=e.split(Uc).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=zee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function zee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var tu=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}},nu=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 Bee(e){let t;try{t=$l(e)}catch(e){if(e instanceof tu||e instanceof nu)return null;throw e}return B(z(t,`HEAD`))?t:null}function ru(e){return`refs/wip/${e}/`}function Vee(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 iu=`ok-checkpoint-v1: `;function au(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(iu))continue;let n;try{n=JSON.parse(e.slice(18))}catch{return null}if(typeof n!=`object`||!n)return null;let r=n,i=r.kind,a=r.metadata;if(typeof a!=`object`||!a)return null;let o=typeof r.docName==`string`?r.docName:null,s=typeof r.size==`number`&&Number.isFinite(r.size)?r.size:null;if(i===`bridge-merge-loss`){let e=a;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:o,size:s,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(i===`producer-guard-loss`){let e=a;return typeof e.construct==`string`?{kind:`producer-guard-loss`,docName:o,size:s,metadata:{construct:e.construct}}:null}if(i===`observer-a-duplication`){let e=a;return typeof e.duplicatedLineCount==`number`&&Number.isFinite(e.duplicatedLineCount)?{kind:`observer-a-duplication`,docName:o,size:s,metadata:{duplicatedLineCount:e.duplicatedLineCount}}:null}if(i===`external-change-rescue`){let e=a;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:o,size:s,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}if(i===`auto-consolidation`){let e=a;return typeof e.foldedRefs==`number`&&Number.isFinite(e.foldedRefs)&&typeof e.trigger==`string`?{kind:`auto-consolidation`,docName:o,size:s,metadata:{foldedRefs:e.foldedRefs,trigger:e.trigger}}:null}return null}return null}function ou(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${iu}${JSON.stringify(t)}`}const su=`ok-actor: `;function cu(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),`${su}${JSON.stringify(i)}`}function lu(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=Hee(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 Hee(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 Uee(e){if(!e)return null;for(let t of e.split(`
4
4
  `)){let e=t.trim();if(!e.startsWith(su))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:lu(n)}return null}function uu(e){if(!e)return[];let t=[];for(let n of e.split(`
@@ -1218,7 +1218,7 @@ tags: [lore, history]
1218
1218
  `),i=n.nextFenced+(r?`
1219
1219
  `:``)+t;ox(x.dc.document,i,`agent`,void 0,C),uS(`mcp-write`),te=!0}ee=!0},x.origin)})}finally{nt?.touchMode(u,`idle`)}if(T){let e;switch(T.kind){case`invalid_value`:e={[T.key]:T.reason};break;case`reserved_key`:e={[T.key]:`'${T.key}' is reserved`};break;case`unknown_key`:e={[T.key]:`'${T.key}' is not a recognized key`};break;case`duplicate_target`:e={[T.key]:`'${T.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${T.expected.join(`, `)}; got: ${T.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${T.bytes} > ${T.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${T.reason}`};break;case`invalid_path`:e={[T.path.map(String).join(`.`)||`__path__`]:T.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(T)})`}}G(o,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(sk(l,u,d,f,void 0,pi({clientName:p,clientVersion:m,label:h}),b),_x(),wi(v),te){let e=await rr(l);if(e?.kind===`failure`){ir(o,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){ar(o,`frontmatter-patch`);return}}nr(l,`frontmatter-patch`)}Ze?.setFocus(u,{agentName:d,currentDoc:l,writeKind:`write`,ts:Date.now()}),rt?.();let E=Yn(l),re=Qn();re===0&&JU().add(1,{"shadow.writer":`agent`,"agent.type":Jm(p)});let ie=cr(S);wr(l,x.dc.document.getText(`source`).toString());let ae=hr();ae.add(l);let oe=OI(x.dc.document.getText(`source`).toString(),l,ae,gr);q(o,200,Ne,{timestamp:w,subscriberCount:E,systemSubscriberCount:re,appliedKeys:ne,...y?{summary:y}:{},...ie?{warning:ie,warnings:[ie]}:{},brokenLinks:oe},{handler:`frontmatter-patch`})}catch(e){if(e instanceof GS){G(o,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:qx(i)},`[frontmatter-patch] handler failed`),G(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ui(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 Wi=J(D,async(e,t)=>{try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!vG(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let i=Jn(r);if(Dx(i)||Ox(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`document-read`});return}let a=n.documents.get(i);if(a){q(t,200,d,{docName:i,content:a.getText(`source`).toString(),lifecycle:Ui(a)},{handler:`document-read`});return}if(!B(GW(s,`file`,i))){G(t,404,`urn:ok:error:doc-not-found`,`Document not found: ${i}.`,{handler:`document-read`});return}let o=await n.openDirectConnection(i);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,d,{docName:i,content:e.getText(`source`).toString(),lifecycle:Ui(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}),Gi=J(D,async(e,t)=>{try{Vt&&await Vt.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{TW(s,r)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(i&&Tt&&FW(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=Qx(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=OW(),n=IW({contentDir:s,contentFilter:Tt,dirFilter:r,maxEntries:t,maxDepth:o,showOk:a,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await i(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&Y.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await i(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\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&&Tt){let e=`showAll:${o===1?`d1:`:``}${a?`ok:`:``}${r??``}`,n=gn.get(e);if(!n){let t=new AbortController,i=(async()=>{let e=[],n=OW(),{truncated:i}=await LW({contentDir:s,contentFilter:Tt,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 c=n;gn.set(e,c),i.finally(()=>{gn.get(e)===c&&gn.delete(e)})}let i=n;i.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--i.waiters,i.waiters<=0&&(i.controller.abort(),gn.get(e)===i&&gn.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await i.promise;if(c)return;q(t,200,yr,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)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`,l)}return}let c=p(),l=h(),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=jn(c);vn?.signature!==e&&(vn={signature:e,assets:tae({contentDir:s,fileIndex:c,readMarkdown:e=>{try{return V(e,`utf-8`)}catch{return null}},isExcluded:Tt?e=>Tt.isPathIgnored(e):void 0})}),f=vn?.assets??[]}catch(e){vn=null,Y.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let m=new Set;for(let e of f)r&&!e.path.startsWith(`${r}/`)&&e.path!==r||(m.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 l){if(t.kind===`markdown`){if(r&&!e.startsWith(`${r}/`)&&e!==r)continue;let n=Hx(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=kE(R(s,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}/`))&&!m.has(e)){let n=EW(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}/`))||m.has(n))continue;let i=kE(R(s,t.canonicalPath)),a=EW(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 g=fe?.()??new Map;if(g.size>0){let e=e=>!r||e===r||e.startsWith(`${r}/`),t=new Map;for(let[e,n]of g){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?kE(R(s,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:kE(R(s,t.canonicalPath))})});for(let[e,t]of l)n(e,n=>{let r=kE(R(s,t.canonicalPath));if(t.kind===`markdown`)d.push({kind:`document`,docName:n,docExt:Hx(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=EW(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,yr,{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}),Ki=J(D,async(e,t)=>{if(!Le){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(!vG(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}q(t,200,ot,{docName:n,backlinks:Le.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:zn(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}),qi=J(D,async(e,t)=>{if(!Le){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||!vG(t)||(r[t]=Le.getBacklinkCount(t))}q(t,200,ne,{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}),Zi=J(D,async(e,t)=>{if(!Le){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(!vG(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=hr();q(t,200,pr,{docName:n,forwardLinks:Le.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Bn(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}),Qi=J(D,async(e,t)=>{if(!Le){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&&!vG(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}=Le.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=Le.getLinkGraph());let s=hr();q(t,200,Je,{nodes:a.map(e=>{if(e.kind===`doc`){let t=Wn(e.docName,s);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Bn(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}),$i=J(D,async(e,t)=>{if(!Le){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(!Sr(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}q(t,200,tr,{orphans:Le.getOrphans([...p().keys()],n).map(e=>({docName:e,title:zn(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}),ta=J(D,async(e,t)=>{if(!Le){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=hr();q(t,200,Ar,{hubs:Le.getHubs(i).map(e=>({docName:e.docName,title:Bn(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}),na=J(D,async(e,t)=>{if(!Le){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||!vG(e))){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>Jn(e)))]:void 0;q(t,200,Kr,{deadLinks:Le.getDeadLinks(hr(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:zn(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}),ia=J(Oe,async(r,i,o)=>{try{let{find:r,replace:c,offset:l}=o,u=UW(o.docName,i,`agent-patch`);if(u===null)return;let d=Jn(u),{agentId:f,agentName:p,colorSeed:m,clientName:h,clientVersion:g,label:_}=di(o);if(ZU(r)){XU().add(1,{result:`rejected`}),G(i,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(Dx(d)||Ox(d)){G(i,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`agent-patch`});return}let v=DE(o.summary),y=await a.getSession(d,f,{displayName:p,colorSeed:m,clientName:h}),b=PL(t,n,d,s,e.resolveEmbed),x=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,S;{let{frontmatter:e,body:t}=cn(y.dc.document.getText(`source`).toString()),n=Zt(e,t),i=l==null?n.indexOf(r):n.slice(l,l+r.length)===r?l:-1;if(i!==-1&&i>=e.length){let e=n.slice(0,i)+c+n.slice(i+r.length);S=await FS(y.dc.document,cn(e).body,`patch`,x)}}let C=new Date().toISOString(),w=!1,T=!1,ee=!1,te;try{let e=Nn(h),t=An[e]??xr(m??f);if(nt?.setPresence(f,{displayName:p,icon:e,color:t,currentDoc:d,mode:`writing`,ts:Date.now()}),CE(y.dc.document.getText(`source`),f,m,h),y.dc.document.transact(()=>{let{frontmatter:e,body:t}=cn(y.dc.document.getText(`source`).toString()),n=Zt(e,t),i=l==null?n.indexOf(r):n.slice(l,l+r.length)===r?l:-1;if(i===-1){l==null?w=!0:T=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":d,findLength:r.length,replaceLength:c.length,hadOffset:l!=null})),mre();return}if(i<e.length){ee=!0;return}let{body:a}=cn(n.slice(0,i)+c+n.slice(i+r.length)),o=LS(y.dc.document);te=IS(y.dc.document,a,`patch`,x,S);let s=Jt(o,LS(y.dc.document))??void 0;y.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Patched (${p}): ${r.slice(0,50)}`,...s===void 0?{}:{changedBlocks:s}})},y.origin),te!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":d,position:`patch`,intendedBytes:te.intendedBytes,actualBytes:te.actualBytes,byteDelta:te.byteDelta,"agent.id":f,"agent.client_name":h})),!w&&!T&&!ee){let{stored:e}=mi(v);sk(d,f,p,m,void 0,pi({clientName:h,clientVersion:g,label:_}),e),_x(),wi(v),cW(`agent-patch`,te)}}finally{nt?.touchMode(f,`idle`)}if(T){G(i,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(w){G(i,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ee){XU().add(1,{result:`rejected`}),G(i,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 ne=await rr(d);if(ne?.kind===`failure`){ir(i,ne.failure,`agent-patch`);return}if(ne?.kind===`divergence`){ar(i,`agent-patch`);return}nr(d,`agent-patch`),Ze?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`edit`,ts:Date.now()}),rt?.();let E=Yn(d),re=Qn();re===0&&JU().add(1,{"shadow.writer":`agent`,"agent.type":Jm(h)});let{response:ie}=mi(v),ae=y.dc.document.getText(`source`).toString();wr(d,ae);let oe=await ZN(ae,d),se=hr();se.add(d);let ce=OI(ae,d,se,gr),le=cr(b),ue=te===void 0?void 0:aS(te),de=[...ue?[ue]:[],...le?[le]:[],...oe??[],...await Gc(y.dc.document.getText(`source`).toString(),d)];q(i,200,He,{timestamp:C,subscriberCount:E,systemSubscriberCount:re,...ie?{summary:ie}:{},...ue?{warning:ue}:le?{warning:le}:{},...de.length>0?{warnings:de}:{},brokenLinks:ce},{handler:`agent-patch`})}catch(e){if(e instanceof tS){nS(i,e,`agent-patch`);return}if(e instanceof oS){cS(i,e,`agent-patch`);return}if(e instanceof GS){G(i,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:qx(r)},`[agent-patch] handler failed`),G(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),aa=J(St,async(t,n,r)=>{try{let t=UW(r.docName,n,`agent-undo`);if(t===null)return;let i=Jn(t),{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=di(r);if(Dx(i)||Ox(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`,!a.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 a.getSession(i,f),g=!1;try{let t=Nn(l),n=An[t]??xr(c??o);nt?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),g=zS(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,m),g&&sk(i,f,s,c,void 0,pi({clientName:l,clientVersion:u,label:d}))}finally{nt?.touchMode(o,`idle`)}if(g){let e=await rr(i);if(e?.kind===`failure`){ir(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){ar(n,`agent-undo`);return}$n(i,`agent-undo`)}Ze?.setFocus(f,{agentName:f,currentDoc:i,writeKind:`undo`,ts:Date.now()}),q(n,200,Ri,{docName:i,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof tS){nS(n,e,`agent-undo`);return}Y.error({err:e,requestId:qx(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`}),oa=J(D,async(e,t)=>{try{let n=Gm(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,eee,Iie(a,n),{handler:`agent-activity`})}catch(n){Y.error({err:n,requestId:qx(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(D,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=Gm(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),o=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(!vG(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=Jn(i);if(Dx(s)||Ox(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!o||Number.isNaN(Number(o))){G(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(o);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=a.getLiveSession(s,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}=Nie(u.undoStack,c,d,s);q(t,200,_e,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){Y.error({err:n,requestId:qx(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(D,async(e,t)=>{try{await xe?.(),q(t,200,i,{},{handler:`test-flush-git`})}catch(n){Y.error({err:n,requestId:qx(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(D,async(e,t)=>{try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=Jn(r.searchParams.get(`docName`)??`test-doc`),o;try{o=jE(i,s)}catch(e){Y.error({err:e,docName:i},`[test-reset] safeContentPath rejected docName`),G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await a.closeAll(i),n.closeConnections(i);let c=`onStoreDocument-${i}`;n.debouncer.isDebounced(c)&&await n.debouncer.executeNow(c);let l=n.documents.get(i);if(l&&await(Ft??n.unloadDocument.bind(n))(l),fl(o,``,`utf-8`),Le&&(Le.deleteDocument(i),Le.saveToDisk().catch(e=>{Y.warn({docName:i,err:e},`[backlinks] Failed to persist cache after test-reset for ${i}`)}),We?.(`backlinks`),We?.(`graph`)),r.searchParams.get(`reset-okignore`)!==`false`)try{let e=z(s,`.okignore`),t=n.documents.get(T);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},$E)}B(e)&&fl(e,``,`utf-8`),Tt&&await Tt.rebuildIgnorePatterns()}catch(e){Y.warn({err:e},`[test-reset] okignore reset partial failure`)}We?.(`files`),q(t,200,Fr,{},{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}),ua=J(D,async(e,t)=>{try{if(!Le){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await Le.rebuildFromDisk(),await Le.ingestGlobalSkillBundles([z(Ss,`.ok`,`skills`)]),Le.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist cache after test-rescan-backlinks`)}),We?.(`backlinks`),We?.(`graph`),q(t,200,oee,{},{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}),j=J(D,async(e,t)=>{try{if(!me){G(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await me(),We?.(`files`),q(t,200,uee,{},{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}),M=J(S,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=di(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=je?.()??`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 ZI(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[fL],l=!0}let d=Ie??`.`,f=DE(typeof n.summary==`string`?n.summary:void 0),p=await DL(o,d,c,u,f.kind===`value`?f.value:void 0,l?{includeUpstream:!1}:void 0);I(`history`).info({checkpointRef:p.checkpointRef},`checkpoint`);try{await nH(o,RV(o.gitDir))}catch(e){Y.warn({err:e},`[rename-log] post-saveVersion GC failed`)}q(t,200,Si,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(n){Y.error({err:n,requestId:qx(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`}),da=J(D,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 xe?.();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`)??je?.()??`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=as(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}=_n.run(u,()=>WU(n,e.folderRel,Ie??`.`,{branch:o,limit:s,offset:l}));f&&TU(`folder`),q(t,200,On,{...await d},{handler:`history`});return}let s=Ie??`.`,c=mW(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}=_n.run(_,()=>UU(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&TU(`doc`);let a=await e,c=Date.now()-v;I(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),q(t,200,On,{...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 fa(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=Ie??`.`,o=mW(i,a);if(`error`in o){G(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=YI(r),c=je?.()??`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 sH(r,i,n,c,RV(r.gitDir),e=>{let t=mW(e,a);return`error`in t?`${e}.md`:t.path},HV());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,Oi,{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 pa=J(g,async(t,r,i)=>{let a=FL(i,ht);if(a.kind===`invalid-summary`){G(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=n.documents.get(i.docName);if(o&&$x(o)){nS(r,new tS({file:Ux(i.docName)}),`rollback`);return}let s=be?.current;if(!s){G(r,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=i,u=Ie??`.`,d=mW(c,u);if(`error`in d){G(r,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=YI(s),p=Date.now();try{let t=RV(s.gitDir),i=HV(),o=await sH(s,c,l,je?.()??`main`,t,e=>{let t=mW(e,u);return`error`in t?`${e}.md`:t.path},i);if(o===null){G(r,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 _L(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=n.documents.get(c);if(!h){G(r,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 MS(d,g),v;h.transact(()=>{sx(h,d,g,_),v=iS(h.getText(`source`).toString(),d,`rollback`)},dW),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":a.kind,...a.kind===`agent`||a.kind===`principal`?{"actor.writer_id":a.writerId}:{}})),cW(`rollback`,v);let y;switch(a.kind){case`agent`:{let e=l.slice(0,8),t=a.summary.kind===`value`,n=t?a.summary:DE(`Restored to ${e}`),r=mi(n);y=t||!r.response?r.response:vi(r.response),sk(c,a.writerId,a.displayName,a.colorSeed,mu(c,l),a.actor,r.stored),_x(),wi(n,!t);break}case`principal`:{let e=mi(a.summary);y=e.response,sk(c,a.writerId,a.displayName,a.colorSeed,mu(c,l),a.actor,e.stored),wi(a.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(a.kind)}`)}$U().add(1,{kind:`rollback`,attribution_kind:a.kind});let b=await rr(c);if(b?.kind===`failure`){ir(r,b.failure,`rollback`);return}if(b?.kind===`divergence`){ar(r,`rollback`);return}$n(c,`rollback`);let x=Date.now()-p;I(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),a.kind===`agent`&&Ze?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:aS(v);q(r,200,Wt,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){G(r,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),ma=J(D,async(e,t)=>{try{q(t,200,Qt,Ex(),{handler:`metrics-reconciliation`})}catch(n){Y.error({err:n,requestId:qx(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}),ha=J(D,async(e,t)=>{try{q(t,200,rn,hi(),{handler:`metrics-parse-health`})}catch(n){Y.error({err:n,requestId:qx(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}),ga=J(D,async(e,n)=>{try{Vt&&await Vt.catch(e=>{Y.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=Fe?.(),i=Qoe();q(n,200,bi,{serverInstanceId:c,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}),_a=A({agents:k(A({id:P(),name:P(),version:P(),description:P().optional(),license:P().optional(),iconUrl:P().optional(),website:P().optional(),source:Yi([`registry`,`custom`]),supported:O(),featured:O(),harness:A({cli:Yi([`claude`,`codex`,`cursor`,`opencode`,`pi`]),availability:Yi([`present`,`not-found`,`unknown`])}).optional()})),stale:O(),maxThreads:N()}),va=J(D,async(e,t)=>{if(vt===void 0){G(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=Tu(),{agents:n,stale:r}=await vt.getCatalog(),i=await yt?.()??[],a=await wt();q(t,200,_a,{agents:[...n.map(t=>{let n=SE[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:xu.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 ya(e,t){if(!zB(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!BB(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=ht?.()??null;if(!n){G(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}q(t,200,Et,n,{handler:`principal`})}async function F(e,t){if(!zB(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!BB(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=nt?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);q(t,200,Me,{presence:r},{handler:`metrics-agent-presence`})}catch(n){Y.error({err:n,requestId:qx(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 ba(e,t){if(!zB(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!BB(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 r;try{let e=[];for(let[t,i]of n.documents){if(Dx(t)||Ox(t)||!i.share.has(`agent-effects`))continue;r=t;let n=i.getMap(`agent-effects`);if(n.size===0)continue;let a=[...n.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,Yr,{effects:e},{handler:`metrics-agent-effects`})}catch(e){Y.error({err:e,"doc.name":r},`[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 xa(e,t){if(!zB(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!BB(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,ln,{decisions:ZL().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:qx(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 Sa(e,t){if(!zB(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!BB(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=_k.read();q(t,200,se,{entries:n,count:n.length,detection:Ck(n[0])},{handler:`embed-detect`})}async function Ca(e,t){if(!zB(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!BB(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(s),r=n,i=!0;try{r=ol(n)}catch(e){let r=Zo(e);if(r===`ENOENT`)Y.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),i=!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,Nt,{contentDir:r,pathSeparator:Uc,symlinkResolved:i},{handler:`workspace`})}let wa=J(D,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=nae(n),i=zc(n).slice(1).toLowerCase();if(!r||!Vi.has(i)){G(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let a=ol(s),o=z(a,n),c;try{c=ol(o)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!ME(c,a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let l;try{l=ul(c)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!l.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let u=JE(a,c);if(u!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(Tt?.isPathIgnored(u)){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let d=Pa.has(i),f={"Content-Type":r,"Content-Length":String(l.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":Ji.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`]=ea),t.writeHead(200,f);try{await Bl(Xc(c),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}),Ta=1048576,Ea=J(D,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=ol(s),i=z(r,n),a;try{a=ol(i)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!ME(a,r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let o;try{o=ul(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(JE(r,a)!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(o.size>Ta){G(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ta}-byte text-viewer cap.`,{handler:`asset-text`});return}let c=(await Cl(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(c)}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}),Da=J(D,async(e,t)=>{try{if(!be?.current){q(t,200,Ot,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=z(be.current.gitDir,`rescue`);if(B(r))try{let t=il(r).filter(e=>Fx(e));for(let i of t){let t=z(r,i),a=ul(t);if(e-a.mtimeMs>864e5){try{dl(t)}catch(e){Y.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:Lx(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=je?.()??`main`,t=await bL(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,Ot,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}),Oa=J(vr,async(e,t,n)=>{try{let e=FL(n,ht);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(!Fx(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(s),a=z(i,r);if(!AE(a,i)){G(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let o=Lx(r);if(Dx(o)||Ox(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`});return}if(zW(r)||Te(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 c=typeof n.template==`string`?n.template.trim():``,l=``,d;if(c.length>0){if(!/^[A-Za-z0-9_-]+$/.test(c)){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=KD(i,n),o=a.find(e=>e.name===c);if(!o){let e=a.length===0?`(none)`:a.map(e=>`"${e.name}" (${e.scope})`).join(`, `);G(t,400,`urn:ok:error:invalid-request`,`Template "${c}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let s=z(i,o.path),u;try{u=V(s,`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=qn(u),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;l=WO(f,{date:KO(),user:p}),d=o.scope}$c(Rc(a),{recursive:!0});try{fl(a,l,{encoding:`utf-8`,flag:`wx`})}catch(e){if(XW(e)){G(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let f=Lx(r);switch(Ut?.delete(f),Tt&&Tt.incrementMdDir(Rc(f)),HL(a,WL(l)),e.kind){case`agent`:case`principal`:sk(f,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)}`)}y?.({kind:`create`,path:a,docName:f,content:l}),Le&&(Le.updateDocumentFromMarkdown(f,l),Le.saveToDisk().catch(e=>{Y.warn({docName:f,err:e},`[backlinks] Failed to persist create-page cache for ${f}`)}),We?.(`backlinks`),We?.(`graph`)),We?.(`files`),d!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:c,templateScope:d,docName:f})),q(t,200,u,{docName:f},{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`}),ka=J(te,async(e,t,n)=>{try{if(FL(n,ht).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(!RW(e)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(zW(e)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(Tt?.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=GW(s,`folder`,e);if(B(r)){G(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}so(r,{recursive:!0}),Cn(e),We?.(`files`),q(t,200,at,{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`}),ja=J($e,async(e,t,r)=>{try{let e=FL(r,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:i}=r,a=r.path,o=i===`file`?Lx(a):a;if(!RW(a)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(zW(a)||i===`file`&&(Dx(o)||Ox(o))||i===`folder`&&BW(a)){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}i===`file`&&sG(s,a);let c=GW(s,i,a);if(!B(c)){if(i===`file`){let e=GW(s,`folder`,a);if(B(e)&&ul(e).isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${i}.`,{handler:`duplicate-path`});return}}G(t,404,`urn:ok:error:doc-not-found`,`${i} does not exist.`,{handler:`duplicate-path`});return}let l=ul(c);if(i===`file`&&!l.isFile()||i===`folder`&&!l.isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${i}.`,{handler:`duplicate-path`});return}let u=i===`file`?[tG(s,a)]:ii(GW(s,`folder`,a)),d=it?.(),f=new Set(d?d.getConflicts().map(e=>e.file):[]);for(let e of u){let r=e,i=n.documents.get(r),a=Ux(r),o=i!==void 0&&$x(i),s=f.has(a);if(o||s){nS(t,new tS({file:a}),`duplicate-path`);return}}let p,m=[];if(i===`file`){let e=zc(c);if(p=rG(s,o).docName,Dx(p)||Ox(p)||Tt?.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=nG(s,p,e),r=V(c,`utf-8`),i=Rc(n),a=B(i);try{so(i,{recursive:!0}),_o(n,r,{encoding:`utf-8`,flag:`wx`})}catch(e){if(XW(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{co(i)}catch(e){let t=Zo(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&Y.warn({destinationDir:i,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{Vx(p,e),Ut?.delete(p),Tt&&(Tt.incrementMdDir(Rc(p)),l=!0),HL(n,WL(r)),y?.({kind:`create`,path:n,docName:p,content:r}),Le?.updateDocumentFromMarkdown(p,r),m=[p]}catch(e){try{fo(n,{force:!0})}catch(e){Y.warn({destinationPath:n,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw Wx(p),Tt&&l&&Tt.decrementMdDir(Rc(p)),y?.({kind:`delete`,path:n,docName:p}),e}}else{if(p=iG(s,a).folderPath,Tt?.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=GW(s,`folder`,p);try{uo(c,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(XW(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 oG(s,p))Cn(e);let e=aG(s,p);m=e.map(e=>e.docName);for(let t of e){let e=zc(t.fullPath);Vx(Lx(t.docName),e),Ut?.delete(t.docName),Tt&&Tt.incrementMdDir(Rc(t.docName)),HL(t.fullPath,WL(t.content)),y?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),Le?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{fo(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)sk(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)}`)}Le&&m.length>0&&(Le.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist duplicate-path cache`)}),We?.(`backlinks`),We?.(`graph`)),We?.(`files`),q(t,200,ut,{kind:i,path:p,duplicatedDocNames:m},{handler:`duplicate-path`})}catch(e){if(e instanceof YW){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=ZW(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`}),Ma=J(D,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(!vG(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=Rn(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,De,{docName:n,headings:_G(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}),Na=J(xt,async(e,t,r)=>{try{let e=FL(r,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:i,fromPath:a,toPath:o}=r;if(!RW(a)||!RW(o)){G(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(i===`file`&&(Dx(a)||Dx(o)||Ox(a)||Ox(o))){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(zW(a)||zW(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(a===o){q(t,200,Li,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let c=i===`asset`&&Fx(a)&&Fx(o)?`file`:i;if(c===`asset`){let n;try{n=Fx(a)&&!Fx(o)?await ci(a,o):await si(a,o)}catch(e){if(e instanceof tS){nS(t,e,`rename-path`);return}let{status:n,type:r,error:i}=jr(e);G(t,n,r,i,{handler:`rename-path`,cause:e});return}n.renamedAssets.length>0&&Pn();let r;if(n.renamedAssets.length>0&&n.rewrittenDocs.length>0){let t=`Renamed asset ${a} → ${o}`;r=Ti(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{Y.debug({kind:`asset`,fromPath:a,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($U().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Ae)try{await Ae()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}q(t,200,Li,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}c===`file`&&sG(s,a);let l=c===`file`?[tG(s,a)]:ii(GW(s,`folder`,a)),u=it?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of l){let r=e,i=n.documents.get(r),a=Ux(r),o=i!==void 0&&$x(i),s=d.has(a);if(o||s){nS(t,new tS({file:a}),`rename-path`);return}}if(Tt){let e=Fx(a)?zc(a):Hx(a);if(c===`file`?Tt.isExcluded(Fx(o)?o:`${o}${e}`):Tt.isDirExcluded(o)){G(t,400,`urn:ok:error:invalid-request`,`Destination ${c===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let f=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,p;try{p=await li(a,o,c,f?{actor:f}:{})}catch(e){if(e instanceof Gj){G(t,409,`urn:ok:error:doc-already-exists`,Or(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,Li,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&Pn();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=Ti(e,`Renamed ${a} → ${o}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:hu(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{Y.debug({kind:i,fromPath:a,toPath:o,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),$U().add(1,{kind:`rename-${c}`,attribution_kind:e.kind}),Ae)try{await Ae()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}q(t,200,Li,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=jr(e);G(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Ra=J(fr,async(e,t,r)=>{try{di(r);let{kind:e,path:i}=r;if(!RW(i)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?ri(i):{path:i,ambiguous:!1};if(a.ambiguous){G(t,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=a.path,c=e===`asset`&&Fx(o)?`file`:e;if(c===`file`&&sG(s,o),zW(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let l=c===`asset`?GW(s,`folder`,o):GW(s,c,o);if(!B(l)){G(t,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`});return}let u=ul(l);if(c===`file`&&!u.isFile()||c===`asset`&&!u.isFile()||c===`folder`&&!u.isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`});return}let d=c===`asset`?[]:c===`file`?[tG(s,o)]:ii(GW(s,`folder`,o)),f=it?.(),p=new Set(f?f.getConflicts().map(e=>e.file):[]);for(let e of d){let r=e,i=n.documents.get(r),a=Ux(r),o=i!==void 0&&$x(i),s=p.has(a);if(o||s){nS(t,new tS({file:a}),`delete-path`);return}}if(await Mr(d,`deleted-upstream`),Ut)for(let e of d)Dx(e)||Ox(e)||(Ut.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));c===`file`||c===`asset`?no(l):(fo(l,{recursive:!0,force:!1}),wn(o)),Pn();for(let e of d)y?.({kind:`delete`,path:z(s,Ux(e)),docName:e});We?.(`files`),q(t,200,qe,{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`}),Ba=J(Se,async(e,t,n)=>Ya(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":lo(n.path),"ok.cleanup.path.role":ho(n.path)}},async()=>{try{if(FL(n,ht).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(!RW(r)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&Fx(r)?`file`:e,a=Lx(r);i===`file`&&sG(s,r);let o=i===`folder`&&BW(r);if(i===`file`&&(Dx(a)||Ox(a))||o||zW(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(i===`asset`){Pn(),We?.(`files`),q(t,200,Rt,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let c=p(),l=i===`file`?c.has(a)?[a]:[]:VW(c,i,r);if(Pn(),l.length===0){q(t,200,Rt,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Mr(l,`deleted-upstream`),Ut)for(let e of l)Dx(e)||Ox(e)||(Ut.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of l)y?.({kind:`delete`,path:z(s,Ux(e)),docName:e});i===`folder`&&wn(r),We?.(`files`),q(t,200,Rt,{deletedDocNames:l},{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`}),Va=J(D,async(e,t)=>{try{let e=p(),n=[];for(let[t,r]of e){let e=Hx(t),i,a;if(r.title!==void 0)i=r.title,a=r.icon;else{i=t;try{let n=V(z(s,`${t}${e}`),`utf-8`);i=iP(n,t),a=aP(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,Ve,{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}),Ha=J(D,async(e,t)=>{try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!vG(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(Dx(r)||Ox(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`suggest-links`});return}q(t,200,Zn,await _U({hocuspocus:n,fileIndex:p(),docName:r}),{handler:`suggest-links`})}catch(e){if(e instanceof XH){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 Ua(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 wW(e,pt??s)}catch(e){if(e instanceof eI){G(t,tI(e.reason),e.reason,rI(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:c,placement:l}=n,u=()=>{if(B(i))try{dl(i)}catch{}},d=NA(ee,{parentDocName:c,placement:l||void 0},t,{handler:`upload-asset`});if(!d.ok){u();return}let{parentDocName:f,placement:p}=d.value,{agentId:h,agentName:g}=di(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(s),v;try{v=p===`parent-dir`?`./`:m?.()??`./`}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(!Aa(v)){u(),G(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let y=yW(f,ra(v),_);if(!ME(y,_)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{WW(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{$c(y,{recursive:!0})}catch(e){if(!XW(e)){u();let n=nI(e);G(t,tI(n),n,rI(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=ol(y),n;try{n=ol(_)}catch{n=_}if(!ME(e,n)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(Zo(e)!==`ENOENT`){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let b=bW(i,4100),x=await bE(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 CW(y,a,o);if(n){u();let r=kE(R(s,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!0,mime:S??null,size:o,destPath:r,httpStatus:200},`[upload] dedup hit`),q(t,200,ae,{src:n,path:r,deduped:!0},{handler:`upload-asset`});return}}let w;if(!r||r===`upload`||hW.test(r)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=r?zc(r).slice(1):``,n=C??t??``;w=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else w=vW(r);try{let n=zoe(i,y,w),r=kE(R(s,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!1,mime:S??null,size:o,destPath:r,httpStatus:200},`[upload] write ok`),q(t,200,ae,{src:n,path:r,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof eI?n.reason:`urn:ok:error:storage-error`;Y.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:qx(e),agentId:h,agentName:g,filename:w,size:o,reason:r,httpStatus:tI(r),err:n},`[upload] write failed`),G(t,tI(r),r,rI(r),{handler:`upload-asset`,cause:n})}}let Wa=`/api/local-op/clone`,Ka=`/api/local-op/ok-init`,qa=600*1e3,Ja={stdio:[`ignore`,`ignore`,`pipe`]},Xa={stdio:[`ignore`,`pipe`,`pipe`]},Za={stdio:`ignore`},$a=`local-op-clone`,eo=J(Ei,to,{handler:$a,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:$a})});async function to(e,t,n){let{url:r,dir:i,branch:a}=n;if(!iB(r)){G(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:$a,cause:Error(`url=${r}`)});return}if(!cB(i)){G(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:$a,cause:Error(`dir=${i}`)});return}if(!mn.tryAcquire(Wa)){G(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:$a,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=Qx(t,$a),s=null,c=DB({cliArgs:ct,url:r,dir:i,branch:a,timeoutMs:qa,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&Y.warn({stderr:SP(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=xB(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(SP(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 ro(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:$a},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),mn.release(Wa)}})(),t.on(`close`,()=>{c.cancel()})}async function ro(e,t){let n=z(aB(e)),r=ZE(n),i=QF(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=ct,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=Nc(a,s(e),hA({...Ja,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 Vl(500);let t=QF(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=Go(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=Go(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 io=`local-op-ok-init`,ao=J(Ln,async(e,t,n)=>{let{projectPath:r}=n;if(!Bc(r)){G(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:io,cause:Error(`projectPath=${r}`)});return}let i;try{i=ol(r)}catch(e){q(t,200,Gn,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:io});return}if(!cB(i)){G(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:io,cause:Error(`projectPath=${r}`)});return}let a=Zl(i).kind;if(a!==`directory`&&a!==`linked`){Y.warn({project:Ic(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${Ic(i)} result=not-a-git-worktree kind=${a}`),q(t,200,Gn,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:io});return}if(wR(i)){Y.warn({project:Ic(i),result:`already-initialized`},`[ok-init] action=init project=${Ic(i)} result=already-initialized`),q(t,200,Gn,{ok:!0,projectPath:i},{handler:io});return}if(!mn.tryAcquire(Ka)){G(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:io,extraHeaders:{"Retry-After":`2`}});return}try{await jo(async()=>{tz(i)}),Y.warn({project:Ic(i),result:`success`},`[ok-init] action=init project=${Ic(i)} result=success`),q(t,200,Gn,{ok:!0,projectPath:i},{handler:io})}catch(e){let n=e instanceof Error?e.message:String(e);Y.warn({project:Ic(i),result:`failed`,reason:n},`[ok-init] action=init project=${Ic(i)} result=failed reason=${n}`),q(t,200,Gn,{ok:!1,reason:`init-failed`,message:n},{handler:io})}finally{mn.release(Ka)}},{handler:io,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:io})}),oo=`/api/local-op/auth/status`,po=`/api/local-op/auth/repos`,mo=`/api/local-op/auth/signout`,go=`/api/local-op/auth/pat`,vo=()=>fP(pt??s),yo={current:null},bo={current:null};function Co(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!mn.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=Qx(t,n),l=s(e=>{if(e.type===`error`){c(500,`urn:ok:error:auth-failed`,o,{cause:e.message?Error(e.message):void 0});return}if(uW(e,it),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}});i.current=l;let u=()=>{l.cancel(),i.current===l&&(i.current=null,mn.release(r))};t.on(`close`,u),l.done.finally(()=>{if(t.off(`close`,u),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===l&&(i.current=null,mn.release(r))})}let To=`local-op-auth-login`,Eo=J(sr,Do,{handler:To,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:To})});async function Do(e,t,n){let r=n.host??vo();Co({res:t,handler:To,guardKey:`/api/local-op/auth/login`,inFlight:yo,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>hB({cliArgs:ct,host:r,timeoutMs:qa,onEvent:e})})}let ko=`local-op-auth-gh-login`,Mo=J(sr,async(e,t,n)=>{let r=n.host??vo(),i=await FB();if(i===null){G(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:ko});return}Co({res:t,handler:ko,guardKey:`/api/local-op/auth/gh-login`,inFlight:bo,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>RB({host:r,ghPath:i,timeoutMs:qa,onEvent:e})})},{handler:ko,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:ko})}),No=`local-op-auth-status`,Po=J(sr,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(oo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:No,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ct,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=Nc(e,i,hA({...Xa,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(`
1220
1220
  `).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 FB()!==null;o===null?q(t,200,Mn,{authenticated:!1,ghAvailable:s},{handler:No}):q(t,200,Mn,{...o,ghAvailable:s},{handler:No})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:No,cause:e})}finally{mn.release(oo)}},{handler:No,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:No})}),Fo=`local-op-auth-pat`,Io=J(Sn,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(go)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:Fo,extraHeaders:{"Retry-After":`5`}});return}try{let e=await gB({cliArgs:ct,host:r,token:n.token});e.ok?(lW(it),q(t,200,Vr,{host:e.host,login:e.login},{handler:Fo})):G(t,400,`urn:ok:error:auth-failed`,e.error,{handler:Fo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:Fo,cause:e})}finally{mn.release(go)}},{handler:Fo,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Fo})}),Lo=`local-op-auth-repos`,Ro=J(sr,zo,{handler:Lo,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Lo})});async function zo(e,t,n){let r=n.host??vo();if(!mn.tryAcquire(po)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Lo,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=Qx(t,Lo),[a,...o]=ct,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=Nc(a,s,hA({...Xa,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},qa);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
1221
- `);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{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(),mn.release(po))}),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()),mn.release(po))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),mn.release(po))})}let Bo=`local-op-auth-signout`,Vo=J(sr,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(mo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Bo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ct,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=Nc(e,i,hA({...Za,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,ti,{},{handler:Bo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Bo,cause:e})}finally{mn.release(mo)}},{handler:Bo,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Bo})}),Ho=`/api/local-op/auth/set-identity`,Uo=`local-op-auth-set-identity`,Wo=J(cee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!pt){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Uo});return}if(!mn.tryAcquire(Ho)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Uo,extraHeaders:{"Retry-After":`5`}});return}try{HR(pt,r,i),it?.()?.refreshIdentity().catch(()=>{}),q(t,200,ti,{},{handler:Uo})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Uo,cause:e})}finally{mn.release(Ho)}},{handler:Uo,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Uo})});async function Ko(e,t){if(dB(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=it?.();if(!e){q(t,200,xi,{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,xi,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 qo=J(Mt,async(e,t,n)=>{let r=it?.();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,oe,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:`sync-trigger`})?it?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Jo(e,t){if(dB(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=it?.();q(t,200,Di,{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 Yo=J(Dt,async(e,t,n)=>{let r=it?.();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,x,{},{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)=>dB(e,t,{handler:`sync-resolve-conflict`})?it?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Xo(e,t){if(!dB(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(!pt){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=Lx(i),o=n.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=it?.(),c=s?s.getConflicts().some(e=>e.file===i):!1;if(!o&&!c){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 l=r.searchParams.get(`source`),u=Ao({baseDir:pt,timeout:{block:15e3}});async function d(e){try{return{present:!0,content:await u.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,r,a]=await Promise.all([d(1),d(2),d(3)]),o=e.present?e.content:``,s=a.present?a.content:``,c=r.present&&a.present?`both-modified`:!r.present&&a.present?`delete-modify`:r.present&&!a.present?`modify-delete`:`both-modified`,u=r.present?r.content:``,f=null;if(l===`ytext`){let e=Lx(i),t=n.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(f=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=qt?qt(e):null;t!==null&&!pW(t)?u=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,Dn,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:f},{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 Qo(e,t){if(!dB(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`),r=n.searchParams.get(`rootDir`)??void 0,i=n.searchParams.get(`packId`),a=wH(i);if(i!==null&&i!==``&&a===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${i}" is not registered.`});return}try{q(t,200,pee,{plan:await BH({projectDir:s,rootDir:r,packId:a})},{handler:`seed-plan`})}catch(e){if(e instanceof fH){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof pH){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 $o=J(Xn,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=wH(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,hn,{result:await FH(i,{projectDir:s,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)=>dB(e,t,{handler:`seed-apply`})});async function es(e,t){if(dB(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,gi,{packs:EH()},{handler:`seed-packs`})}}let ts=J(kr,async(e,t,n)=>{if(n.out!==void 0&&!cB(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,er,await tF({...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)=>dB(e,t,{handler:`install-skill`})});async function ns(e,t){if(dB(e,t,{handler:`installed-agents`}))try{await CA(e,t,In.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:qx(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let rs=J(D,async(e,t)=>{if(!ze){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,o,{tags:ze.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 is(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(!ze){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=ze.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:zn(e),matchingTags:t,snippet:null}));q(t,200,_t,{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 as(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(s),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${Uc}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let os=/^[A-Za-z0-9_-]+$/;function ss(e,t,n=`template`){return!e||!os.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 cs(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}${Uc}`))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 ls(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 us=WR({GET:J(D,async(e,t)=>{try{let n=as(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await pO(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,xE.parse)(await Cl(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,kn,{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(ki,async(e,t,n)=>{try{if(sn){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=FL(n,ht);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=as(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=vO({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`&&(Mi(e,Ai(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Pi(`folder-config-put`))}q(t,200,kt,{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 ds(e,t,r,i){if(!t)return!1;let a=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=n.documents.get(a);return o&&$x(o)?(nS(i,new tS({file:`${a}.md`}),r),!0):!1}function fs(e,t,r){let i=n.documents.get(e);return i&&$x(i)?(nS(r,new tS({file:`${e}.md`}),t),!0):!1}let ps=J(D,UR(async(e,t)=>{let n=qD(z(s));q(t,200,iee,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),ms=e=>{let{body:t}=cn(e);return{frontmatter:Xe(e)??{},body:t}},hs=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ss(r,t,`template-get`))return;let i=as(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=cs(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=fn(await Cl(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,lee,{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}),gs=J(Br,async(e,t,n)=>{try{if(sn){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=FL(n,ht);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(!ss(r,t,`template-put`))return;let i=as(n.folder,t,`folder`,`template-put`);if(!i||ds(i.folderRel,r,`template-put`,t))return;let o=JO({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:ls(n.frontmatter)});if(!o.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:o.error.code,cause:Error(o.error.message)});return}let s=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!B(s),l=R(i.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=Os(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=di(n),h=await a.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{ox(h.dc.document,o.content,`agent`)},h.origin);let g=await rr(u);if(g?.kind===`failure`){ir(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){ar(t,`template-put`);return}Mi(e,Ai(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await Pi(`template-put`),q(t,200,see,{path:l,created:c,warnings:o.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`}),_s=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ss(r,t,`template-delete`))return;let i=as(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=FL({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},ht);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(ds(i.folderRel,r,`template-delete`,t))return;await Mr([Os(i.folderRel,r)],`deleted-upstream`);let s=XO({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&&(Mi(o,Ai(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Pi(`template-delete`)),q(t,200,aee,{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}),vs=WR({GET:hs,PUT:gs,POST:J(or,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!ss(n.fromName,t,`template-move`)||!ss(n.toName,t,`template-move`))return;let r=as(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=as(n.toFolder,t,`folder`,`template-move`);if(!i||ds(r.folderRel,n.fromName,`template-move`,t))return;await Mr([Os(r.folderRel,n.fromName)],`renamed`);let a=await QO({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await hG(pt,e,t);return n||mG(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=cs(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=qn(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=YO({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ls(n.frontmatter)});t.ok||(o=t.error)}}if(Mi(e,Ai(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Pi(`template-move`),We?.(`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,xn,{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:_s},{handler:`template`}),ys=J(Pr,async(e,t,r)=>{try{if(sn){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=FL(r,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let i=r.sourcePath;if(!vG(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let o=Jn(i);if(Dx(o)||Ox(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`template-import`});return}let c=GW(s,`file`,o);if(!B(c)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${o}.`,{handler:`template-import`});return}let l=n.documents.get(o);if(r.deleteSource){let e=it?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),r=l!==void 0&&$x(l),a=n.has(i);if(r||a){nS(t,new tS({file:i}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await n.openDirectConnection(o);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=r.name;if(!d){let{basename:e}=KW(i);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!ss(d,t,`template-import`))return;let f=as(r.targetFolder,t,`folder`,`template-import`);if(!f||ds(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=cn(u),h=mt(p),g={};try{h.trim()&&(g=(0,xE.parse)(h))}catch{}let _=r.title||g?.title||iP(u,d),v=g?.description||``,b=Array.isArray(g?.tags)?g.tags:[],x={...g};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,xE.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=JO({name:d,body:S,frontmatter:{title:_,description:v,tags:b}});if(!C.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!B(w),ee=R(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),te=Os(f.folderRel,d),{agentId:ne,agentName:E,colorSeed:re,clientName:ie}=di(r),ae=await a.getSession(te,ne,{displayName:E,colorSeed:re,clientName:ie});ae.dc.document.transact(()=>{ox(ae.dc.document,C.content,`agent`)},ae.origin);let oe=await rr(te);if(oe?.kind===`failure`){ir(t,oe.failure,`template-import`);return}if(oe?.kind===`divergence`){ar(t,`template-import`);return}Mi(e,Ai(`template`,f.folderRel,d),`template-import: ${ee}`),r.deleteSource&&(await Mr([o],`deleted-upstream`),Ut&&Ut.setDeleted(o),no(c),y?.({kind:`delete`,path:c,docName:o})),await Pi(`template-import`),We?.(`files`),q(t,200,ei,{path:ee,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function bs(e,t,n){return!e||e.length>64||!C.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 xs(e,t,n){let r=we.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 Ss=gt??hl();function Cs(e){return z(e===`global`?Ss:s,`.ok`,`skills`)}let ws=EP.project;function Ts(){if(!pt)return null;let e=[],t=null;for(let n of ji){let r=pn[n];if(!r)continue;let i=z(pt,...r.split(`/`),ws);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(pt,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Es(){let e=Ts();if(!e)return null;let t;try{let{frontmatter:n}=ms(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:ws,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Ds(e,t,n){return OP(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 Os(e,t){return`${Ge}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function ks(e){return e===`navigation`||e===`relevance`?e:void 0}function As(e,t){return R(t===`global`?Ss:s,e).split(/[\\/]/).filter(Boolean).join(`/`)}function js(e){return e===`global`?Ss:pt}async function Ms(e,t){let n=await mj(e,t);return kF(t,e,ji),n!==null}function Ns(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=il(e,{withFileTypes:!0})}catch(r){return I(`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()||!C.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}=ms(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:As(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Ps=J(D,UR(async(e,t)=>{let n=Ns(Cs(`project`),`project`),r=Ns(Cs(`global`),`global`),i=pt?dj(pt).skills:{},a=dj(Ss).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=Eoe(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===ws)?null:Es();q(t,200,en,{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}),Fs=A({managed:O().nullable(),importable:N().int().nonnegative()}),Is=()=>({managed:pt?iF(pt)?.manageEditorSkills??null:null,importable:pt?joe({projectDir:pt,skillsRoot:Cs(`project`)}):0}),Ls=WR({GET:J(D,async(e,t)=>{if(!pt){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Fs,Is(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:J(A({manageEditorSkills:O()}),async(e,t,n)=>{if(!pt){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await aF(pt,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await GF({projectDir:pt,skillsRoot:Cs(`project`)});e.adopted.length+e.collided.length>0&&We?.(`files`)}q(t,200,Fs,Is(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),Rs=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!bs(r,t,`skill-get`))return;let i=xs(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===ws&&i===`project`){let e=Ts();if(e){let{frontmatter:n,body:a}=ms(await Cl(e.skillMd,`utf-8`));q(t,200,Ye,{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:jF(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Cs(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}=ms(await Cl(o,`utf-8`));q(t,200,Ye,{skill:{name:r,scope:i,path:As(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:jF(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}),zs=J(Ct,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!bs(n.name,t,`skill-put`)||Ds(n.name,t,`skill-put`))return;let r=TO({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=Cs(n.scope),o=z(i,n.name,`SKILL.md`),s=!B(o),c=R(i,o).split(/[\\/]/).filter(Boolean).join(`/`),l=It(n.scope,n.name);if(fs(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=di(n),m=await a.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{ox(m.dc.document,r.content,`agent`)},m.origin);let h=await rr(l);if(h?.kind===`failure`){ir(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){ar(t,`skill-put`);return}n.scope===`project`&&(Mi(e,Ai(`skill`,``,n.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Pi(`skill-put`)),We?.(`files`),q(t,200,zi,{path:c,created:s,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`}),Bs=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!bs(r,t,`skill-delete`)||Ds(r,t,`skill-delete`))return;let i=xs(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Cs(i),o=n.searchParams,s=FL({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},ht);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Mr([It(i,r)],`deleted-upstream`);let c=jO({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`&&(Mi(s,Ai(`skill`,``,r),`skill-delete: ${c.path}`),await Pi(`skill-delete`)),We?.(`files`));let l=js(i);l&&await Ms(l,r),q(t,200,E,{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}),Vs=WR({GET:Rs,PUT:zs,POST:J(ke,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!bs(n.fromName,t,`skill-move`)||!bs(n.toName,t,`skill-move`)||Ds(n.fromName,t,`skill-move`)||Ds(n.toName,t,`skill-move`))return;let r=Cs(n.scope);await Mr([It(n.scope,n.fromName)],`renamed`);let i=await MO({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await hG(pt,e,t);return n||mG(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=ms(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=EO({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{Ks(r,n.fromName,n.toName)}catch(e){I(`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=As(z(r,n.fromName),n.scope),p=As(z(r,n.toName),n.scope);n.scope===`project`&&(Mi(e,Ai(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Pi(`skill-move`));let m=js(n.scope);if(m){let e=await mj(m,n.fromName);if(e){let t=xF(e.hosts);kF(n.fromName,m,t);let i=OF(z(r,n.toName),n.toName,m,t);await pj(m,n.toName,{...e,hosts:i})}}if(We?.(`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,Ue,{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:Bs},{handler:`skill`});function Hs(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 Us(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Ws(e,t){let n=t.replace(/\.md$/i,``);return`${Ht(e).replace(/\/SKILL$/,``)}/${n}`}function Gs(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of il(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 Ks(e,t,n){if(!Le)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{Le.deleteDocument(e),ze?.deleteDocument(e);return}Le.renameDocument(e,t,r),ze?.renameDocument(e,t,r)};r(Ht(t),Ht(n),z(e,n,`SKILL.md`));for(let i of Gs(e,n))r(Ws(t,i),Ws(n,i),z(e,n,i));We?.(`backlinks`),We?.(`graph`)}let qs=WR({GET:J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!bs(r,t,`skill-file-get`))return;let i=xs(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===ws&&i===`project`?Ts():null,s=o&&a===`SKILL.md`?`reference`:Hs(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(Cs(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${Uc}`)){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?yi.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 Cl(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,br,{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(f,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!bs(n.name,t,`skill-file-put`)||Ds(n.name,t,`skill-file-put`))return;let r=Hs(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=Cs(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 o=n.path.replace(/\\/g,`/`),s=Us(n.scope,r,o),c;if(s){let e=Ws(n.name,o);if(fs(e,`skill-file-put`,t))return;if(c=!B(z(i,n.name,o)),c&&OO(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:s,colorSeed:l,clientName:u}=di(n),d=await a.getSession(e,r,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{ox(d.dc.document,n.content,`agent`)},d.origin);let f=await rr(e);if(f?.kind===`failure`){ir(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){ar(t,`skill-file-put`);return}}else{let e=kO({skillsRoot:i,name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}n.scope===`project`&&(Mi(e,Ai(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${o}`),await Pi(`skill-file-put`)),We?.(`files`),q(t,200,mr,{path:o,created:c,kind:r,content:s},{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(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!bs(r,t,`skill-file-delete`)||Ds(r,t,`skill-file-delete`))return;let i=xs(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=Hs(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=FL({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},ht);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=Cs(i);Us(i,o,a)&&await Mr([Ws(r,a)],`deleted-upstream`);let l=AO({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`&&(Mi(s,Ai(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Pi(`skill-file-delete`)),l.existed&&We?.(`files`),q(t,200,st,{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`}),Js=J(tt,async(e,t,n)=>{try{let e=Cs(n.scope);if(!bs(n.name,t,`skill-install`)||Ds(n.name,t,`skill-install`))return;if(n.scope===`project`&&!pt){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=js(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=wF(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?ji.filter(e=>n.targets?.some(t=>t===e)):[...ji]:n.targets===void 0?TF(r,JF(r)??void 0):ji.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=xF(dj(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&kF(n.name,r,l);let u=OF(i,n.name,r,o);u.length===0?await mj(r,n.name):await pj(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),We?.(`files`),q(t,200,pe,{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`}),Ys=J(Re,async(e,t,n)=>{try{if(!bs(n.name,t,`skill-uninstall`)||Ds(n.name,t,`skill-uninstall`))return;let e=js(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 Ms(e,n.name);We?.(`files`),q(t,200,Zr,{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`}),Xs=WR({GET:J(D,UR(async(e,t)=>{let n=pt?JF(pt):null;q(t,200,Bt,{targets:TF(pt??``,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(nee,UR(async(e,t,n)=>{if(!pt){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=TF(pt,JF(pt)??void 0),o=Cs(`project`);await Foe(pt,r);let{reprojected:s,bundleHosts:c}=await Noe({projectDir:pt,skillsRoot:o,targets:r});We?.(`files`),q(t,200,ye,{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`}),Zs=J(v,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!bs(n.name,t,`skill-restore`)||Ds(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 qH({shadow:r,contentDir:s,contentRoot:Ie??`.`,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=wF(z(s,`.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."),Mi(e,Ai(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Pi(`skill-restore`),We?.(`files`),q(t,200,Kt,{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`}),Qs=J(Pe,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!bs(n.name,t,`skill-update`)||Ds(n.name,t,`skill-update`))return;if(!MF(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=woe(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(Cs(`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 o;try{o=NF(V(i,`utf-8`))}catch{}let s,c=be?.current;if(c)try{let e=je?.()??`main`;s=(await DL(c,Ie??`.`,[fL],e,`Before updating ${n.name} (${o??`unversioned`} → ${r.version})`)).checkpointRef}catch(e){I(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=It(`project`,n.name);if(fs(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=di(n),m=await a.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{ox(m.dc.document,r.content,`agent`)},m.origin);let h=await rr(l);if(h?.kind===`failure`){ir(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){ar(t,`skill-update`);return}Mi(e,Ai(`skill`,``,n.name),`skill-pack-update: ${n.name} (${o??`unversioned`} → ${r.version})`),await Pi(`skill-update`),We?.(`files`),q(t,200,on,{name:n.name,version:r.version,...o===void 0?{}:{previousVersion:o},...s===void 0?{}:{checkpointRef:s}},{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 $s(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])=>At({kind:`folder`,path:e,modifiedTs:t}))}function ec(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 tc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function nc(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 rc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function ic(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function ac(e,t,n,r){let i=r.documents.filter(e=>!Yt(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!$t?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};$t.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await $t.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=tn?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=$t.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function oc(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`?ec(e.document.content,t):void 0}}async function sc(e){let t=performance.now();if(gc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await _c(),i=await ac(e.query,e.intent,e.semanticParam,n),a=re(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>oc(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},Rk({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 cc(){let e=Cs(`project`);if(!B(e))return[];let t;try{t=il(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!C.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=ul(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function lc(){let e=[];for(let t of cc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=ms(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(At({kind:`page`,path:It(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function uc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let dc=new Map;async function fc(){let e=[],t=[],n=new Set;for(let[r,i]of h()){if(Dx(r)||Ox(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(At({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=uc(i),o=dc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await Cl(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=iP(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=At({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=AW(),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),I(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),aW().add(1)),{documents:[...e,...lc(),...i,...$s([...e,...i])],truncated:a}}function pc(){return cc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function mc(){return b?`gen:${b()}|skills${pc()}`:`${[...h()].filter(([e])=>!Dx(e)&&!Ox(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${uc(t)}`).join(``)}|skills${pc()}`}let hc=Vt===void 0;Vt?.then(()=>{hc=!0},e=>{hc=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function gc(){return!hc}async function _c(){let e=`${s}${pt??``}`,t=mc(),n=gG.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 fc();if(!e)return sW().add(1,{mode:`cold`}),{corpus:fee(t),truncated:n};let a=w(e,t);if(a.rebuilt){sW().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;I(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else sW().add(1,{mode:`incremental`}),I(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();gG.set(e,{fingerprint:t,pending:a});try{let n=await a;return gG.get(e)?.pending===a&&gG.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw gG.get(e)?.pending===a&&gG.delete(e),t}}function vc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{_c().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}vc();let yc=WR({GET:J(D,UR(async(e,t)=>{let n=_ee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=tc(n.get(`intent`)),o=ks(n.get(`ranking`)),s=nc(n.get(`scope`)??n.get(`scopes`)),c=rc(n.get(`semantic`)),l=ic(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,Pt,await sc({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(Ci,UR(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=tc(n.intent),a=ks(n.ranking),o=nc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=rc(n.semantic),l=ic(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,Pt,await sc({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`}),bc=J(D,UR(async(e,t)=>{q(t,200,ft,{...await YP(hl())},{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)=>dB(e,t,{handler:`skill-install-state`})});async function xc(e,t){if(dB(e,t,{handler:`handoff`}))try{await YA(e,t,{contentDir:s,platform:process.platform,isSchemeRegistered:In.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:qx(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Sc(e,t){if(dB(e,t,{handler:`spawn-cursor`}))try{await zA(e,t,{contentDir:s,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:qx(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Cc=J(Ke,async(e,t,n)=>{try{if(!pt){sP(`no-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`no-remote`},{handler:oP});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!hae(e,n.kind)){sP(`invalid-path`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`invalid-path`},{handler:oP});return}let r=bae(pt);if(r===null){if(dP(pt).kind===`no-remote`){sP(`no-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`no-remote`},{handler:oP});return}sP(`detached-head`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`detached-head`},{handler:oP});return}let i=dP(pt);if(i.kind===`no-remote`){sP(`no-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`no-remote`},{handler:oP});return}if(i.kind===`non-github`){sP(`non-github-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`non-github-remote`},{handler:oP});return}if(!Tae(pt,r)){sP(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,Qe,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:oP});return}let a=cG(pt,s);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&I(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=gae(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=_ae(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Bm(c)}`,u=await vae(pt,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);sP(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,Qe,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:oP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:oP,cause:e})}},{handler:oP,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:oP})}),wc=J(D,async(e,t)=>{try{if(!pt){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:kR});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(!Lt(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:kR});return}if(!DR(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:kR});return}q(t,200,_r,await OR(pt,r,i,a),{handler:kR})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:kR,cause:e})}},{handler:kR,method:`GET`,skipBodyParse:!0}),Tc=J(bt,async(e,t,n)=>{try{if(!pt){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:TP});return}if(!DR(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:TP});return}let e=cG(pt,s);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;q(t,200,mee,await Bae(pt,n.branch,r,n.kind),{handler:TP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:TP,cause:e})}},{handler:TP,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:TP})}),Ec=J(l,async(e,t,n)=>{if(FL(n,ht).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:PR});return}if(!pt){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:PR});return}try{q(t,200,dr,await jo(()=>IR(pt,n.branch,{fastForward:n.fastForward===!0})),{handler:PR})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:PR,cause:e})}},{handler:PR,method:`POST`});async function Dc(e){let[t,...n]=ct,r=[...n,...e];return await new Promise((e,n)=>{let i=Nc(t,r,hA({...Xa,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},gP),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 ${gP}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=SP(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 Oc=J(D,async(e,t)=>{if(!mn.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:pP,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Dc([`share`,`owners`,`--json`]),n=Eae(yP(e));xP(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,de,n,{handler:pP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:pP,cause:e})}finally{mn.release(`/api/share/publish/owners`)}},{handler:pP,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>dB(e,t,{handler:pP})}),kc=J(D,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!vP(r)||!_P(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:mP});return}if(!mn.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:mP,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Dc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Dae(yP(e));xP(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,lt,n,{handler:mP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mP,cause:e})}finally{mn.release(`/api/share/publish/name-check`)}},{handler:mP,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>dB(e,t,{handler:mP})}),Ac=J(Ee,async(e,t,n)=>{if(!pt){xP(`publish-create`,`no-project`),q(t,200,Be,{ok:!1,error:`no-project`},{handler:hP});return}if(!vP(n.owner)||!_P(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:hP});return}if(!mn.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:hP,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,pt,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Dc(e),i=Aae(yP(r));xP(`publish-create`,i.ok?`ok`:i.error),i.ok&&it?.()?.refreshRemote().catch(()=>{}),q(t,200,Be,i,{handler:hP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:hP,cause:e})}finally{mn.release(`/api/share/publish`)}},{handler:hP,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:hP})}),jc=J(et,async(e,t,n)=>{try{let e=I(`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,dt,{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)=>dB(e,t,{handler:`client-logs`})}),Mc=pt?ZE(pt):null;async function Pc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=e.headers.host,r={collabUrl:n?`ws://${n}/collab`:null,previewUrl:null,port:Mc?Go(Mc)?.port??0:0,singleFile:sn};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,En,r,{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 Fc=`local-op-embeddings-set-key`,Lc=`local-op-embeddings-clear-key`,L=`/api/local-op/embeddings`,Vc=J(fi,async(e,t,n)=>{if(!mn.tryAcquire(L)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Fc,extraHeaders:{"Retry-After":`5`}});return}try{await new eA(nn).set(n.key),q(t,200,Tr,{keyPresent:!0},{handler:Fc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Fc,cause:e})}finally{mn.release(L)}},{handler:Fc,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Fc})}),Hc=J(D,async(e,t)=>{if(!mn.tryAcquire(L)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Lc,extraHeaders:{"Retry-After":`5`}});return}try{await iA(nn),q(t,200,Tr,{keyPresent:!1},{handler:Lc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Lc,cause:e})}finally{mn.release(L)}},{handler:Lc,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Lc})}),Wc=J(D,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if($t){let t=$t.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=await new eA(nn).get(),o=process.env.OK_EMBEDDINGS_API_KEY??null,s=a?`file`:o?`env`:null,c=s!==null,l=a??o,u=l&&l.length>=8?l.slice(-4):null,d=0;for(let[e]of p())!Dx(e)&&!Ox(e)&&!Yt(e)&&(d+=1);q(t,200,ce,{enabled:e,keyPresent:c,keySource:s,keyHint:u,ready:n,capable:r,embedded:i,total:d},{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 Gc(e,t){let n=an?.()??Wr;try{return(await $r(e,AN(s,n,{docName:t,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t)).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}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory lint pass failed post-write; omitting advisories`),[]}}let Kc=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!vG(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=an?.()??Wr,i=[],a=ON(s,n??void 0,e=>i.push(e));q(t,200,ai,{effective:kN(r,a),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}),qc=J(Fn,async(e,t,n)=>{let r;try{r=WN(z(s),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}try{let e=an?.()??Wr,n=[],r=ON(s,void 0,e=>n.push(e));q(t,200,ai,{effective:kN(e,r),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`}),Jc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),r=n.documents.get(t);return r===void 0?null:r.getText(`source`).toString()},Yc=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!vG(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=$W(s,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=an?.()??Wr;q(t,200,ree,await jN({projectDir:pt??s,contentDir:s,baseConfig:i,docRelPath:r,liveSourceFor:Jc}),{handler:`lint`})}catch(e){if(e instanceof Zj){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}),Zc=J(D,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&&!RW(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=an?.()??Wr;q(t,200,zr,await NN({projectDir:pt??s,contentDir:s,baseConfig:i,targetPath:r,liveSourceFor:Jc}),{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}),Qc=J(Cr,async(t,n,r)=>{try{let t=UW(r.docName,n,`lint-fix`);if(t===null)return;let i=Jn(t),o=FL(r,ht);if(o.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=o.kind===`anonymous`?`principal-anonymous`:o.writerId,l=o.kind===`anonymous`?`Anonymous`:o.displayName,u=o.kind===`anonymous`?c:o.colorSeed,d=o.kind===`agent`?o.clientName:void 0;if(Dx(i)||Ox(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=$W(s,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}WW(z(s,f),s);let p=an?.()??Wr,{stored:m}=mi(o.summary),h=await a.getSession(i,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await MN({projectDir:pt??s,contentDir:s,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Nn(d),n=An[t]??xr(u??c);nt?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{IS(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0)},h.origin),o.kind!==`anonymous`&&sk(i,c,l,u,void 0,o.kind===`agent`?pi({clientName:o.clientName,clientVersion:o.clientVersion,label:o.label}):o.actor,m)}finally{nt?.touchMode(c,`idle`)}let t=await rr(i);if(t?.kind===`failure`){ir(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){ar(n,`lint-fix`);return}nr(i,`lint-fix`);try{b=await $r(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,ui,{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 Zj){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof tS){nS(n,e,`lint-fix`);return}if(e instanceof oS){cS(n,e,`lint-fix`);return}if(e instanceof GS){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`}),el=`link-preview`,tl=new Zz({cacheDir:sn?null:z(pt??s,`.ok`,`local`,`link-previews`)}),nl=null,rl=()=>(nl??=tl.init(),nl),al=un??Hz;async function sl(e){let t=await al(e);return t.ok?{ok:!0,metadata:await qz({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:al})}:{ok:!1,reason:t.reason}}let cl=()=>{try{return dn?.()===!0}catch{return!1}},ll={"/api/config":Pc,"/api/asset":wa,"/api/asset-text":Ea,"/api/document":Wi,"/api/documents":Gi,"/api/backlinks":Ki,"/api/backlink-counts":qi,"/api/link-preview":J(_i,async(e,t,n)=>{try{if(!cl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Ni,{ok:!1,reason:`disabled`},{handler:el});return}await rl();let e=!1,r=await tl.load(n.url,()=>(e=!0,sl(n.url)));tl.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,Ni,i,{handler:el})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:el,cause:e})}},{handler:el,method:`POST`,preBodyGate:(e,t)=>{let n=eB({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:el}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:el}),!1)}}),"/api/forward-links":Zi,"/api/link-graph":Qi,"/api/dead-links":na,"/api/orphans":$i,"/api/hubs":ta,"/api/tags":rs,"/api/pages":Va,"/api/folder-config":us,"/api/template":vs,"/api/template/import":ys,"/api/templates":ps,"/api/skill":Vs,"/api/skill-file":qs,"/api/skills":Ps,"/api/skills/management":Ls,"/api/skill/install":Js,"/api/skill/uninstall":Ys,"/api/skill/restore":Zs,"/api/skill/update":Qs,"/api/skill-targets":Xs,"/api/search":yc,"/api/semantic-status":Wc,"/api/lint/config":Kc,"/api/lint/markdownlint-config":qc,"/api/lint":Yc,"/api/lint/audit":Zc,"/api/lint/fix":Qc,"/api/suggest-links":Ha,"/api/page-headings":Ma,"/api/create-page":Oa,"/api/create-folder":ka,"/api/duplicate-path":ja,"/api/rename-path":Na,"/api/delete-path":Ra,"/api/trash/cleanup":Ba,"/api/upload":Ua,"/api/agent-write":Fi,"/api/agent-write-md":Ii,"/api/agent-write-batch":Bi,"/api/frontmatter-patch":Hi,"/api/agent-patch":ia,"/api/agent-undo":aa,"/api/agent-activity":oa,"/api/agent-burst-diff":sa,"/api/save-version":M,"/api/history":da,"/api/rollback":pa,"/api/metrics/reconciliation":ma,"/api/metrics/parse-health":ha,"/api/metrics/agent-presence":F,"/api/metrics/agent-effects":ba,"/api/metrics/watcher-recent":xa,"/api/__embed-detect":Sa,"/api/server-info":ga,"/api/acp/catalog":va,"/api/share/construct-url":Cc,"/api/share/target-status":Tc,"/api/git/branch-info":wc,"/api/git/checkout":Ec,"/api/share/publish/owners":Oc,"/api/share/publish/name-check":kc,"/api/share/publish":Ac,"/api/principal":ya,"/api/rescue":Da,"/api/workspace":Ca,"/api/sync/status":Ko,"/api/sync/trigger":qo,"/api/sync/conflicts":Jo,"/api/sync/conflict-content":Xo,"/api/sync/resolve-conflict":Yo,"/api/local-op/clone":eo,"/api/local-op/ok-init":ao,"/api/local-op/auth/login":Eo,"/api/local-op/auth/status":Po,"/api/local-op/auth/pat":Io,"/api/local-op/auth/gh-login":Mo,"/api/local-op/auth/repos":Ro,"/api/local-op/auth/signout":Vo,"/api/local-op/auth/set-identity":Wo,"/api/local-op/embeddings/set-key":Vc,"/api/local-op/embeddings/clear-key":Hc,"/api/installed-agents":ns,"/api/spawn-cursor":Sc,"/api/handoff":xc,"/api/install-skill":ts,"/api/skill/install-state":bc,"/api/seed/plan":Qo,"/api/seed/apply":$o,"/api/seed/packs":es,"/api/client-logs":jc};ge&&(ll[`/api/test-reset`]=la,ll[`/api/test-flush-git`]=ca,ll[`/api/test-rescan-backlinks`]=ua,ll[`/api/test-rescan-files`]=j);let pl=new Set(`/api/upload./api/lint/markdownlint-config./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 n=e.url?.split(`?`)[0];if(!n)return;let r=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};vk({ts:Date.now(),url:n,method:e.method??``,ua:r(`user-agent`),origin:r(`origin`),referer:r(`referer`),host:r(`host`),remote:e.socket?.remoteAddress,secChUa:r(`sec-ch-ua`),secChUaMobile:r(`sec-ch-ua-mobile`),secChUaPlatform:r(`sec-ch-ua-platform`),secFetchSite:r(`sec-fetch-site`),secFetchDest:r(`sec-fetch-dest`),secFetchMode:r(`sec-fetch-mode`),secFetchUser:r(`sec-fetch-user`)});let i=e.method??`GET`,a=n;n.startsWith(`/api/history/`)?a=`/api/history/:sha`:n.startsWith(`/api/tags/`)?a=`/api/tags/:name`:ll[n]||(a=`/api/*`);let o=n.startsWith(`/api/`)?Vre(e):void 0;if(o!==void 0&&(Hre(e,o),typeof t.setHeader==`function`&&t.setHeader(Gx,o),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Y.info({event:`api.access`,requestId:o,method:i,route:a,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${i} ${a} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!OE(n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),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, ${Gx}, ${he.protocol}, ${he.runtime}, ${he.kind}`),t.setHeader(`Access-Control-Expose-Headers`,Gx)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(pl.has(n)||ml.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!zB(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!BB(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(sn&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!zB(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!BB(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!n.startsWith(`/api/`))return;let s=Ia.extract(za.active(),e.headers),c=Qa(),l=Date.now();await za.with(s,()=>c.startActiveSpan(`HTTP ${i} ${a}`,{kind:La.SERVER,attributes:{[wo]:i,[So]:a,[gee]:n,[hee]:`http`,[xo]:e.headers[`user-agent`]??``,"ok.request.id":o}},async r=>{try{let a=ll[n],o=!1;if(a)o=!0,await a(e,t);else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&(o=!0,await fa(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await is(e,t,r))}o||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${i} ${n}`});let s=t.statusCode;r.setAttribute(Oo,s),s>=500&&r.setStatus({code:Fa.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:Fa.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:a,cause:e}),e}finally{r.end();let e=(Date.now()-l)/1e3;KU().record(e,{[wo]:i,[So]:a,[Oo]:t.statusCode})}}))}}}function xG(e){let t=e?.code;return typeof t==`string`?t:void 0}function SG(e){let t;try{t=il(e.contentDir,{withFileTypes:!0})}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Ix(n.name,Vi)&&e.basenameIndex.add(n.name)}async function CG(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await wl(i,{withFileTypes:!0})}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=kE(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Sl(a)}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Tl(a)}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!AE(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await El(i)}catch(t){let n=xG(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()&&Ix(a,Xi)&&!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()&&Ix(a,Xi)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const wG=A({principalId:P().optional(),tabSessionId:P().optional(),expectedServerInstanceId:P().optional(),expectedBranch:P().optional(),expectedDocLineageEpoch:P().optional(),clientProtocolVersion:N().optional(),clientRuntimeVersion:P().optional(),clientKind:P().optional()}).loose(),TG=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function EG(e){return TG.includes(e)}function DG(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function OG(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!EG(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 kG=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=DG(e,this.payload)}};function AG(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=wG.safeParse(t);return n.success?n.data:void 0}var jG=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const MG=I(`conflict-storage`);var NG=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(ZE(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){MG.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){MG.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=Rc(this.storePath);B(e)||$c(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};fl(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){MG.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){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=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-RhB108wn.mjs`),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!AE(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);fl(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),MG.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await wP(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){MG.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}),MG.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})}}};function PG(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 FG(e,t){let n=ZE(e);try{$c(n,{recursive:!0}),fl(L(n,le),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=To(e);$c(Rc(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`};fl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const IG=new Map;let LG=!1;function RG(e,t){try{let n=PG(e,t);for(let e of IG.keys())FG(e,n)}catch{}}function zG(e){IG.set(e,(IG.get(e)??0)+1),LG||(LG=!0,process.on(`uncaughtExceptionMonitor`,RG));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=IG.get(e)??0;n<=1?IG.delete(e):IG.set(e,n-1)}}}function BG(e){let t=e.scheduler??p,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 VG(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function HG(e){if(!B(e))return{};let t;try{t=(0,xE.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(!VG(t))return{};let n=t.telemetry;if(!VG(n))return{};let r=n.localSink;return VG(r)?r:{}}function UG(e){return typeof e==`boolean`?e:void 0}function WG(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function GG(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function KG(e){if(VG(e))return WG(e.maxBytes)}function qG(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=HG(qa(`project`,e.projectDir)),n=HG(qa(`project-local`,e.projectDir));if((UG(n.enabled)??UG(t.enabled)??!0)===!1)return null;let r=KG(n.spans)??KG(t.spans)??52428800,i=KG(n.logs)??KG(t.logs)??26214400,a=GG(n.attributeDenylist)??GG(t.attributeDenylist)??ta;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var JG;(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})(JG||={});var YG;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(YG||={});const XG=JG.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),ZG=e=>{switch(typeof e){case`undefined`:return XG.undefined;case`string`:return XG.string;case`number`:return Number.isNaN(e)?XG.nan:XG.number;case`boolean`:return XG.boolean;case`function`:return XG.function;case`bigint`:return XG.bigint;case`symbol`:return XG.symbol;case`object`:return Array.isArray(e)?XG.array:e===null?XG.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?XG.promise:typeof Map<`u`&&e instanceof Map?XG.map:typeof Set<`u`&&e instanceof Set?XG.set:typeof Date<`u`&&e instanceof Date?XG.date:XG.object;default:return XG.unknown}},X=JG.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 QG=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,JG.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()}};QG.create=e=>new QG(e);const $G=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===XG.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,JG.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${JG.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${JG.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${JG.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}"`:JG.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,JG.assertNever(e)}return{message:n}};let eK=$G;function tK(){return eK}const nK=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 rK(e,t){let n=tK(),r=nK({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===$G?void 0:$G].filter(e=>!!e)});e.common.issues.push(r)}var iK=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 aK;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 aK;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 aK=Object.freeze({status:`aborted`}),oK=e=>({status:`dirty`,value:e}),sK=e=>({status:`valid`,value:e}),cK=e=>e.status===`aborted`,lK=e=>e.status===`dirty`,uK=e=>e.status===`valid`,dK=e=>typeof Promise<`u`&&e instanceof Promise;var fK;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(fK||={});var pK=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 mK=(e,t)=>{if(uK(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 QG(e.common.issues);return this._error=t,this._error}}};function hK(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 gK=class{get description(){return this._def.description}_getType(e){return ZG(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ZG(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new iK,ctx:{common:e.parent.common,data:e.data,parsedType:ZG(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(dK(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:ZG(e)};return mK(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:ZG(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return uK(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=>uK(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:ZG(e)},r=this._parse({data:e,path:n.path,parent:n});return mK(n,await(dK(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 vq({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 yq.create(this,this._def)}nullable(){return bq.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $K.create(this)}promise(){return _q.create(this,this._def)}or(e){return nq.create([this,e],this._def)}and(e){return oq.create(this,e,this._def)}transform(e){return new vq({...hK(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new xq({...hK(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new wq({typeName:Z.ZodBranded,type:this,...hK(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Sq({...hK(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 Tq.create(this,e)}readonly(){return Eq.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const _K=/^c[^\s-]{8,}$/i,vK=/^[0-9a-z]+$/,yK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bK=/^[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,xK=/^[a-z0-9_-]{21}$/i,SK=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,CK=/^[-+]?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)?)??$/,wK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let TK;const EK=/^(?:(?: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])$/,DK=/^(?:(?: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])$/,OK=/^(([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]))$/,kK=/^(([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])$/,AK=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jK=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,MK=`((\\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])))`,NK=RegExp(`^${MK}$`);function PK(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 FK(e){return RegExp(`^${PK(e)}$`)}function IK(e){let t=`${MK}T${PK(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function LK(e,t){return!!((t===`v4`||!t)&&EK.test(e)||(t===`v6`||!t)&&OK.test(e))}function RK(e,t){if(!SK.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 zK(e,t){return!!((t===`v4`||!t)&&DK.test(e)||(t===`v6`||!t)&&kK.test(e))}var BK=class e extends gK{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==XG.string){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.string,received:t.parsedType}),aK}let t=new iK,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),rK(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),rK(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?rK(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&rK(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)wK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)TK||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),TK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)bK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)xK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)_K.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)vK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)yK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(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),rK(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),rK(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),rK(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),rK(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),rK(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?IK(r).test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?NK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?FK(r).test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?CK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?LK(e.data,r.version)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?RK(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?zK(e.data,r.version)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?AK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?jK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):JG.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,...fK.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...fK.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...fK.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...fK.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...fK.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...fK.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...fK.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...fK.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...fK.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...fK.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...fK.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...fK.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...fK.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...fK.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,...fK.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,...fK.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...fK.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...fK.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...fK.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...fK.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...fK.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...fK.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...fK.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...fK.errToObj(t)})}nonempty(e){return this.min(1,fK.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}};BK.create=e=>new BK({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...hK(e)});function VK(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 HK=class e extends gK{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)!==XG.number){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.number,received:t.parsedType}),aK}let t,n=new iK;for(let r of this._def.checks)r.kind===`int`?JG.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),rK(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),rK(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),rK(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?VK(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),rK(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),rK(t,{code:X.not_finite,message:r.message}),n.dirty()):JG.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,fK.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,fK.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,fK.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,fK.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:fK.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:fK.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:fK.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:fK.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:fK.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:fK.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:fK.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:fK.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:fK.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:fK.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`&&JG.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)}};HK.create=e=>new HK({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...hK(e)});var UK=class e extends gK{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)!==XG.bigint)return this._getInvalidInput(e);let t,n=new iK;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),rK(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),rK(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),rK(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):JG.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.bigint,received:t.parsedType}),aK}gte(e,t){return this.setLimit(`min`,e,!0,fK.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,fK.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,fK.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,fK.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:fK.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:fK.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:fK.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:fK.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:fK.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:fK.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}};UK.create=e=>new UK({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...hK(e)});var WK=class extends gK{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==XG.boolean){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.boolean,received:t.parsedType}),aK}return sK(e.data)}};WK.create=e=>new WK({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...hK(e)});var GK=class e extends gK{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==XG.date){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.date,received:t.parsedType}),aK}if(Number.isNaN(e.data.getTime()))return rK(this._getOrReturnCtx(e),{code:X.invalid_date}),aK;let t=new iK,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),rK(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),rK(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):JG.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:fK.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:fK.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)}};GK.create=e=>new GK({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...hK(e)});var KK=class extends gK{_parse(e){if(this._getType(e)!==XG.symbol){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.symbol,received:t.parsedType}),aK}return sK(e.data)}};KK.create=e=>new KK({typeName:Z.ZodSymbol,...hK(e)});var qK=class extends gK{_parse(e){if(this._getType(e)!==XG.undefined){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.undefined,received:t.parsedType}),aK}return sK(e.data)}};qK.create=e=>new qK({typeName:Z.ZodUndefined,...hK(e)});var JK=class extends gK{_parse(e){if(this._getType(e)!==XG.null){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.null,received:t.parsedType}),aK}return sK(e.data)}};JK.create=e=>new JK({typeName:Z.ZodNull,...hK(e)});var YK=class extends gK{constructor(){super(...arguments),this._any=!0}_parse(e){return sK(e.data)}};YK.create=e=>new YK({typeName:Z.ZodAny,...hK(e)});var XK=class extends gK{constructor(){super(...arguments),this._unknown=!0}_parse(e){return sK(e.data)}};XK.create=e=>new XK({typeName:Z.ZodUnknown,...hK(e)});var ZK=class extends gK{_parse(e){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.never,received:t.parsedType}),aK}};ZK.create=e=>new ZK({typeName:Z.ZodNever,...hK(e)});var QK=class extends gK{_parse(e){if(this._getType(e)!==XG.undefined){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.void,received:t.parsedType}),aK}return sK(e.data)}};QK.create=e=>new QK({typeName:Z.ZodVoid,...hK(e)});var $K=class e extends gK{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==XG.array)return rK(t,{code:X.invalid_type,expected:XG.array,received:t.parsedType}),aK;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(rK(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&&(rK(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&&(rK(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 pK(t,e,t.path,n)))).then(e=>iK.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new pK(t,e,t.path,n)));return iK.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:fK.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:fK.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:fK.toString(n)}})}nonempty(e){return this.min(1,e)}};$K.create=(e,t)=>new $K({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...hK(t)});function eq(e){if(e instanceof tq){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=yq.create(eq(r))}return new tq({...e._def,shape:()=>t})}else if(e instanceof $K)return new $K({...e._def,type:eq(e.element)});else if(e instanceof yq)return yq.create(eq(e.unwrap()));else if(e instanceof bq)return bq.create(eq(e.unwrap()));else if(e instanceof sq)return sq.create(e.items.map(e=>eq(e)));else return e}var tq=class e extends gK{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=JG.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==XG.object){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.object,received:t.parsedType}),aK}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZK&&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 pK(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ZK){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&&(rK(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 pK(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=>iK.mergeObjectSync(t,e)):iK.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return fK.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:fK.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 JG.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 JG.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return eq(this)}partial(t){let n={};for(let e of JG.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 JG.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof yq;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return mq(JG.objectKeys(this.shape))}};tq.create=(e,t)=>new tq({shape:()=>e,unknownKeys:`strip`,catchall:ZK.create(),typeName:Z.ZodObject,...hK(t)}),tq.strictCreate=(e,t)=>new tq({shape:()=>e,unknownKeys:`strict`,catchall:ZK.create(),typeName:Z.ZodObject,...hK(t)}),tq.lazycreate=(e,t)=>new tq({shape:e,unknownKeys:`strip`,catchall:ZK.create(),typeName:Z.ZodObject,...hK(t)});var nq=class extends gK{_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 QG(e.ctx.common.issues));return rK(t,{code:X.invalid_union,unionErrors:n}),aK}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 QG(e));return rK(t,{code:X.invalid_union,unionErrors:i}),aK}}get options(){return this._def.options}};nq.create=(e,t)=>new nq({options:e,typeName:Z.ZodUnion,...hK(t)});const rq=e=>e instanceof fq?rq(e.schema):e instanceof vq?rq(e.innerType()):e instanceof pq?[e.value]:e instanceof hq?e.options:e instanceof gq?JG.objectValues(e.enum):e instanceof xq?rq(e._def.innerType):e instanceof qK?[void 0]:e instanceof JK?[null]:e instanceof yq?[void 0,...rq(e.unwrap())]:e instanceof bq?[null,...rq(e.unwrap())]:e instanceof wq||e instanceof Eq?rq(e.unwrap()):e instanceof Sq?rq(e._def.innerType):[];var iq=class e extends gK{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==XG.object)return rK(t,{code:X.invalid_type,expected:XG.object,received:t.parsedType}),aK;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}):(rK(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),aK)}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=rq(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,...hK(r)})}};function aq(e,t){let n=ZG(e),r=ZG(t);if(e===t)return{valid:!0,data:e};if(n===XG.object&&r===XG.object){let n=JG.objectKeys(t),r=JG.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=aq(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===XG.array&&r===XG.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=aq(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===XG.date&&r===XG.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var oq=class extends gK{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(cK(e)||cK(r))return aK;let i=aq(e.value,r.value);return i.valid?((lK(e)||lK(r))&&t.dirty(),{status:t.value,value:i.data}):(rK(n,{code:X.invalid_intersection_types}),aK)};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}))}};oq.create=(e,t,n)=>new oq({left:e,right:t,typeName:Z.ZodIntersection,...hK(n)});var sq=class e extends gK{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==XG.array)return rK(n,{code:X.invalid_type,expected:XG.array,received:n.parsedType}),aK;if(n.data.length<this._def.items.length)return rK(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),aK;!this._def.rest&&n.data.length>this._def.items.length&&(rK(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 pK(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>iK.mergeArray(t,e)):iK.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};sq.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new sq({items:e,typeName:Z.ZodTuple,rest:null,...hK(t)})};var cq=class e extends gK{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!==XG.object)return rK(n,{code:X.invalid_type,expected:XG.object,received:n.parsedType}),aK;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new pK(n,e,n.path,e)),value:a._parse(new pK(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?iK.mergeObjectAsync(t,r):iK.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof gK?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...hK(r)}):new e({keyType:BK.create(),valueType:t,typeName:Z.ZodRecord,...hK(n)})}},lq=class extends gK{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!==XG.map)return rK(n,{code:X.invalid_type,expected:XG.map,received:n.parsedType}),aK;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new pK(n,e,n.path,[a,`key`])),value:i._parse(new pK(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 aK;(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 aK;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};lq.create=(e,t,n)=>new lq({valueType:t,keyType:e,typeName:Z.ZodMap,...hK(n)});var uq=class e extends gK{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==XG.set)return rK(n,{code:X.invalid_type,expected:XG.set,received:n.parsedType}),aK;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(rK(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&&(rK(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 aK;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 pK(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:fK.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:fK.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};uq.create=(e,t)=>new uq({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...hK(t)});var dq=class e extends gK{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==XG.function)return rK(t,{code:X.invalid_type,expected:XG.function,received:t.parsedType}),aK;function n(e,n){return nK({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tK(),$G].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return nK({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tK(),$G].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 _q){let e=this;return sK(async function(...t){let o=new QG([]),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 sK(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new QG([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new QG([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:sq.create(t).rest(XK.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||sq.create([]).rest(XK.create()),returns:n||XK.create(),typeName:Z.ZodFunction,...hK(r)})}},fq=class extends gK{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})}};fq.create=(e,t)=>new fq({getter:e,typeName:Z.ZodLazy,...hK(t)});var pq=class extends gK{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return rK(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),aK}return{status:`valid`,value:e.data}}get value(){return this._def.value}};pq.create=(e,t)=>new pq({value:e,typeName:Z.ZodLiteral,...hK(t)});function mq(e,t){return new hq({values:e,typeName:Z.ZodEnum,...hK(t)})}var hq=class e extends gK{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return rK(t,{expected:JG.joinValues(n),received:t.parsedType,code:X.invalid_type}),aK}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return rK(t,{received:t.data,code:X.invalid_enum_value,options:n}),aK}return sK(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})}};hq.create=mq;var gq=class extends gK{_parse(e){let t=JG.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==XG.string&&n.parsedType!==XG.number){let e=JG.objectValues(t);return rK(n,{expected:JG.joinValues(e),received:n.parsedType,code:X.invalid_type}),aK}if(this._cache||=new Set(JG.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=JG.objectValues(t);return rK(n,{received:n.data,code:X.invalid_enum_value,options:e}),aK}return sK(e.data)}get enum(){return this._def.values}};gq.create=(e,t)=>new gq({values:e,typeName:Z.ZodNativeEnum,...hK(t)});var _q=class extends gK{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==XG.promise&&t.common.async===!1?(rK(t,{code:X.invalid_type,expected:XG.promise,received:t.parsedType}),aK):sK((t.parsedType===XG.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_q.create=(e,t)=>new _q({type:e,typeName:Z.ZodPromise,...hK(t)});var vq=class extends gK{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=>{rK(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 aK;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?aK:r.status===`dirty`||t.value===`dirty`?oK(r.value):r});{if(t.value===`aborted`)return aK;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?aK:r.status===`dirty`||t.value===`dirty`?oK(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`?aK:(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`?aK:(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(!uK(e))return aK;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=>uK(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):aK);JG.assertNever(r)}};vq.create=(e,t,n)=>new vq({schema:e,typeName:Z.ZodEffects,effect:t,...hK(n)}),vq.createWithPreprocess=(e,t,n)=>new vq({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...hK(n)});var yq=class extends gK{_parse(e){return this._getType(e)===XG.undefined?sK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yq.create=(e,t)=>new yq({innerType:e,typeName:Z.ZodOptional,...hK(t)});var bq=class extends gK{_parse(e){return this._getType(e)===XG.null?sK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bq.create=(e,t)=>new bq({innerType:e,typeName:Z.ZodNullable,...hK(t)});var xq=class extends gK{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===XG.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};xq.create=(e,t)=>new xq({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...hK(t)});var Sq=class extends gK{_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 dK(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new QG(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new QG(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Sq.create=(e,t)=>new Sq({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...hK(t)});var Cq=class extends gK{_parse(e){if(this._getType(e)!==XG.nan){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.nan,received:t.parsedType}),aK}return{status:`valid`,value:e.data}}};Cq.create=e=>new Cq({typeName:Z.ZodNaN,...hK(e)});var wq=class extends gK{_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}},Tq=class e extends gK{_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`?aK:e.status===`dirty`?(t.dirty(),oK(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`?aK: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})}},Eq=class extends gK{_parse(e){let t=this._def.innerType._parse(e),n=e=>(uK(e)&&(e.value=Object.freeze(e.value)),e);return dK(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Eq.create=(e,t)=>new Eq({innerType:e,typeName:Z.ZodReadonly,...hK(t)}),tq.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||={}),BK.create,HK.create,Cq.create,UK.create,WK.create,GK.create,KK.create,qK.create,JK.create,YK.create,XK.create,ZK.create,QK.create,$K.create;const Dq=tq.create;tq.strictCreate,nq.create,iq.create,oq.create,sq.create,cq.create,lq.create,uq.create,dq.create,fq.create,pq.create,hq.create,gq.create,_q.create,vq.create,yq.create,bq.create,vq.createWithPreprocess,Tq.create;const Oq=Wi(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ka.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Na(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ma(e,t,n),e.parseAsync=async(t,n)=>ua(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>na(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)=>ja(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),kq=Wi(`ZodMiniObject`,(e,t)=>{la.init(e,t),Oq.init(e,t),ia(e,`shape`,()=>t.shape)});function Aq(e,t){return new kq({type:`object`,shape:e??{},...Gi(t)})}function jq(e){return!!e._zod}function Mq(e){let t=Object.values(e);if(t.length===0)return Aq({});let n=t.every(jq),r=t.every(e=>!jq(e));if(n)return Aq(e);if(r)return Dq(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Nq(e,t){return jq(e)?Ma(e,t):e.safeParse(t)}async function Pq(e,t){return jq(e)?await na(e,t):await e.safeParseAsync(t)}function Fq(e){if(!e)return;let t;if(t=jq(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Iq(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 Mq(e)}}if(jq(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 Lq(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 Rq(e){return e.description}function zq(e){if(jq(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Bq(e){if(jq(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 Vq=`2025-11-25`,Hq=[Vq,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Uq=`io.modelcontextprotocol/related-task`,Wq=sa(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Gq=Oa([P(),N().int()]),Kq=P();wa({ttl:N().optional(),pollInterval:N().optional()});const qq=A({ttl:N().optional()}),Jq=A({taskId:P()}),Yq=wa({progressToken:Gq.optional(),[Uq]:Jq.optional()}),Xq=A({_meta:Yq.optional()}),Zq=Xq.extend({task:qq.optional()}),Qq=e=>Zq.safeParse(e).success,$q=A({method:P(),params:Xq.loose().optional()}),eJ=A({_meta:Yq.optional()}),tJ=A({method:P(),params:eJ.loose().optional()}),nJ=wa({_meta:Yq.optional()}),rJ=Oa([P(),N().int()]),iJ=A({jsonrpc:F(`2.0`),id:rJ,...$q.shape}).strict(),aJ=e=>iJ.safeParse(e).success,oJ=A({jsonrpc:F(`2.0`),...tJ.shape}).strict(),sJ=e=>oJ.safeParse(e).success,cJ=A({jsonrpc:F(`2.0`),id:rJ,result:nJ}).strict(),lJ=e=>cJ.safeParse(e).success;var uJ;(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`})(uJ||={});const dJ=A({jsonrpc:F(`2.0`),id:rJ.optional(),error:A({code:N().int(),message:P(),data:M().optional()})}).strict(),fJ=e=>dJ.safeParse(e).success,pJ=Oa([iJ,oJ,cJ,dJ]);Oa([cJ,dJ]);const mJ=nJ.strict(),hJ=eJ.extend({requestId:rJ.optional(),reason:P().optional()}),gJ=tJ.extend({method:F(`notifications/cancelled`),params:hJ}),_J=A({icons:k(A({src:P(),mimeType:P().optional(),sizes:k(P()).optional(),theme:Yi([`light`,`dark`]).optional()})).optional()}),vJ=A({name:P(),title:P().optional()}),yJ=vJ.extend({...vJ.shape,..._J.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),bJ=Ta(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,da(A({form:da(A({applyDefaults:O().optional()}),j(P(),M())).optional(),url:Wq.optional()}),j(P(),M()).optional())),xJ=wa({list:Wq.optional(),cancel:Wq.optional(),requests:wa({sampling:wa({createMessage:Wq.optional()}).optional(),elicitation:wa({create:Wq.optional()}).optional()}).optional()}),SJ=wa({list:Wq.optional(),cancel:Wq.optional(),requests:wa({tools:wa({call:Wq.optional()}).optional()}).optional()}),CJ=A({experimental:j(P(),Wq).optional(),sampling:A({context:Wq.optional(),tools:Wq.optional()}).optional(),elicitation:bJ.optional(),roots:A({listChanged:O().optional()}).optional(),tasks:xJ.optional(),extensions:j(P(),Wq).optional()}),wJ=Xq.extend({protocolVersion:P(),capabilities:CJ,clientInfo:yJ}),TJ=$q.extend({method:F(`initialize`),params:wJ}),EJ=e=>TJ.safeParse(e).success,DJ=A({experimental:j(P(),Wq).optional(),logging:Wq.optional(),completions:Wq.optional(),prompts:A({listChanged:O().optional()}).optional(),resources:A({subscribe:O().optional(),listChanged:O().optional()}).optional(),tools:A({listChanged:O().optional()}).optional(),tasks:SJ.optional(),extensions:j(P(),Wq).optional()}),OJ=nJ.extend({protocolVersion:P(),capabilities:DJ,serverInfo:yJ,instructions:P().optional()}),kJ=tJ.extend({method:F(`notifications/initialized`),params:eJ.optional()}),AJ=e=>kJ.safeParse(e).success,jJ=$q.extend({method:F(`ping`),params:Xq.optional()}),MJ=A({progress:N(),total:ba(N()),message:ba(P())}),NJ=A({...eJ.shape,...MJ.shape,progressToken:Gq}),PJ=tJ.extend({method:F(`notifications/progress`),params:NJ}),FJ=Xq.extend({cursor:Kq.optional()}),IJ=$q.extend({params:FJ.optional()}),LJ=nJ.extend({nextCursor:Kq.optional()}),RJ=Yi([`working`,`input_required`,`completed`,`failed`,`cancelled`]),zJ=A({taskId:P(),status:RJ,ttl:Oa([N(),Sa()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:ba(N()),statusMessage:ba(P())}),BJ=nJ.extend({task:zJ}),VJ=eJ.merge(zJ),HJ=tJ.extend({method:F(`notifications/tasks/status`),params:VJ}),UJ=$q.extend({method:F(`tasks/get`),params:Xq.extend({taskId:P()})}),WJ=nJ.merge(zJ),GJ=$q.extend({method:F(`tasks/result`),params:Xq.extend({taskId:P()})});nJ.loose();const KJ=IJ.extend({method:F(`tasks/list`)}),qJ=LJ.extend({tasks:k(zJ)}),JJ=$q.extend({method:F(`tasks/cancel`),params:Xq.extend({taskId:P()})}),YJ=nJ.merge(zJ),XJ=A({uri:P(),mimeType:ba(P()),_meta:j(P(),M()).optional()}),ZJ=XJ.extend({text:P()}),QJ=P().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),$J=XJ.extend({blob:QJ}),eY=Yi([`user`,`assistant`]),tY=A({audience:k(eY).optional(),priority:N().min(0).max(1).optional(),lastModified:xa({offset:!0}).optional()}),nY=A({...vJ.shape,..._J.shape,uri:P(),description:ba(P()),mimeType:ba(P()),size:ba(N()),annotations:tY.optional(),_meta:ba(wa({}))}),rY=A({...vJ.shape,..._J.shape,uriTemplate:P(),description:ba(P()),mimeType:ba(P()),annotations:tY.optional(),_meta:ba(wa({}))}),iY=IJ.extend({method:F(`resources/list`)}),aY=LJ.extend({resources:k(nY)}),oY=IJ.extend({method:F(`resources/templates/list`)}),sY=LJ.extend({resourceTemplates:k(rY)}),cY=Xq.extend({uri:P()}),lY=cY,uY=$q.extend({method:F(`resources/read`),params:lY}),dY=nJ.extend({contents:k(Oa([ZJ,$J]))}),fY=tJ.extend({method:F(`notifications/resources/list_changed`),params:eJ.optional()}),pY=cY,mY=$q.extend({method:F(`resources/subscribe`),params:pY}),hY=cY,gY=$q.extend({method:F(`resources/unsubscribe`),params:hY}),_Y=eJ.extend({uri:P()}),vY=tJ.extend({method:F(`notifications/resources/updated`),params:_Y}),yY=A({name:P(),description:ba(P()),required:ba(O())}),bY=A({...vJ.shape,..._J.shape,description:ba(P()),arguments:ba(k(yY)),_meta:ba(wa({}))}),xY=IJ.extend({method:F(`prompts/list`)}),SY=LJ.extend({prompts:k(bY)}),CY=Xq.extend({name:P(),arguments:j(P(),P()).optional()}),wY=$q.extend({method:F(`prompts/get`),params:CY}),TY=A({type:F(`text`),text:P(),annotations:tY.optional(),_meta:j(P(),M()).optional()}),EY=A({type:F(`image`),data:QJ,mimeType:P(),annotations:tY.optional(),_meta:j(P(),M()).optional()}),DY=A({type:F(`audio`),data:QJ,mimeType:P(),annotations:tY.optional(),_meta:j(P(),M()).optional()}),OY=A({type:F(`tool_use`),name:P(),id:P(),input:j(P(),M()),_meta:j(P(),M()).optional()}),kY=A({type:F(`resource`),resource:Oa([ZJ,$J]),annotations:tY.optional(),_meta:j(P(),M()).optional()}),AY=Oa([TY,EY,DY,nY.extend({type:F(`resource_link`)}),kY]),jY=A({role:eY,content:AY}),MY=nJ.extend({description:P().optional(),messages:k(jY)}),NY=tJ.extend({method:F(`notifications/prompts/list_changed`),params:eJ.optional()}),PY=A({title:P().optional(),readOnlyHint:O().optional(),destructiveHint:O().optional(),idempotentHint:O().optional(),openWorldHint:O().optional()}),FY=A({taskSupport:Yi([`required`,`optional`,`forbidden`]).optional()}),IY=A({...vJ.shape,..._J.shape,description:P().optional(),inputSchema:A({type:F(`object`),properties:j(P(),Wq).optional(),required:k(P()).optional()}).catchall(M()),outputSchema:A({type:F(`object`),properties:j(P(),Wq).optional(),required:k(P()).optional()}).catchall(M()).optional(),annotations:PY.optional(),execution:FY.optional(),_meta:j(P(),M()).optional()}),LY=IJ.extend({method:F(`tools/list`)}),RY=LJ.extend({tools:k(IY)}),zY=nJ.extend({content:k(AY).default([]),structuredContent:j(P(),M()).optional(),isError:O().optional()});zY.or(nJ.extend({toolResult:M()}));const BY=Zq.extend({name:P(),arguments:j(P(),M()).optional()}),VY=$q.extend({method:F(`tools/call`),params:BY}),HY=tJ.extend({method:F(`notifications/tools/list_changed`),params:eJ.optional()});A({autoRefresh:O().default(!0),debounceMs:N().int().nonnegative().default(300)});const UY=Yi([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),WY=Xq.extend({level:UY}),GY=$q.extend({method:F(`logging/setLevel`),params:WY}),KY=eJ.extend({level:UY,logger:P().optional(),data:M()}),qY=tJ.extend({method:F(`notifications/message`),params:KY}),JY=A({hints:k(A({name:P().optional()})).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),YY=A({mode:Yi([`auto`,`required`,`none`]).optional()}),XY=A({type:F(`tool_result`),toolUseId:P().describe(`The unique identifier for the corresponding tool call.`),content:k(AY).default([]),structuredContent:A({}).loose().optional(),isError:O().optional(),_meta:j(P(),M()).optional()}),ZY=$i(`type`,[TY,EY,DY]),QY=$i(`type`,[TY,EY,DY,OY,XY]),$Y=A({role:eY,content:Oa([QY,k(QY)]),_meta:j(P(),M()).optional()}),eX=Zq.extend({messages:k($Y),modelPreferences:JY.optional(),systemPrompt:P().optional(),includeContext:Yi([`none`,`thisServer`,`allServers`]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:k(P()).optional(),metadata:Wq.optional(),tools:k(IY).optional(),toolChoice:YY.optional()}),tX=$q.extend({method:F(`sampling/createMessage`),params:eX}),nX=nJ.extend({model:P(),stopReason:ba(Yi([`endTurn`,`stopSequence`,`maxTokens`]).or(P())),role:eY,content:ZY}),rX=nJ.extend({model:P(),stopReason:ba(Yi([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(P())),role:eY,content:Oa([QY,k(QY)])}),iX=A({type:F(`boolean`),title:P().optional(),description:P().optional(),default:O().optional()}),aX=A({type:F(`string`),title:P().optional(),description:P().optional(),minLength:N().optional(),maxLength:N().optional(),format:Yi([`email`,`uri`,`date`,`date-time`]).optional(),default:P().optional()}),oX=A({type:Yi([`number`,`integer`]),title:P().optional(),description:P().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),sX=A({type:F(`string`),title:P().optional(),description:P().optional(),enum:k(P()),default:P().optional()}),cX=A({type:F(`string`),title:P().optional(),description:P().optional(),oneOf:k(A({const:P(),title:P()})),default:P().optional()}),lX=Oa([Oa([A({type:F(`string`),title:P().optional(),description:P().optional(),enum:k(P()),enumNames:k(P()).optional(),default:P().optional()}),Oa([sX,cX]),Oa([A({type:F(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:A({type:F(`string`),enum:k(P())}),default:k(P()).optional()}),A({type:F(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:A({anyOf:k(A({const:P(),title:P()}))}),default:k(P()).optional()})])]),iX,aX,oX]),uX=Oa([Zq.extend({mode:F(`form`).optional(),message:P(),requestedSchema:A({type:F(`object`),properties:j(P(),lX),required:k(P()).optional()})}),Zq.extend({mode:F(`url`),message:P(),elicitationId:P(),url:P().url()})]),dX=$q.extend({method:F(`elicitation/create`),params:uX}),fX=eJ.extend({elicitationId:P()}),pX=tJ.extend({method:F(`notifications/elicitation/complete`),params:fX}),mX=nJ.extend({action:Yi([`accept`,`decline`,`cancel`]),content:Ta(e=>e===null?void 0:e,j(P(),Oa([P(),N(),O(),k(P())])).optional())}),hX=A({type:F(`ref/resource`),uri:P()}),gX=A({type:F(`ref/prompt`),name:P()}),_X=Xq.extend({ref:Oa([gX,hX]),argument:A({name:P(),value:P()}),context:A({arguments:j(P(),P()).optional()}).optional()}),vX=$q.extend({method:F(`completion/complete`),params:_X});function yX(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function bX(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const xX=nJ.extend({completion:wa({values:k(P()).max(100),total:ba(N().int()),hasMore:ba(O())})}),SX=A({uri:P().startsWith(`file://`),name:P().optional(),_meta:j(P(),M()).optional()}),CX=$q.extend({method:F(`roots/list`),params:Xq.optional()}),wX=nJ.extend({roots:k(SX)}),TX=tJ.extend({method:F(`notifications/roots/list_changed`),params:eJ.optional()});Oa([jJ,TJ,vX,GY,wY,xY,iY,oY,uY,mY,gY,VY,LY,UJ,GJ,KJ,JJ]),Oa([gJ,PJ,kJ,TX,HJ]),Oa([mJ,nX,rX,mX,wX,WJ,qJ,BJ]),Oa([jJ,tX,dX,CX,UJ,GJ,KJ,JJ]),Oa([gJ,PJ,qY,vY,fY,HY,NY,HJ,pX]),Oa([mJ,OJ,xX,MY,SY,aY,sY,dY,zY,RY,WJ,qJ,BJ]);var EX=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===uJ.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new DX(e.elicitations,n)}return new e(t,n,r)}},DX=class extends EX{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(uJ.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function OX(e){return e===`completed`||e===`failed`||e===`cancelled`}const kX=Symbol(`Let zodToJsonSchema decide on which parser to use`),AX={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`},jX=e=>typeof e==`string`?{...AX,name:e}:{...AX,...e},MX=e=>{let t=jX(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 NX(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function PX(e,t,n,r,i){e[t]=n,NX(e,t,r,i)}const FX=(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 IX(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?FX(t,e.currentPath):t.join(`/`)}}function LX(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=DZ(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&PX(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&PX(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(PX(n,`minItems`,e.exactLength.value,e.exactLength.message,t),PX(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function RX(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?PX(n,`minimum`,r.value,r.message,t):PX(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),PX(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?PX(n,`maximum`,r.value,r.message,t):PX(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),PX(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:PX(n,`multipleOf`,r.value,r.message,t);break}return n}function zX(){return{type:`boolean`}}function BX(e,t){return DZ(e.type._def,t)}const VX=(e,t)=>DZ(e.innerType._def,t);function HX(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>HX(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 UX(e,t)}}const UX=(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`:PX(n,`minimum`,r.value,r.message,t);break;case`max`:PX(n,`maximum`,r.value,r.message,t);break}return n};function WX(e,t){return{...DZ(e.innerType._def,t),default:e.defaultValue()}}function GX(e,t){return t.effectStrategy===`input`?DZ(e.schema._def,t):IX(t)}function KX(e){return{type:`string`,enum:Array.from(e.values)}}const qX=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function JX(e,t){let n=[DZ(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),DZ(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(qX(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 YX(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 XX;const ZX={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:()=>(XX===void 0&&(XX=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),XX),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 QX(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:PX(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:PX(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`:nZ(n,`email`,r.message,t);break;case`format:idn-email`:nZ(n,`idn-email`,r.message,t);break;case`pattern:zod`:rZ(n,ZX.email,r.message,t);break}break;case`url`:nZ(n,`uri`,r.message,t);break;case`uuid`:nZ(n,`uuid`,r.message,t);break;case`regex`:rZ(n,r.regex,r.message,t);break;case`cuid`:rZ(n,ZX.cuid,r.message,t);break;case`cuid2`:rZ(n,ZX.cuid2,r.message,t);break;case`startsWith`:rZ(n,RegExp(`^${$X(r.value,t)}`),r.message,t);break;case`endsWith`:rZ(n,RegExp(`${$X(r.value,t)}$`),r.message,t);break;case`datetime`:nZ(n,`date-time`,r.message,t);break;case`date`:nZ(n,`date`,r.message,t);break;case`time`:nZ(n,`time`,r.message,t);break;case`duration`:nZ(n,`duration`,r.message,t);break;case`length`:PX(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),PX(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:rZ(n,RegExp($X(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&nZ(n,`ipv4`,r.message,t),r.version!==`v4`&&nZ(n,`ipv6`,r.message,t);break;case`base64url`:rZ(n,ZX.base64url,r.message,t);break;case`jwt`:rZ(n,ZX.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&rZ(n,ZX.ipv4Cidr,r.message,t),r.version!==`v4`&&rZ(n,ZX.ipv6Cidr,r.message,t);break;case`emoji`:rZ(n,ZX.emoji(),r.message,t);break;case`ulid`:rZ(n,ZX.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:nZ(n,`binary`,r.message,t);break;case`contentEncoding:base64`:PX(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:rZ(n,ZX.base64,r.message,t);break}break;case`nanoid`:rZ(n,ZX.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function $X(e,t){return t.patternStrategy===`escape`?tZ(e):e}const eZ=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function tZ(e){let t=``;for(let n=0;n<e.length;n++)eZ.has(e[n])||(t+=`\\`),t+=e[n];return t}function nZ(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}}})):PX(e,`format`,t,n,r)}function rZ(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:iZ(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):PX(e,`pattern`,iZ(t,r),n,r)}function iZ(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
1221
+ `);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{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(),mn.release(po))}),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()),mn.release(po))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),mn.release(po))})}let Bo=`local-op-auth-signout`,Vo=J(sr,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(mo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Bo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ct,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=Nc(e,i,hA({...Za,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,ti,{},{handler:Bo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Bo,cause:e})}finally{mn.release(mo)}},{handler:Bo,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Bo})}),Ho=`/api/local-op/auth/set-identity`,Uo=`local-op-auth-set-identity`,Wo=J(cee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!pt){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Uo});return}if(!mn.tryAcquire(Ho)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Uo,extraHeaders:{"Retry-After":`5`}});return}try{HR(pt,r,i),it?.()?.refreshIdentity().catch(()=>{}),q(t,200,ti,{},{handler:Uo})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Uo,cause:e})}finally{mn.release(Ho)}},{handler:Uo,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Uo})});async function Ko(e,t){if(dB(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=it?.();if(!e){q(t,200,xi,{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,xi,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 qo=J(Mt,async(e,t,n)=>{let r=it?.();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,oe,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:`sync-trigger`})?it?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Jo(e,t){if(dB(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=it?.();q(t,200,Di,{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 Yo=J(Dt,async(e,t,n)=>{let r=it?.();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,x,{},{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)=>dB(e,t,{handler:`sync-resolve-conflict`})?it?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Xo(e,t){if(!dB(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(!pt){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=Lx(i),o=n.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=it?.(),c=s?s.getConflicts().some(e=>e.file===i):!1;if(!o&&!c){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 l=r.searchParams.get(`source`),u=Ao({baseDir:pt,timeout:{block:15e3}});async function d(e){try{return{present:!0,content:await u.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,r,a]=await Promise.all([d(1),d(2),d(3)]),o=e.present?e.content:``,s=a.present?a.content:``,c=r.present&&a.present?`both-modified`:!r.present&&a.present?`delete-modify`:r.present&&!a.present?`modify-delete`:`both-modified`,u=r.present?r.content:``,f=null;if(l===`ytext`){let e=Lx(i),t=n.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(f=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=qt?qt(e):null;t!==null&&!pW(t)?u=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,Dn,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:f},{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 Qo(e,t){if(!dB(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`),r=n.searchParams.get(`rootDir`)??void 0,i=n.searchParams.get(`packId`),a=wH(i);if(i!==null&&i!==``&&a===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${i}" is not registered.`});return}try{q(t,200,pee,{plan:await BH({projectDir:s,rootDir:r,packId:a})},{handler:`seed-plan`})}catch(e){if(e instanceof fH){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof pH){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 $o=J(Xn,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=wH(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,hn,{result:await FH(i,{projectDir:s,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)=>dB(e,t,{handler:`seed-apply`})});async function es(e,t){if(dB(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,gi,{packs:EH()},{handler:`seed-packs`})}}let ts=J(kr,async(e,t,n)=>{if(n.out!==void 0&&!cB(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,er,await tF({...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)=>dB(e,t,{handler:`install-skill`})});async function ns(e,t){if(dB(e,t,{handler:`installed-agents`}))try{await CA(e,t,In.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:qx(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let rs=J(D,async(e,t)=>{if(!ze){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,o,{tags:ze.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 is(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(!ze){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=ze.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:zn(e),matchingTags:t,snippet:null}));q(t,200,_t,{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 as(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(s),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${Uc}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let os=/^[A-Za-z0-9_-]+$/;function ss(e,t,n=`template`){return!e||!os.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 cs(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}${Uc}`))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 ls(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 us=WR({GET:J(D,async(e,t)=>{try{let n=as(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await pO(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,xE.parse)(await Cl(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,kn,{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(ki,async(e,t,n)=>{try{if(sn){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=FL(n,ht);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=as(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=vO({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`&&(Mi(e,Ai(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Pi(`folder-config-put`))}q(t,200,kt,{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 ds(e,t,r,i){if(!t)return!1;let a=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=n.documents.get(a);return o&&$x(o)?(nS(i,new tS({file:`${a}.md`}),r),!0):!1}function fs(e,t,r){let i=n.documents.get(e);return i&&$x(i)?(nS(r,new tS({file:`${e}.md`}),t),!0):!1}let ps=J(D,UR(async(e,t)=>{let n=qD(z(s));q(t,200,iee,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),ms=e=>{let{body:t}=cn(e);return{frontmatter:Xe(e)??{},body:t}},hs=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ss(r,t,`template-get`))return;let i=as(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=cs(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=fn(await Cl(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,lee,{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}),gs=J(Br,async(e,t,n)=>{try{if(sn){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=FL(n,ht);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(!ss(r,t,`template-put`))return;let i=as(n.folder,t,`folder`,`template-put`);if(!i||ds(i.folderRel,r,`template-put`,t))return;let o=JO({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:ls(n.frontmatter)});if(!o.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:o.error.code,cause:Error(o.error.message)});return}let s=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!B(s),l=R(i.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=Os(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=di(n),h=await a.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{ox(h.dc.document,o.content,`agent`)},h.origin);let g=await rr(u);if(g?.kind===`failure`){ir(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){ar(t,`template-put`);return}Mi(e,Ai(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await Pi(`template-put`),q(t,200,see,{path:l,created:c,warnings:o.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`}),_s=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ss(r,t,`template-delete`))return;let i=as(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=FL({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},ht);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(ds(i.folderRel,r,`template-delete`,t))return;await Mr([Os(i.folderRel,r)],`deleted-upstream`);let s=XO({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&&(Mi(o,Ai(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Pi(`template-delete`)),q(t,200,aee,{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}),vs=WR({GET:hs,PUT:gs,POST:J(or,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!ss(n.fromName,t,`template-move`)||!ss(n.toName,t,`template-move`))return;let r=as(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=as(n.toFolder,t,`folder`,`template-move`);if(!i||ds(r.folderRel,n.fromName,`template-move`,t))return;await Mr([Os(r.folderRel,n.fromName)],`renamed`);let a=await QO({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await hG(pt,e,t);return n||mG(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=cs(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=qn(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=YO({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ls(n.frontmatter)});t.ok||(o=t.error)}}if(Mi(e,Ai(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Pi(`template-move`),We?.(`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,xn,{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:_s},{handler:`template`}),ys=J(Pr,async(e,t,r)=>{try{if(sn){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=FL(r,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let i=r.sourcePath;if(!vG(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let o=Jn(i);if(Dx(o)||Ox(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`template-import`});return}let c=GW(s,`file`,o);if(!B(c)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${o}.`,{handler:`template-import`});return}let l=n.documents.get(o);if(r.deleteSource){let e=it?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),r=l!==void 0&&$x(l),a=n.has(i);if(r||a){nS(t,new tS({file:i}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await n.openDirectConnection(o);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=r.name;if(!d){let{basename:e}=KW(i);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!ss(d,t,`template-import`))return;let f=as(r.targetFolder,t,`folder`,`template-import`);if(!f||ds(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=cn(u),h=mt(p),g={};try{h.trim()&&(g=(0,xE.parse)(h))}catch{}let _=r.title||g?.title||iP(u,d),v=g?.description||``,b=Array.isArray(g?.tags)?g.tags:[],x={...g};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,xE.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=JO({name:d,body:S,frontmatter:{title:_,description:v,tags:b}});if(!C.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!B(w),ee=R(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),te=Os(f.folderRel,d),{agentId:ne,agentName:E,colorSeed:re,clientName:ie}=di(r),ae=await a.getSession(te,ne,{displayName:E,colorSeed:re,clientName:ie});ae.dc.document.transact(()=>{ox(ae.dc.document,C.content,`agent`)},ae.origin);let oe=await rr(te);if(oe?.kind===`failure`){ir(t,oe.failure,`template-import`);return}if(oe?.kind===`divergence`){ar(t,`template-import`);return}Mi(e,Ai(`template`,f.folderRel,d),`template-import: ${ee}`),r.deleteSource&&(await Mr([o],`deleted-upstream`),Ut&&Ut.setDeleted(o),no(c),y?.({kind:`delete`,path:c,docName:o})),await Pi(`template-import`),We?.(`files`),q(t,200,ei,{path:ee,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function bs(e,t,n){return!e||e.length>64||!C.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 xs(e,t,n){let r=we.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 Ss=gt??hl();function Cs(e){return z(e===`global`?Ss:s,`.ok`,`skills`)}let ws=EP.project;function Ts(){if(!pt)return null;let e=[],t=null;for(let n of ji){let r=pn[n];if(!r)continue;let i=z(pt,...r.split(`/`),ws);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(pt,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Es(){let e=Ts();if(!e)return null;let t;try{let{frontmatter:n}=ms(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:ws,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Ds(e,t,n){return OP(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 Os(e,t){return`${Ge}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function ks(e){return e===`navigation`||e===`relevance`?e:void 0}function As(e,t){return R(t===`global`?Ss:s,e).split(/[\\/]/).filter(Boolean).join(`/`)}function js(e){return e===`global`?Ss:pt}async function Ms(e,t){let n=await mj(e,t);return kF(t,e,ji),n!==null}function Ns(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=il(e,{withFileTypes:!0})}catch(r){return I(`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()||!C.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}=ms(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:As(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Ps=J(D,UR(async(e,t)=>{let n=Ns(Cs(`project`),`project`),r=Ns(Cs(`global`),`global`),i=pt?dj(pt).skills:{},a=dj(Ss).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=Eoe(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===ws)?null:Es();q(t,200,en,{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}),Fs=A({managed:O().nullable(),importable:N().int().nonnegative()}),Is=()=>({managed:pt?iF(pt)?.manageEditorSkills??null:null,importable:pt?joe({projectDir:pt,skillsRoot:Cs(`project`)}):0}),Ls=WR({GET:J(D,async(e,t)=>{if(!pt){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Fs,Is(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:J(A({manageEditorSkills:O()}),async(e,t,n)=>{if(!pt){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await aF(pt,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await GF({projectDir:pt,skillsRoot:Cs(`project`)});e.adopted.length+e.collided.length>0&&We?.(`files`)}q(t,200,Fs,Is(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),Rs=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!bs(r,t,`skill-get`))return;let i=xs(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===ws&&i===`project`){let e=Ts();if(e){let{frontmatter:n,body:a}=ms(await Cl(e.skillMd,`utf-8`));q(t,200,Ye,{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:jF(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Cs(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}=ms(await Cl(o,`utf-8`));q(t,200,Ye,{skill:{name:r,scope:i,path:As(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:jF(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}),zs=J(Ct,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!bs(n.name,t,`skill-put`)||Ds(n.name,t,`skill-put`))return;let r=TO({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=Cs(n.scope),o=z(i,n.name,`SKILL.md`),s=!B(o),c=R(i,o).split(/[\\/]/).filter(Boolean).join(`/`),l=It(n.scope,n.name);if(fs(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=di(n),m=await a.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{ox(m.dc.document,r.content,`agent`)},m.origin);let h=await rr(l);if(h?.kind===`failure`){ir(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){ar(t,`skill-put`);return}n.scope===`project`&&(Mi(e,Ai(`skill`,``,n.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Pi(`skill-put`)),We?.(`files`),q(t,200,zi,{path:c,created:s,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`}),Bs=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!bs(r,t,`skill-delete`)||Ds(r,t,`skill-delete`))return;let i=xs(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Cs(i),o=n.searchParams,s=FL({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},ht);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Mr([It(i,r)],`deleted-upstream`);let c=jO({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`&&(Mi(s,Ai(`skill`,``,r),`skill-delete: ${c.path}`),await Pi(`skill-delete`)),We?.(`files`));let l=js(i);l&&await Ms(l,r),q(t,200,E,{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}),Vs=WR({GET:Rs,PUT:zs,POST:J(ke,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!bs(n.fromName,t,`skill-move`)||!bs(n.toName,t,`skill-move`)||Ds(n.fromName,t,`skill-move`)||Ds(n.toName,t,`skill-move`))return;let r=Cs(n.scope);await Mr([It(n.scope,n.fromName)],`renamed`);let i=await MO({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await hG(pt,e,t);return n||mG(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=ms(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=EO({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{Ks(r,n.fromName,n.toName)}catch(e){I(`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=As(z(r,n.fromName),n.scope),p=As(z(r,n.toName),n.scope);n.scope===`project`&&(Mi(e,Ai(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Pi(`skill-move`));let m=js(n.scope);if(m){let e=await mj(m,n.fromName);if(e){let t=xF(e.hosts);kF(n.fromName,m,t);let i=OF(z(r,n.toName),n.toName,m,t);await pj(m,n.toName,{...e,hosts:i})}}if(We?.(`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,Ue,{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:Bs},{handler:`skill`});function Hs(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 Us(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Ws(e,t){let n=t.replace(/\.md$/i,``);return`${Ht(e).replace(/\/SKILL$/,``)}/${n}`}function Gs(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of il(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 Ks(e,t,n){if(!Le)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{Le.deleteDocument(e),ze?.deleteDocument(e);return}Le.renameDocument(e,t,r),ze?.renameDocument(e,t,r)};r(Ht(t),Ht(n),z(e,n,`SKILL.md`));for(let i of Gs(e,n))r(Ws(t,i),Ws(n,i),z(e,n,i));We?.(`backlinks`),We?.(`graph`)}let qs=WR({GET:J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!bs(r,t,`skill-file-get`))return;let i=xs(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===ws&&i===`project`?Ts():null,s=o&&a===`SKILL.md`?`reference`:Hs(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(Cs(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${Uc}`)){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?yi.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 Cl(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,br,{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(f,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!bs(n.name,t,`skill-file-put`)||Ds(n.name,t,`skill-file-put`))return;let r=Hs(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=Cs(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 o=n.path.replace(/\\/g,`/`),s=Us(n.scope,r,o),c;if(s){let e=Ws(n.name,o);if(fs(e,`skill-file-put`,t))return;if(c=!B(z(i,n.name,o)),c&&OO(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:s,colorSeed:l,clientName:u}=di(n),d=await a.getSession(e,r,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{ox(d.dc.document,n.content,`agent`)},d.origin);let f=await rr(e);if(f?.kind===`failure`){ir(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){ar(t,`skill-file-put`);return}}else{let e=kO({skillsRoot:i,name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}n.scope===`project`&&(Mi(e,Ai(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${o}`),await Pi(`skill-file-put`)),We?.(`files`),q(t,200,mr,{path:o,created:c,kind:r,content:s},{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(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!bs(r,t,`skill-file-delete`)||Ds(r,t,`skill-file-delete`))return;let i=xs(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=Hs(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=FL({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},ht);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=Cs(i);Us(i,o,a)&&await Mr([Ws(r,a)],`deleted-upstream`);let l=AO({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`&&(Mi(s,Ai(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Pi(`skill-file-delete`)),l.existed&&We?.(`files`),q(t,200,st,{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`}),Js=J(tt,async(e,t,n)=>{try{let e=Cs(n.scope);if(!bs(n.name,t,`skill-install`)||Ds(n.name,t,`skill-install`))return;if(n.scope===`project`&&!pt){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=js(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=wF(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?ji.filter(e=>n.targets?.some(t=>t===e)):[...ji]:n.targets===void 0?TF(r,JF(r)??void 0):ji.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=xF(dj(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&kF(n.name,r,l);let u=OF(i,n.name,r,o);u.length===0?await mj(r,n.name):await pj(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),We?.(`files`),q(t,200,pe,{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`}),Ys=J(Re,async(e,t,n)=>{try{if(!bs(n.name,t,`skill-uninstall`)||Ds(n.name,t,`skill-uninstall`))return;let e=js(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 Ms(e,n.name);We?.(`files`),q(t,200,Zr,{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`}),Xs=WR({GET:J(D,UR(async(e,t)=>{let n=pt?JF(pt):null;q(t,200,Bt,{targets:TF(pt??``,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(nee,UR(async(e,t,n)=>{if(!pt){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=TF(pt,JF(pt)??void 0),o=Cs(`project`);await Foe(pt,r);let{reprojected:s,bundleHosts:c}=await Noe({projectDir:pt,skillsRoot:o,targets:r});We?.(`files`),q(t,200,ye,{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`}),Zs=J(v,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!bs(n.name,t,`skill-restore`)||Ds(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 qH({shadow:r,contentDir:s,contentRoot:Ie??`.`,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=wF(z(s,`.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."),Mi(e,Ai(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Pi(`skill-restore`),We?.(`files`),q(t,200,Kt,{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`}),Qs=J(Pe,async(e,t,n)=>{try{let e=FL(n,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!bs(n.name,t,`skill-update`)||Ds(n.name,t,`skill-update`))return;if(!MF(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=woe(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(Cs(`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 o;try{o=NF(V(i,`utf-8`))}catch{}let s,c=be?.current;if(c)try{let e=je?.()??`main`;s=(await DL(c,Ie??`.`,[fL],e,`Before updating ${n.name} (${o??`unversioned`} → ${r.version})`)).checkpointRef}catch(e){I(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=It(`project`,n.name);if(fs(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=di(n),m=await a.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{ox(m.dc.document,r.content,`agent`)},m.origin);let h=await rr(l);if(h?.kind===`failure`){ir(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){ar(t,`skill-update`);return}Mi(e,Ai(`skill`,``,n.name),`skill-pack-update: ${n.name} (${o??`unversioned`} → ${r.version})`),await Pi(`skill-update`),We?.(`files`),q(t,200,on,{name:n.name,version:r.version,...o===void 0?{}:{previousVersion:o},...s===void 0?{}:{checkpointRef:s}},{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 $s(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])=>At({kind:`folder`,path:e,modifiedTs:t}))}function ec(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 tc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function nc(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 rc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function ic(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function ac(e,t,n,r){let i=r.documents.filter(e=>!Yt(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!$t?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};$t.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await $t.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=tn?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=$t.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function oc(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`?ec(e.document.content,t):void 0}}async function sc(e){let t=performance.now();if(gc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await _c(),i=await ac(e.query,e.intent,e.semanticParam,n),a=re(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>oc(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},Rk({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 cc(){let e=Cs(`project`);if(!B(e))return[];let t;try{t=il(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!C.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=ul(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function lc(){let e=[];for(let t of cc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=ms(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(At({kind:`page`,path:It(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function uc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let dc=new Map;async function fc(){let e=[],t=[],n=new Set;for(let[r,i]of h()){if(Dx(r)||Ox(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(At({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=uc(i),o=dc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await Cl(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=iP(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=At({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=AW(),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),I(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),aW().add(1)),{documents:[...e,...lc(),...i,...$s([...e,...i])],truncated:a}}function pc(){return cc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function mc(){return b?`gen:${b()}|skills${pc()}`:`${[...h()].filter(([e])=>!Dx(e)&&!Ox(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${uc(t)}`).join(``)}|skills${pc()}`}let hc=Vt===void 0;Vt?.then(()=>{hc=!0},e=>{hc=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function gc(){return!hc}async function _c(){let e=`${s}${pt??``}`,t=mc(),n=gG.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 fc();if(!e)return sW().add(1,{mode:`cold`}),{corpus:fee(t),truncated:n};let a=w(e,t);if(a.rebuilt){sW().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;I(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else sW().add(1,{mode:`incremental`}),I(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();gG.set(e,{fingerprint:t,pending:a});try{let n=await a;return gG.get(e)?.pending===a&&gG.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw gG.get(e)?.pending===a&&gG.delete(e),t}}function vc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{_c().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}vc();let yc=WR({GET:J(D,UR(async(e,t)=>{let n=_ee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=tc(n.get(`intent`)),o=ks(n.get(`ranking`)),s=nc(n.get(`scope`)??n.get(`scopes`)),c=rc(n.get(`semantic`)),l=ic(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,Pt,await sc({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(Ci,UR(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=tc(n.intent),a=ks(n.ranking),o=nc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=rc(n.semantic),l=ic(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,Pt,await sc({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`}),bc=J(D,UR(async(e,t)=>{q(t,200,ft,{...await YP(hl())},{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)=>dB(e,t,{handler:`skill-install-state`})});async function xc(e,t){if(dB(e,t,{handler:`handoff`}))try{await YA(e,t,{contentDir:s,platform:process.platform,isSchemeRegistered:In.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:qx(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Sc(e,t){if(dB(e,t,{handler:`spawn-cursor`}))try{await zA(e,t,{contentDir:s,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:qx(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Cc=J(Ke,async(e,t,n)=>{try{if(!pt){sP(`no-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`no-remote`},{handler:oP});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!hae(e,n.kind)){sP(`invalid-path`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`invalid-path`},{handler:oP});return}let r=bae(pt);if(r===null){if(dP(pt).kind===`no-remote`){sP(`no-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`no-remote`},{handler:oP});return}sP(`detached-head`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`detached-head`},{handler:oP});return}let i=dP(pt);if(i.kind===`no-remote`){sP(`no-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`no-remote`},{handler:oP});return}if(i.kind===`non-github`){sP(`non-github-remote`,{kind:n.kind}),q(t,200,Qe,{ok:!1,error:`non-github-remote`},{handler:oP});return}if(!Tae(pt,r)){sP(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,Qe,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:oP});return}let a=cG(pt,s);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&I(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=gae(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=_ae(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Bm(c)}`,u=await vae(pt,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);sP(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,Qe,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:oP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:oP,cause:e})}},{handler:oP,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:oP})}),wc=J(D,async(e,t)=>{try{if(!pt){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:kR});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(!Lt(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:kR});return}if(!DR(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:kR});return}q(t,200,_r,await OR(pt,r,i,a),{handler:kR})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:kR,cause:e})}},{handler:kR,method:`GET`,skipBodyParse:!0}),Tc=J(bt,async(e,t,n)=>{try{if(!pt){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:TP});return}if(!DR(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:TP});return}let e=cG(pt,s);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;q(t,200,mee,await Bae(pt,n.branch,r,n.kind),{handler:TP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:TP,cause:e})}},{handler:TP,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:TP})}),Ec=J(l,async(e,t,n)=>{if(FL(n,ht).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:PR});return}if(!pt){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:PR});return}try{q(t,200,dr,await jo(()=>IR(pt,n.branch,{fastForward:n.fastForward===!0})),{handler:PR})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:PR,cause:e})}},{handler:PR,method:`POST`});async function Dc(e){let[t,...n]=ct,r=[...n,...e];return await new Promise((e,n)=>{let i=Nc(t,r,hA({...Xa,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},gP),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 ${gP}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=SP(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 Oc=J(D,async(e,t)=>{if(!mn.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:pP,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Dc([`share`,`owners`,`--json`]),n=Eae(yP(e));xP(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,de,n,{handler:pP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:pP,cause:e})}finally{mn.release(`/api/share/publish/owners`)}},{handler:pP,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>dB(e,t,{handler:pP})}),kc=J(D,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!vP(r)||!_P(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:mP});return}if(!mn.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:mP,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Dc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Dae(yP(e));xP(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,lt,n,{handler:mP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mP,cause:e})}finally{mn.release(`/api/share/publish/name-check`)}},{handler:mP,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>dB(e,t,{handler:mP})}),Ac=J(Ee,async(e,t,n)=>{if(!pt){xP(`publish-create`,`no-project`),q(t,200,Be,{ok:!1,error:`no-project`},{handler:hP});return}if(!vP(n.owner)||!_P(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:hP});return}if(!mn.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:hP,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,pt,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Dc(e),i=Aae(yP(r));xP(`publish-create`,i.ok?`ok`:i.error),i.ok&&it?.()?.refreshRemote().catch(()=>{}),q(t,200,Be,i,{handler:hP})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:hP,cause:e})}finally{mn.release(`/api/share/publish`)}},{handler:hP,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:hP})}),jc=J(et,async(e,t,n)=>{try{let e=I(`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,dt,{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)=>dB(e,t,{handler:`client-logs`})}),Mc=pt?ZE(pt):null;async function Pc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=e.headers.host,r={collabUrl:n?`ws://${n}/collab`:null,previewUrl:null,port:Mc?Go(Mc)?.port??0:0,singleFile:sn};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,En,r,{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 Fc=`local-op-embeddings-set-key`,Lc=`local-op-embeddings-clear-key`,L=`/api/local-op/embeddings`,Vc=J(fi,async(e,t,n)=>{if(!mn.tryAcquire(L)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Fc,extraHeaders:{"Retry-After":`5`}});return}try{await new eA(nn).set(n.key),q(t,200,Tr,{keyPresent:!0},{handler:Fc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Fc,cause:e})}finally{mn.release(L)}},{handler:Fc,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Fc})}),Hc=J(D,async(e,t)=>{if(!mn.tryAcquire(L)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Lc,extraHeaders:{"Retry-After":`5`}});return}try{await iA(nn),q(t,200,Tr,{keyPresent:!1},{handler:Lc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Lc,cause:e})}finally{mn.release(L)}},{handler:Lc,method:`POST`,preBodyGate:(e,t)=>dB(e,t,{handler:Lc})}),Wc=J(D,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if($t){let t=$t.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=await new eA(nn).get(),o=process.env.OK_EMBEDDINGS_API_KEY??null,s=a?`file`:o?`env`:null,c=s!==null,l=a??o,u=l&&l.length>=8?l.slice(-4):null,d=0;for(let[e]of p())!Dx(e)&&!Ox(e)&&!Yt(e)&&(d+=1);q(t,200,ce,{enabled:e,keyPresent:c,keySource:s,keyHint:u,ready:n,capable:r,embedded:i,total:d},{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 Gc(e,t){let n=an?.()??Wr;try{return(await $r(e,AN(s,n,{docName:t,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t)).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}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory lint pass failed post-write; omitting advisories`),[]}}let Kc=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!vG(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=an?.()??Wr,i=[],a=ON(s,n??void 0,e=>i.push(e));q(t,200,ai,{effective:kN(r,a),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}),qc=J(Fn,async(e,t,n)=>{let r;try{r=WN(z(s),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}try{let e=an?.()??Wr,n=[],r=ON(s,void 0,e=>n.push(e));q(t,200,ai,{effective:kN(e,r),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`}),Jc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),r=n.documents.get(t);return r===void 0?null:r.getText(`source`).toString()},Yc=J(D,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!vG(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=$W(s,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=an?.()??Wr;q(t,200,ree,await jN({projectDir:pt??s,contentDir:s,baseConfig:i,docRelPath:r,liveSourceFor:Jc}),{handler:`lint`})}catch(e){if(e instanceof Zj){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}),Zc=J(D,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&&!RW(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=an?.()??Wr;q(t,200,zr,await NN({projectDir:pt??s,contentDir:s,baseConfig:i,targetPath:r,liveSourceFor:Jc}),{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}),Qc=J(Cr,async(t,n,r)=>{try{let t=UW(r.docName,n,`lint-fix`);if(t===null)return;let i=Jn(t),o=FL(r,ht);if(o.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=o.kind===`anonymous`?`principal-anonymous`:o.writerId,l=o.kind===`anonymous`?`Anonymous`:o.displayName,u=o.kind===`anonymous`?c:o.colorSeed,d=o.kind===`agent`?o.clientName:void 0;if(Dx(i)||Ox(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=$W(s,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}WW(z(s,f),s);let p=an?.()??Wr,{stored:m}=mi(o.summary),h=await a.getSession(i,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await MN({projectDir:pt??s,contentDir:s,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Nn(d),n=An[t]??xr(u??c);nt?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{IS(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0)},h.origin),o.kind!==`anonymous`&&sk(i,c,l,u,void 0,o.kind===`agent`?pi({clientName:o.clientName,clientVersion:o.clientVersion,label:o.label}):o.actor,m)}finally{nt?.touchMode(c,`idle`)}let t=await rr(i);if(t?.kind===`failure`){ir(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){ar(n,`lint-fix`);return}nr(i,`lint-fix`);try{b=await $r(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,ui,{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 Zj){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof tS){nS(n,e,`lint-fix`);return}if(e instanceof oS){cS(n,e,`lint-fix`);return}if(e instanceof GS){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`}),el=`link-preview`,tl=new Zz({cacheDir:sn?null:z(pt??s,`.ok`,`local`,`link-previews`)}),nl=null,rl=()=>(nl??=tl.init(),nl),al=un??Hz;async function sl(e){let t=await al(e);return t.ok?{ok:!0,metadata:await qz({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:al})}:{ok:!1,reason:t.reason}}let cl=()=>{try{return dn?.()===!0}catch{return!1}},ll={"/api/config":Pc,"/api/asset":wa,"/api/asset-text":Ea,"/api/document":Wi,"/api/documents":Gi,"/api/backlinks":Ki,"/api/backlink-counts":qi,"/api/link-preview":J(_i,async(e,t,n)=>{try{if(!cl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Ni,{ok:!1,reason:`disabled`},{handler:el});return}await rl();let e=!1,r=await tl.load(n.url,()=>(e=!0,sl(n.url)));tl.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,Ni,i,{handler:el})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:el,cause:e})}},{handler:el,method:`POST`,preBodyGate:(e,t)=>{let n=eB({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:el}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:el}),!1)}}),"/api/forward-links":Zi,"/api/link-graph":Qi,"/api/dead-links":na,"/api/orphans":$i,"/api/hubs":ta,"/api/tags":rs,"/api/pages":Va,"/api/folder-config":us,"/api/template":vs,"/api/template/import":ys,"/api/templates":ps,"/api/skill":Vs,"/api/skill-file":qs,"/api/skills":Ps,"/api/skills/management":Ls,"/api/skill/install":Js,"/api/skill/uninstall":Ys,"/api/skill/restore":Zs,"/api/skill/update":Qs,"/api/skill-targets":Xs,"/api/search":yc,"/api/semantic-status":Wc,"/api/lint/config":Kc,"/api/lint/markdownlint-config":qc,"/api/lint":Yc,"/api/lint/audit":Zc,"/api/lint/fix":Qc,"/api/suggest-links":Ha,"/api/page-headings":Ma,"/api/create-page":Oa,"/api/create-folder":ka,"/api/duplicate-path":ja,"/api/rename-path":Na,"/api/delete-path":Ra,"/api/trash/cleanup":Ba,"/api/upload":Ua,"/api/agent-write":Fi,"/api/agent-write-md":Ii,"/api/agent-write-batch":Bi,"/api/frontmatter-patch":Hi,"/api/agent-patch":ia,"/api/agent-undo":aa,"/api/agent-activity":oa,"/api/agent-burst-diff":sa,"/api/save-version":M,"/api/history":da,"/api/rollback":pa,"/api/metrics/reconciliation":ma,"/api/metrics/parse-health":ha,"/api/metrics/agent-presence":F,"/api/metrics/agent-effects":ba,"/api/metrics/watcher-recent":xa,"/api/__embed-detect":Sa,"/api/server-info":ga,"/api/acp/catalog":va,"/api/share/construct-url":Cc,"/api/share/target-status":Tc,"/api/git/branch-info":wc,"/api/git/checkout":Ec,"/api/share/publish/owners":Oc,"/api/share/publish/name-check":kc,"/api/share/publish":Ac,"/api/principal":ya,"/api/rescue":Da,"/api/workspace":Ca,"/api/sync/status":Ko,"/api/sync/trigger":qo,"/api/sync/conflicts":Jo,"/api/sync/conflict-content":Xo,"/api/sync/resolve-conflict":Yo,"/api/local-op/clone":eo,"/api/local-op/ok-init":ao,"/api/local-op/auth/login":Eo,"/api/local-op/auth/status":Po,"/api/local-op/auth/pat":Io,"/api/local-op/auth/gh-login":Mo,"/api/local-op/auth/repos":Ro,"/api/local-op/auth/signout":Vo,"/api/local-op/auth/set-identity":Wo,"/api/local-op/embeddings/set-key":Vc,"/api/local-op/embeddings/clear-key":Hc,"/api/installed-agents":ns,"/api/spawn-cursor":Sc,"/api/handoff":xc,"/api/install-skill":ts,"/api/skill/install-state":bc,"/api/seed/plan":Qo,"/api/seed/apply":$o,"/api/seed/packs":es,"/api/client-logs":jc};ge&&(ll[`/api/test-reset`]=la,ll[`/api/test-flush-git`]=ca,ll[`/api/test-rescan-backlinks`]=ua,ll[`/api/test-rescan-files`]=j);let pl=new Set(`/api/upload./api/lint/markdownlint-config./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 n=e.url?.split(`?`)[0];if(!n)return;let r=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};vk({ts:Date.now(),url:n,method:e.method??``,ua:r(`user-agent`),origin:r(`origin`),referer:r(`referer`),host:r(`host`),remote:e.socket?.remoteAddress,secChUa:r(`sec-ch-ua`),secChUaMobile:r(`sec-ch-ua-mobile`),secChUaPlatform:r(`sec-ch-ua-platform`),secFetchSite:r(`sec-fetch-site`),secFetchDest:r(`sec-fetch-dest`),secFetchMode:r(`sec-fetch-mode`),secFetchUser:r(`sec-fetch-user`)});let i=e.method??`GET`,a=n;n.startsWith(`/api/history/`)?a=`/api/history/:sha`:n.startsWith(`/api/tags/`)?a=`/api/tags/:name`:ll[n]||(a=`/api/*`);let o=n.startsWith(`/api/`)?Vre(e):void 0;if(o!==void 0&&(Hre(e,o),typeof t.setHeader==`function`&&t.setHeader(Gx,o),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Y.info({event:`api.access`,requestId:o,method:i,route:a,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${i} ${a} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!OE(n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),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, ${Gx}, ${he.protocol}, ${he.runtime}, ${he.kind}`),t.setHeader(`Access-Control-Expose-Headers`,Gx)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(pl.has(n)||ml.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!zB(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!BB(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(sn&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!zB(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!BB(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!n.startsWith(`/api/`))return;let s=Ia.extract(za.active(),e.headers),c=Qa(),l=Date.now();await za.with(s,()=>c.startActiveSpan(`HTTP ${i} ${a}`,{kind:La.SERVER,attributes:{[wo]:i,[So]:a,[gee]:n,[hee]:`http`,[xo]:e.headers[`user-agent`]??``,"ok.request.id":o}},async r=>{try{let a=ll[n],o=!1;if(a)o=!0,await a(e,t);else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&(o=!0,await fa(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await is(e,t,r))}o||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${i} ${n}`});let s=t.statusCode;r.setAttribute(Oo,s),s>=500&&r.setStatus({code:Fa.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:Fa.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:a,cause:e}),e}finally{r.end();let e=(Date.now()-l)/1e3;KU().record(e,{[wo]:i,[So]:a,[Oo]:t.statusCode})}}))}}}function xG(e){let t=e?.code;return typeof t==`string`?t:void 0}function SG(e){let t;try{t=il(e.contentDir,{withFileTypes:!0})}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Ix(n.name,Vi)&&e.basenameIndex.add(n.name)}async function CG(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await wl(i,{withFileTypes:!0})}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=kE(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Sl(a)}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Tl(a)}catch(t){let n=xG(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!AE(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await El(i)}catch(t){let n=xG(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()&&Ix(a,Xi)&&!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()&&Ix(a,Xi)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const wG=A({principalId:P().optional(),tabSessionId:P().optional(),expectedServerInstanceId:P().optional(),expectedBranch:P().optional(),expectedDocLineageEpoch:P().optional(),clientProtocolVersion:N().optional(),clientRuntimeVersion:P().optional(),clientKind:P().optional()}).loose(),TG=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function EG(e){return TG.includes(e)}function DG(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function OG(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!EG(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 kG=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=DG(e,this.payload)}};function AG(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=wG.safeParse(t);return n.success?n.data:void 0}var jG=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const MG=I(`conflict-storage`);var NG=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(ZE(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){MG.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){MG.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=Rc(this.storePath);B(e)||$c(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};fl(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){MG.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){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=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-BGt8xT_1.mjs`),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!AE(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);fl(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),MG.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await wP(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){MG.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}),MG.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})}}};function PG(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 FG(e,t){let n=ZE(e);try{$c(n,{recursive:!0}),fl(L(n,le),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=To(e);$c(Rc(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`};fl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const IG=new Map;let LG=!1;function RG(e,t){try{let n=PG(e,t);for(let e of IG.keys())FG(e,n)}catch{}}function zG(e){IG.set(e,(IG.get(e)??0)+1),LG||(LG=!0,process.on(`uncaughtExceptionMonitor`,RG));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=IG.get(e)??0;n<=1?IG.delete(e):IG.set(e,n-1)}}}function BG(e){let t=e.scheduler??p,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 VG(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function HG(e){if(!B(e))return{};let t;try{t=(0,xE.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(!VG(t))return{};let n=t.telemetry;if(!VG(n))return{};let r=n.localSink;return VG(r)?r:{}}function UG(e){return typeof e==`boolean`?e:void 0}function WG(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function GG(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function KG(e){if(VG(e))return WG(e.maxBytes)}function qG(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=HG(qa(`project`,e.projectDir)),n=HG(qa(`project-local`,e.projectDir));if((UG(n.enabled)??UG(t.enabled)??!0)===!1)return null;let r=KG(n.spans)??KG(t.spans)??52428800,i=KG(n.logs)??KG(t.logs)??26214400,a=GG(n.attributeDenylist)??GG(t.attributeDenylist)??ta;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var JG;(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})(JG||={});var YG;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(YG||={});const XG=JG.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),ZG=e=>{switch(typeof e){case`undefined`:return XG.undefined;case`string`:return XG.string;case`number`:return Number.isNaN(e)?XG.nan:XG.number;case`boolean`:return XG.boolean;case`function`:return XG.function;case`bigint`:return XG.bigint;case`symbol`:return XG.symbol;case`object`:return Array.isArray(e)?XG.array:e===null?XG.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?XG.promise:typeof Map<`u`&&e instanceof Map?XG.map:typeof Set<`u`&&e instanceof Set?XG.set:typeof Date<`u`&&e instanceof Date?XG.date:XG.object;default:return XG.unknown}},X=JG.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 QG=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,JG.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()}};QG.create=e=>new QG(e);const $G=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===XG.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,JG.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${JG.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${JG.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${JG.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}"`:JG.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,JG.assertNever(e)}return{message:n}};let eK=$G;function tK(){return eK}const nK=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 rK(e,t){let n=tK(),r=nK({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===$G?void 0:$G].filter(e=>!!e)});e.common.issues.push(r)}var iK=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 aK;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 aK;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 aK=Object.freeze({status:`aborted`}),oK=e=>({status:`dirty`,value:e}),sK=e=>({status:`valid`,value:e}),cK=e=>e.status===`aborted`,lK=e=>e.status===`dirty`,uK=e=>e.status===`valid`,dK=e=>typeof Promise<`u`&&e instanceof Promise;var fK;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(fK||={});var pK=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 mK=(e,t)=>{if(uK(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 QG(e.common.issues);return this._error=t,this._error}}};function hK(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 gK=class{get description(){return this._def.description}_getType(e){return ZG(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ZG(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new iK,ctx:{common:e.parent.common,data:e.data,parsedType:ZG(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(dK(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:ZG(e)};return mK(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:ZG(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return uK(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=>uK(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:ZG(e)},r=this._parse({data:e,path:n.path,parent:n});return mK(n,await(dK(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 vq({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 yq.create(this,this._def)}nullable(){return bq.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $K.create(this)}promise(){return _q.create(this,this._def)}or(e){return nq.create([this,e],this._def)}and(e){return oq.create(this,e,this._def)}transform(e){return new vq({...hK(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new xq({...hK(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new wq({typeName:Z.ZodBranded,type:this,...hK(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Sq({...hK(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 Tq.create(this,e)}readonly(){return Eq.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const _K=/^c[^\s-]{8,}$/i,vK=/^[0-9a-z]+$/,yK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bK=/^[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,xK=/^[a-z0-9_-]{21}$/i,SK=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,CK=/^[-+]?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)?)??$/,wK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let TK;const EK=/^(?:(?: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])$/,DK=/^(?:(?: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])$/,OK=/^(([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]))$/,kK=/^(([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])$/,AK=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jK=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,MK=`((\\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])))`,NK=RegExp(`^${MK}$`);function PK(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 FK(e){return RegExp(`^${PK(e)}$`)}function IK(e){let t=`${MK}T${PK(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function LK(e,t){return!!((t===`v4`||!t)&&EK.test(e)||(t===`v6`||!t)&&OK.test(e))}function RK(e,t){if(!SK.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 zK(e,t){return!!((t===`v4`||!t)&&DK.test(e)||(t===`v6`||!t)&&kK.test(e))}var BK=class e extends gK{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==XG.string){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.string,received:t.parsedType}),aK}let t=new iK,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),rK(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),rK(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?rK(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&rK(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)wK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)TK||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),TK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)bK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)xK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)_K.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)vK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)yK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(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),rK(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),rK(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),rK(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),rK(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),rK(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?IK(r).test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?NK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?FK(r).test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?CK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?LK(e.data,r.version)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?RK(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?zK(e.data,r.version)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?AK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?jK.test(e.data)||(n=this._getOrReturnCtx(e,n),rK(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):JG.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,...fK.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...fK.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...fK.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...fK.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...fK.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...fK.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...fK.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...fK.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...fK.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...fK.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...fK.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...fK.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...fK.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...fK.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,...fK.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,...fK.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...fK.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...fK.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...fK.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...fK.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...fK.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...fK.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...fK.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...fK.errToObj(t)})}nonempty(e){return this.min(1,fK.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}};BK.create=e=>new BK({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...hK(e)});function VK(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 HK=class e extends gK{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)!==XG.number){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.number,received:t.parsedType}),aK}let t,n=new iK;for(let r of this._def.checks)r.kind===`int`?JG.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),rK(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),rK(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),rK(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?VK(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),rK(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),rK(t,{code:X.not_finite,message:r.message}),n.dirty()):JG.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,fK.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,fK.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,fK.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,fK.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:fK.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:fK.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:fK.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:fK.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:fK.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:fK.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:fK.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:fK.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:fK.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:fK.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`&&JG.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)}};HK.create=e=>new HK({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...hK(e)});var UK=class e extends gK{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)!==XG.bigint)return this._getInvalidInput(e);let t,n=new iK;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),rK(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),rK(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),rK(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):JG.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.bigint,received:t.parsedType}),aK}gte(e,t){return this.setLimit(`min`,e,!0,fK.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,fK.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,fK.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,fK.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:fK.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:fK.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:fK.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:fK.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:fK.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:fK.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}};UK.create=e=>new UK({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...hK(e)});var WK=class extends gK{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==XG.boolean){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.boolean,received:t.parsedType}),aK}return sK(e.data)}};WK.create=e=>new WK({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...hK(e)});var GK=class e extends gK{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==XG.date){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.date,received:t.parsedType}),aK}if(Number.isNaN(e.data.getTime()))return rK(this._getOrReturnCtx(e),{code:X.invalid_date}),aK;let t=new iK,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),rK(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),rK(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):JG.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:fK.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:fK.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)}};GK.create=e=>new GK({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...hK(e)});var KK=class extends gK{_parse(e){if(this._getType(e)!==XG.symbol){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.symbol,received:t.parsedType}),aK}return sK(e.data)}};KK.create=e=>new KK({typeName:Z.ZodSymbol,...hK(e)});var qK=class extends gK{_parse(e){if(this._getType(e)!==XG.undefined){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.undefined,received:t.parsedType}),aK}return sK(e.data)}};qK.create=e=>new qK({typeName:Z.ZodUndefined,...hK(e)});var JK=class extends gK{_parse(e){if(this._getType(e)!==XG.null){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.null,received:t.parsedType}),aK}return sK(e.data)}};JK.create=e=>new JK({typeName:Z.ZodNull,...hK(e)});var YK=class extends gK{constructor(){super(...arguments),this._any=!0}_parse(e){return sK(e.data)}};YK.create=e=>new YK({typeName:Z.ZodAny,...hK(e)});var XK=class extends gK{constructor(){super(...arguments),this._unknown=!0}_parse(e){return sK(e.data)}};XK.create=e=>new XK({typeName:Z.ZodUnknown,...hK(e)});var ZK=class extends gK{_parse(e){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.never,received:t.parsedType}),aK}};ZK.create=e=>new ZK({typeName:Z.ZodNever,...hK(e)});var QK=class extends gK{_parse(e){if(this._getType(e)!==XG.undefined){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.void,received:t.parsedType}),aK}return sK(e.data)}};QK.create=e=>new QK({typeName:Z.ZodVoid,...hK(e)});var $K=class e extends gK{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==XG.array)return rK(t,{code:X.invalid_type,expected:XG.array,received:t.parsedType}),aK;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(rK(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&&(rK(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&&(rK(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 pK(t,e,t.path,n)))).then(e=>iK.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new pK(t,e,t.path,n)));return iK.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:fK.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:fK.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:fK.toString(n)}})}nonempty(e){return this.min(1,e)}};$K.create=(e,t)=>new $K({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...hK(t)});function eq(e){if(e instanceof tq){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=yq.create(eq(r))}return new tq({...e._def,shape:()=>t})}else if(e instanceof $K)return new $K({...e._def,type:eq(e.element)});else if(e instanceof yq)return yq.create(eq(e.unwrap()));else if(e instanceof bq)return bq.create(eq(e.unwrap()));else if(e instanceof sq)return sq.create(e.items.map(e=>eq(e)));else return e}var tq=class e extends gK{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=JG.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==XG.object){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.object,received:t.parsedType}),aK}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ZK&&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 pK(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof ZK){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&&(rK(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 pK(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=>iK.mergeObjectSync(t,e)):iK.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return fK.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:fK.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 JG.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 JG.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return eq(this)}partial(t){let n={};for(let e of JG.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 JG.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof yq;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return mq(JG.objectKeys(this.shape))}};tq.create=(e,t)=>new tq({shape:()=>e,unknownKeys:`strip`,catchall:ZK.create(),typeName:Z.ZodObject,...hK(t)}),tq.strictCreate=(e,t)=>new tq({shape:()=>e,unknownKeys:`strict`,catchall:ZK.create(),typeName:Z.ZodObject,...hK(t)}),tq.lazycreate=(e,t)=>new tq({shape:e,unknownKeys:`strip`,catchall:ZK.create(),typeName:Z.ZodObject,...hK(t)});var nq=class extends gK{_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 QG(e.ctx.common.issues));return rK(t,{code:X.invalid_union,unionErrors:n}),aK}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 QG(e));return rK(t,{code:X.invalid_union,unionErrors:i}),aK}}get options(){return this._def.options}};nq.create=(e,t)=>new nq({options:e,typeName:Z.ZodUnion,...hK(t)});const rq=e=>e instanceof fq?rq(e.schema):e instanceof vq?rq(e.innerType()):e instanceof pq?[e.value]:e instanceof hq?e.options:e instanceof gq?JG.objectValues(e.enum):e instanceof xq?rq(e._def.innerType):e instanceof qK?[void 0]:e instanceof JK?[null]:e instanceof yq?[void 0,...rq(e.unwrap())]:e instanceof bq?[null,...rq(e.unwrap())]:e instanceof wq||e instanceof Eq?rq(e.unwrap()):e instanceof Sq?rq(e._def.innerType):[];var iq=class e extends gK{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==XG.object)return rK(t,{code:X.invalid_type,expected:XG.object,received:t.parsedType}),aK;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}):(rK(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),aK)}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=rq(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,...hK(r)})}};function aq(e,t){let n=ZG(e),r=ZG(t);if(e===t)return{valid:!0,data:e};if(n===XG.object&&r===XG.object){let n=JG.objectKeys(t),r=JG.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=aq(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===XG.array&&r===XG.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=aq(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===XG.date&&r===XG.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var oq=class extends gK{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(cK(e)||cK(r))return aK;let i=aq(e.value,r.value);return i.valid?((lK(e)||lK(r))&&t.dirty(),{status:t.value,value:i.data}):(rK(n,{code:X.invalid_intersection_types}),aK)};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}))}};oq.create=(e,t,n)=>new oq({left:e,right:t,typeName:Z.ZodIntersection,...hK(n)});var sq=class e extends gK{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==XG.array)return rK(n,{code:X.invalid_type,expected:XG.array,received:n.parsedType}),aK;if(n.data.length<this._def.items.length)return rK(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),aK;!this._def.rest&&n.data.length>this._def.items.length&&(rK(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 pK(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>iK.mergeArray(t,e)):iK.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};sq.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new sq({items:e,typeName:Z.ZodTuple,rest:null,...hK(t)})};var cq=class e extends gK{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!==XG.object)return rK(n,{code:X.invalid_type,expected:XG.object,received:n.parsedType}),aK;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new pK(n,e,n.path,e)),value:a._parse(new pK(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?iK.mergeObjectAsync(t,r):iK.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof gK?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...hK(r)}):new e({keyType:BK.create(),valueType:t,typeName:Z.ZodRecord,...hK(n)})}},lq=class extends gK{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!==XG.map)return rK(n,{code:X.invalid_type,expected:XG.map,received:n.parsedType}),aK;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new pK(n,e,n.path,[a,`key`])),value:i._parse(new pK(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 aK;(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 aK;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};lq.create=(e,t,n)=>new lq({valueType:t,keyType:e,typeName:Z.ZodMap,...hK(n)});var uq=class e extends gK{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==XG.set)return rK(n,{code:X.invalid_type,expected:XG.set,received:n.parsedType}),aK;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(rK(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&&(rK(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 aK;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 pK(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:fK.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:fK.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};uq.create=(e,t)=>new uq({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...hK(t)});var dq=class e extends gK{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==XG.function)return rK(t,{code:X.invalid_type,expected:XG.function,received:t.parsedType}),aK;function n(e,n){return nK({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tK(),$G].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return nK({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tK(),$G].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 _q){let e=this;return sK(async function(...t){let o=new QG([]),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 sK(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new QG([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new QG([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:sq.create(t).rest(XK.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||sq.create([]).rest(XK.create()),returns:n||XK.create(),typeName:Z.ZodFunction,...hK(r)})}},fq=class extends gK{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})}};fq.create=(e,t)=>new fq({getter:e,typeName:Z.ZodLazy,...hK(t)});var pq=class extends gK{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return rK(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),aK}return{status:`valid`,value:e.data}}get value(){return this._def.value}};pq.create=(e,t)=>new pq({value:e,typeName:Z.ZodLiteral,...hK(t)});function mq(e,t){return new hq({values:e,typeName:Z.ZodEnum,...hK(t)})}var hq=class e extends gK{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return rK(t,{expected:JG.joinValues(n),received:t.parsedType,code:X.invalid_type}),aK}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return rK(t,{received:t.data,code:X.invalid_enum_value,options:n}),aK}return sK(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})}};hq.create=mq;var gq=class extends gK{_parse(e){let t=JG.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==XG.string&&n.parsedType!==XG.number){let e=JG.objectValues(t);return rK(n,{expected:JG.joinValues(e),received:n.parsedType,code:X.invalid_type}),aK}if(this._cache||=new Set(JG.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=JG.objectValues(t);return rK(n,{received:n.data,code:X.invalid_enum_value,options:e}),aK}return sK(e.data)}get enum(){return this._def.values}};gq.create=(e,t)=>new gq({values:e,typeName:Z.ZodNativeEnum,...hK(t)});var _q=class extends gK{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==XG.promise&&t.common.async===!1?(rK(t,{code:X.invalid_type,expected:XG.promise,received:t.parsedType}),aK):sK((t.parsedType===XG.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_q.create=(e,t)=>new _q({type:e,typeName:Z.ZodPromise,...hK(t)});var vq=class extends gK{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=>{rK(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 aK;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?aK:r.status===`dirty`||t.value===`dirty`?oK(r.value):r});{if(t.value===`aborted`)return aK;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?aK:r.status===`dirty`||t.value===`dirty`?oK(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`?aK:(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`?aK:(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(!uK(e))return aK;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=>uK(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):aK);JG.assertNever(r)}};vq.create=(e,t,n)=>new vq({schema:e,typeName:Z.ZodEffects,effect:t,...hK(n)}),vq.createWithPreprocess=(e,t,n)=>new vq({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...hK(n)});var yq=class extends gK{_parse(e){return this._getType(e)===XG.undefined?sK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yq.create=(e,t)=>new yq({innerType:e,typeName:Z.ZodOptional,...hK(t)});var bq=class extends gK{_parse(e){return this._getType(e)===XG.null?sK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bq.create=(e,t)=>new bq({innerType:e,typeName:Z.ZodNullable,...hK(t)});var xq=class extends gK{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===XG.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};xq.create=(e,t)=>new xq({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...hK(t)});var Sq=class extends gK{_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 dK(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new QG(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new QG(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Sq.create=(e,t)=>new Sq({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...hK(t)});var Cq=class extends gK{_parse(e){if(this._getType(e)!==XG.nan){let t=this._getOrReturnCtx(e);return rK(t,{code:X.invalid_type,expected:XG.nan,received:t.parsedType}),aK}return{status:`valid`,value:e.data}}};Cq.create=e=>new Cq({typeName:Z.ZodNaN,...hK(e)});var wq=class extends gK{_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}},Tq=class e extends gK{_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`?aK:e.status===`dirty`?(t.dirty(),oK(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`?aK: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})}},Eq=class extends gK{_parse(e){let t=this._def.innerType._parse(e),n=e=>(uK(e)&&(e.value=Object.freeze(e.value)),e);return dK(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Eq.create=(e,t)=>new Eq({innerType:e,typeName:Z.ZodReadonly,...hK(t)}),tq.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||={}),BK.create,HK.create,Cq.create,UK.create,WK.create,GK.create,KK.create,qK.create,JK.create,YK.create,XK.create,ZK.create,QK.create,$K.create;const Dq=tq.create;tq.strictCreate,nq.create,iq.create,oq.create,sq.create,cq.create,lq.create,uq.create,dq.create,fq.create,pq.create,hq.create,gq.create,_q.create,vq.create,yq.create,bq.create,vq.createWithPreprocess,Tq.create;const Oq=Wi(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ka.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Na(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ma(e,t,n),e.parseAsync=async(t,n)=>ua(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>na(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)=>ja(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),kq=Wi(`ZodMiniObject`,(e,t)=>{la.init(e,t),Oq.init(e,t),ia(e,`shape`,()=>t.shape)});function Aq(e,t){return new kq({type:`object`,shape:e??{},...Gi(t)})}function jq(e){return!!e._zod}function Mq(e){let t=Object.values(e);if(t.length===0)return Aq({});let n=t.every(jq),r=t.every(e=>!jq(e));if(n)return Aq(e);if(r)return Dq(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Nq(e,t){return jq(e)?Ma(e,t):e.safeParse(t)}async function Pq(e,t){return jq(e)?await na(e,t):await e.safeParseAsync(t)}function Fq(e){if(!e)return;let t;if(t=jq(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Iq(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 Mq(e)}}if(jq(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 Lq(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 Rq(e){return e.description}function zq(e){if(jq(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Bq(e){if(jq(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 Vq=`2025-11-25`,Hq=[Vq,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Uq=`io.modelcontextprotocol/related-task`,Wq=sa(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Gq=Oa([P(),N().int()]),Kq=P();wa({ttl:N().optional(),pollInterval:N().optional()});const qq=A({ttl:N().optional()}),Jq=A({taskId:P()}),Yq=wa({progressToken:Gq.optional(),[Uq]:Jq.optional()}),Xq=A({_meta:Yq.optional()}),Zq=Xq.extend({task:qq.optional()}),Qq=e=>Zq.safeParse(e).success,$q=A({method:P(),params:Xq.loose().optional()}),eJ=A({_meta:Yq.optional()}),tJ=A({method:P(),params:eJ.loose().optional()}),nJ=wa({_meta:Yq.optional()}),rJ=Oa([P(),N().int()]),iJ=A({jsonrpc:F(`2.0`),id:rJ,...$q.shape}).strict(),aJ=e=>iJ.safeParse(e).success,oJ=A({jsonrpc:F(`2.0`),...tJ.shape}).strict(),sJ=e=>oJ.safeParse(e).success,cJ=A({jsonrpc:F(`2.0`),id:rJ,result:nJ}).strict(),lJ=e=>cJ.safeParse(e).success;var uJ;(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`})(uJ||={});const dJ=A({jsonrpc:F(`2.0`),id:rJ.optional(),error:A({code:N().int(),message:P(),data:M().optional()})}).strict(),fJ=e=>dJ.safeParse(e).success,pJ=Oa([iJ,oJ,cJ,dJ]);Oa([cJ,dJ]);const mJ=nJ.strict(),hJ=eJ.extend({requestId:rJ.optional(),reason:P().optional()}),gJ=tJ.extend({method:F(`notifications/cancelled`),params:hJ}),_J=A({icons:k(A({src:P(),mimeType:P().optional(),sizes:k(P()).optional(),theme:Yi([`light`,`dark`]).optional()})).optional()}),vJ=A({name:P(),title:P().optional()}),yJ=vJ.extend({...vJ.shape,..._J.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),bJ=Ta(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,da(A({form:da(A({applyDefaults:O().optional()}),j(P(),M())).optional(),url:Wq.optional()}),j(P(),M()).optional())),xJ=wa({list:Wq.optional(),cancel:Wq.optional(),requests:wa({sampling:wa({createMessage:Wq.optional()}).optional(),elicitation:wa({create:Wq.optional()}).optional()}).optional()}),SJ=wa({list:Wq.optional(),cancel:Wq.optional(),requests:wa({tools:wa({call:Wq.optional()}).optional()}).optional()}),CJ=A({experimental:j(P(),Wq).optional(),sampling:A({context:Wq.optional(),tools:Wq.optional()}).optional(),elicitation:bJ.optional(),roots:A({listChanged:O().optional()}).optional(),tasks:xJ.optional(),extensions:j(P(),Wq).optional()}),wJ=Xq.extend({protocolVersion:P(),capabilities:CJ,clientInfo:yJ}),TJ=$q.extend({method:F(`initialize`),params:wJ}),EJ=e=>TJ.safeParse(e).success,DJ=A({experimental:j(P(),Wq).optional(),logging:Wq.optional(),completions:Wq.optional(),prompts:A({listChanged:O().optional()}).optional(),resources:A({subscribe:O().optional(),listChanged:O().optional()}).optional(),tools:A({listChanged:O().optional()}).optional(),tasks:SJ.optional(),extensions:j(P(),Wq).optional()}),OJ=nJ.extend({protocolVersion:P(),capabilities:DJ,serverInfo:yJ,instructions:P().optional()}),kJ=tJ.extend({method:F(`notifications/initialized`),params:eJ.optional()}),AJ=e=>kJ.safeParse(e).success,jJ=$q.extend({method:F(`ping`),params:Xq.optional()}),MJ=A({progress:N(),total:ba(N()),message:ba(P())}),NJ=A({...eJ.shape,...MJ.shape,progressToken:Gq}),PJ=tJ.extend({method:F(`notifications/progress`),params:NJ}),FJ=Xq.extend({cursor:Kq.optional()}),IJ=$q.extend({params:FJ.optional()}),LJ=nJ.extend({nextCursor:Kq.optional()}),RJ=Yi([`working`,`input_required`,`completed`,`failed`,`cancelled`]),zJ=A({taskId:P(),status:RJ,ttl:Oa([N(),Sa()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:ba(N()),statusMessage:ba(P())}),BJ=nJ.extend({task:zJ}),VJ=eJ.merge(zJ),HJ=tJ.extend({method:F(`notifications/tasks/status`),params:VJ}),UJ=$q.extend({method:F(`tasks/get`),params:Xq.extend({taskId:P()})}),WJ=nJ.merge(zJ),GJ=$q.extend({method:F(`tasks/result`),params:Xq.extend({taskId:P()})});nJ.loose();const KJ=IJ.extend({method:F(`tasks/list`)}),qJ=LJ.extend({tasks:k(zJ)}),JJ=$q.extend({method:F(`tasks/cancel`),params:Xq.extend({taskId:P()})}),YJ=nJ.merge(zJ),XJ=A({uri:P(),mimeType:ba(P()),_meta:j(P(),M()).optional()}),ZJ=XJ.extend({text:P()}),QJ=P().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),$J=XJ.extend({blob:QJ}),eY=Yi([`user`,`assistant`]),tY=A({audience:k(eY).optional(),priority:N().min(0).max(1).optional(),lastModified:xa({offset:!0}).optional()}),nY=A({...vJ.shape,..._J.shape,uri:P(),description:ba(P()),mimeType:ba(P()),size:ba(N()),annotations:tY.optional(),_meta:ba(wa({}))}),rY=A({...vJ.shape,..._J.shape,uriTemplate:P(),description:ba(P()),mimeType:ba(P()),annotations:tY.optional(),_meta:ba(wa({}))}),iY=IJ.extend({method:F(`resources/list`)}),aY=LJ.extend({resources:k(nY)}),oY=IJ.extend({method:F(`resources/templates/list`)}),sY=LJ.extend({resourceTemplates:k(rY)}),cY=Xq.extend({uri:P()}),lY=cY,uY=$q.extend({method:F(`resources/read`),params:lY}),dY=nJ.extend({contents:k(Oa([ZJ,$J]))}),fY=tJ.extend({method:F(`notifications/resources/list_changed`),params:eJ.optional()}),pY=cY,mY=$q.extend({method:F(`resources/subscribe`),params:pY}),hY=cY,gY=$q.extend({method:F(`resources/unsubscribe`),params:hY}),_Y=eJ.extend({uri:P()}),vY=tJ.extend({method:F(`notifications/resources/updated`),params:_Y}),yY=A({name:P(),description:ba(P()),required:ba(O())}),bY=A({...vJ.shape,..._J.shape,description:ba(P()),arguments:ba(k(yY)),_meta:ba(wa({}))}),xY=IJ.extend({method:F(`prompts/list`)}),SY=LJ.extend({prompts:k(bY)}),CY=Xq.extend({name:P(),arguments:j(P(),P()).optional()}),wY=$q.extend({method:F(`prompts/get`),params:CY}),TY=A({type:F(`text`),text:P(),annotations:tY.optional(),_meta:j(P(),M()).optional()}),EY=A({type:F(`image`),data:QJ,mimeType:P(),annotations:tY.optional(),_meta:j(P(),M()).optional()}),DY=A({type:F(`audio`),data:QJ,mimeType:P(),annotations:tY.optional(),_meta:j(P(),M()).optional()}),OY=A({type:F(`tool_use`),name:P(),id:P(),input:j(P(),M()),_meta:j(P(),M()).optional()}),kY=A({type:F(`resource`),resource:Oa([ZJ,$J]),annotations:tY.optional(),_meta:j(P(),M()).optional()}),AY=Oa([TY,EY,DY,nY.extend({type:F(`resource_link`)}),kY]),jY=A({role:eY,content:AY}),MY=nJ.extend({description:P().optional(),messages:k(jY)}),NY=tJ.extend({method:F(`notifications/prompts/list_changed`),params:eJ.optional()}),PY=A({title:P().optional(),readOnlyHint:O().optional(),destructiveHint:O().optional(),idempotentHint:O().optional(),openWorldHint:O().optional()}),FY=A({taskSupport:Yi([`required`,`optional`,`forbidden`]).optional()}),IY=A({...vJ.shape,..._J.shape,description:P().optional(),inputSchema:A({type:F(`object`),properties:j(P(),Wq).optional(),required:k(P()).optional()}).catchall(M()),outputSchema:A({type:F(`object`),properties:j(P(),Wq).optional(),required:k(P()).optional()}).catchall(M()).optional(),annotations:PY.optional(),execution:FY.optional(),_meta:j(P(),M()).optional()}),LY=IJ.extend({method:F(`tools/list`)}),RY=LJ.extend({tools:k(IY)}),zY=nJ.extend({content:k(AY).default([]),structuredContent:j(P(),M()).optional(),isError:O().optional()});zY.or(nJ.extend({toolResult:M()}));const BY=Zq.extend({name:P(),arguments:j(P(),M()).optional()}),VY=$q.extend({method:F(`tools/call`),params:BY}),HY=tJ.extend({method:F(`notifications/tools/list_changed`),params:eJ.optional()});A({autoRefresh:O().default(!0),debounceMs:N().int().nonnegative().default(300)});const UY=Yi([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),WY=Xq.extend({level:UY}),GY=$q.extend({method:F(`logging/setLevel`),params:WY}),KY=eJ.extend({level:UY,logger:P().optional(),data:M()}),qY=tJ.extend({method:F(`notifications/message`),params:KY}),JY=A({hints:k(A({name:P().optional()})).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),YY=A({mode:Yi([`auto`,`required`,`none`]).optional()}),XY=A({type:F(`tool_result`),toolUseId:P().describe(`The unique identifier for the corresponding tool call.`),content:k(AY).default([]),structuredContent:A({}).loose().optional(),isError:O().optional(),_meta:j(P(),M()).optional()}),ZY=$i(`type`,[TY,EY,DY]),QY=$i(`type`,[TY,EY,DY,OY,XY]),$Y=A({role:eY,content:Oa([QY,k(QY)]),_meta:j(P(),M()).optional()}),eX=Zq.extend({messages:k($Y),modelPreferences:JY.optional(),systemPrompt:P().optional(),includeContext:Yi([`none`,`thisServer`,`allServers`]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:k(P()).optional(),metadata:Wq.optional(),tools:k(IY).optional(),toolChoice:YY.optional()}),tX=$q.extend({method:F(`sampling/createMessage`),params:eX}),nX=nJ.extend({model:P(),stopReason:ba(Yi([`endTurn`,`stopSequence`,`maxTokens`]).or(P())),role:eY,content:ZY}),rX=nJ.extend({model:P(),stopReason:ba(Yi([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(P())),role:eY,content:Oa([QY,k(QY)])}),iX=A({type:F(`boolean`),title:P().optional(),description:P().optional(),default:O().optional()}),aX=A({type:F(`string`),title:P().optional(),description:P().optional(),minLength:N().optional(),maxLength:N().optional(),format:Yi([`email`,`uri`,`date`,`date-time`]).optional(),default:P().optional()}),oX=A({type:Yi([`number`,`integer`]),title:P().optional(),description:P().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),sX=A({type:F(`string`),title:P().optional(),description:P().optional(),enum:k(P()),default:P().optional()}),cX=A({type:F(`string`),title:P().optional(),description:P().optional(),oneOf:k(A({const:P(),title:P()})),default:P().optional()}),lX=Oa([Oa([A({type:F(`string`),title:P().optional(),description:P().optional(),enum:k(P()),enumNames:k(P()).optional(),default:P().optional()}),Oa([sX,cX]),Oa([A({type:F(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:A({type:F(`string`),enum:k(P())}),default:k(P()).optional()}),A({type:F(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:A({anyOf:k(A({const:P(),title:P()}))}),default:k(P()).optional()})])]),iX,aX,oX]),uX=Oa([Zq.extend({mode:F(`form`).optional(),message:P(),requestedSchema:A({type:F(`object`),properties:j(P(),lX),required:k(P()).optional()})}),Zq.extend({mode:F(`url`),message:P(),elicitationId:P(),url:P().url()})]),dX=$q.extend({method:F(`elicitation/create`),params:uX}),fX=eJ.extend({elicitationId:P()}),pX=tJ.extend({method:F(`notifications/elicitation/complete`),params:fX}),mX=nJ.extend({action:Yi([`accept`,`decline`,`cancel`]),content:Ta(e=>e===null?void 0:e,j(P(),Oa([P(),N(),O(),k(P())])).optional())}),hX=A({type:F(`ref/resource`),uri:P()}),gX=A({type:F(`ref/prompt`),name:P()}),_X=Xq.extend({ref:Oa([gX,hX]),argument:A({name:P(),value:P()}),context:A({arguments:j(P(),P()).optional()}).optional()}),vX=$q.extend({method:F(`completion/complete`),params:_X});function yX(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function bX(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const xX=nJ.extend({completion:wa({values:k(P()).max(100),total:ba(N().int()),hasMore:ba(O())})}),SX=A({uri:P().startsWith(`file://`),name:P().optional(),_meta:j(P(),M()).optional()}),CX=$q.extend({method:F(`roots/list`),params:Xq.optional()}),wX=nJ.extend({roots:k(SX)}),TX=tJ.extend({method:F(`notifications/roots/list_changed`),params:eJ.optional()});Oa([jJ,TJ,vX,GY,wY,xY,iY,oY,uY,mY,gY,VY,LY,UJ,GJ,KJ,JJ]),Oa([gJ,PJ,kJ,TX,HJ]),Oa([mJ,nX,rX,mX,wX,WJ,qJ,BJ]),Oa([jJ,tX,dX,CX,UJ,GJ,KJ,JJ]),Oa([gJ,PJ,qY,vY,fY,HY,NY,HJ,pX]),Oa([mJ,OJ,xX,MY,SY,aY,sY,dY,zY,RY,WJ,qJ,BJ]);var EX=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===uJ.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new DX(e.elicitations,n)}return new e(t,n,r)}},DX=class extends EX{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(uJ.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function OX(e){return e===`completed`||e===`failed`||e===`cancelled`}const kX=Symbol(`Let zodToJsonSchema decide on which parser to use`),AX={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`},jX=e=>typeof e==`string`?{...AX,name:e}:{...AX,...e},MX=e=>{let t=jX(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 NX(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function PX(e,t,n,r,i){e[t]=n,NX(e,t,r,i)}const FX=(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 IX(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?FX(t,e.currentPath):t.join(`/`)}}function LX(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=DZ(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&PX(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&PX(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(PX(n,`minItems`,e.exactLength.value,e.exactLength.message,t),PX(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function RX(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?PX(n,`minimum`,r.value,r.message,t):PX(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),PX(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?PX(n,`maximum`,r.value,r.message,t):PX(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),PX(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:PX(n,`multipleOf`,r.value,r.message,t);break}return n}function zX(){return{type:`boolean`}}function BX(e,t){return DZ(e.type._def,t)}const VX=(e,t)=>DZ(e.innerType._def,t);function HX(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>HX(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 UX(e,t)}}const UX=(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`:PX(n,`minimum`,r.value,r.message,t);break;case`max`:PX(n,`maximum`,r.value,r.message,t);break}return n};function WX(e,t){return{...DZ(e.innerType._def,t),default:e.defaultValue()}}function GX(e,t){return t.effectStrategy===`input`?DZ(e.schema._def,t):IX(t)}function KX(e){return{type:`string`,enum:Array.from(e.values)}}const qX=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function JX(e,t){let n=[DZ(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),DZ(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(qX(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 YX(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 XX;const ZX={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:()=>(XX===void 0&&(XX=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),XX),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 QX(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:PX(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:PX(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`:nZ(n,`email`,r.message,t);break;case`format:idn-email`:nZ(n,`idn-email`,r.message,t);break;case`pattern:zod`:rZ(n,ZX.email,r.message,t);break}break;case`url`:nZ(n,`uri`,r.message,t);break;case`uuid`:nZ(n,`uuid`,r.message,t);break;case`regex`:rZ(n,r.regex,r.message,t);break;case`cuid`:rZ(n,ZX.cuid,r.message,t);break;case`cuid2`:rZ(n,ZX.cuid2,r.message,t);break;case`startsWith`:rZ(n,RegExp(`^${$X(r.value,t)}`),r.message,t);break;case`endsWith`:rZ(n,RegExp(`${$X(r.value,t)}$`),r.message,t);break;case`datetime`:nZ(n,`date-time`,r.message,t);break;case`date`:nZ(n,`date`,r.message,t);break;case`time`:nZ(n,`time`,r.message,t);break;case`duration`:nZ(n,`duration`,r.message,t);break;case`length`:PX(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),PX(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:rZ(n,RegExp($X(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&nZ(n,`ipv4`,r.message,t),r.version!==`v4`&&nZ(n,`ipv6`,r.message,t);break;case`base64url`:rZ(n,ZX.base64url,r.message,t);break;case`jwt`:rZ(n,ZX.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&rZ(n,ZX.ipv4Cidr,r.message,t),r.version!==`v4`&&rZ(n,ZX.ipv6Cidr,r.message,t);break;case`emoji`:rZ(n,ZX.emoji(),r.message,t);break;case`ulid`:rZ(n,ZX.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:nZ(n,`binary`,r.message,t);break;case`contentEncoding:base64`:PX(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:rZ(n,ZX.base64,r.message,t);break}break;case`nanoid`:rZ(n,ZX.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function $X(e,t){return t.patternStrategy===`escape`?tZ(e):e}const eZ=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function tZ(e){let t=``;for(let n=0;n<e.length;n++)eZ.has(e[n])||(t+=`\\`),t+=e[n];return t}function nZ(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}}})):PX(e,`format`,t,n,r)}function rZ(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:iZ(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):PX(e,`pattern`,iZ(t,r),n,r)}function iZ(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
1222
1222
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1223
1223
  ]))`;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 aZ(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]:DZ(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??IX(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:DZ(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}=QX(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}=BX(e.keyType._def,t);return{...n,propertyNames:i}}return n}function oZ(e,t){return t.mapStrategy===`record`?aZ(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[DZ(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||IX(t),DZ(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||IX(t)],minItems:2,maxItems:2}}}function sZ(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 cZ(e){return e.target===`openAi`?void 0:{not:IX({...e,currentPath:[...e.currentPath,`not`]})}}function lZ(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const uZ={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function dZ(e,t){if(t.target===`openApi3`)return fZ(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in uZ&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=uZ[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 fZ(e,t)}const fZ=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>DZ(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 pZ(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:uZ[e.innerType._def.typeName],nullable:!0}:{type:[uZ[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=DZ(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=DZ(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function mZ(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`,NX(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?PX(n,`minimum`,r.value,r.message,t):PX(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),PX(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?PX(n,`maximum`,r.value,r.message,t):PX(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),PX(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:PX(n,`multipleOf`,r.value,r.message,t);break}return n}function hZ(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=_Z(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=DZ(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=gZ(e,t);return o!==void 0&&(r.additionalProperties=o),r}function gZ(e,t){if(e.catchall._def.typeName!==`ZodNever`)return DZ(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 _Z(e){try{return e.isOptional()}catch{return!0}}const vZ=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return DZ(e.innerType._def,t);let n=DZ(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:IX(t)},n]}:IX(t)},yZ=(e,t)=>{if(t.pipeStrategy===`input`)return DZ(e.in._def,t);if(t.pipeStrategy===`output`)return DZ(e.out._def,t);let n=DZ(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,DZ(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function bZ(e,t){return DZ(e.type._def,t)}function xZ(e,t){let n={type:`array`,uniqueItems:!0,items:DZ(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&PX(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&PX(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function SZ(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>DZ(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:DZ(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>DZ(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function CZ(e){return{not:IX(e)}}function wZ(e){return IX(e)}const TZ=(e,t)=>DZ(e.innerType._def,t),EZ=(e,t,n)=>{switch(t){case Z.ZodString:return QX(e,n);case Z.ZodNumber:return mZ(e,n);case Z.ZodObject:return hZ(e,n);case Z.ZodBigInt:return RX(e,n);case Z.ZodBoolean:return zX();case Z.ZodDate:return HX(e,n);case Z.ZodUndefined:return CZ(n);case Z.ZodNull:return lZ(n);case Z.ZodArray:return LX(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return dZ(e,n);case Z.ZodIntersection:return JX(e,n);case Z.ZodTuple:return SZ(e,n);case Z.ZodRecord:return aZ(e,n);case Z.ZodLiteral:return YX(e,n);case Z.ZodEnum:return KX(e);case Z.ZodNativeEnum:return sZ(e);case Z.ZodNullable:return pZ(e,n);case Z.ZodOptional:return vZ(e,n);case Z.ZodMap:return oZ(e,n);case Z.ZodSet:return xZ(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return bZ(e,n);case Z.ZodNaN:case Z.ZodNever:return cZ(n);case Z.ZodEffects:return GX(e,n);case Z.ZodAny:return IX(n);case Z.ZodUnknown:return wZ(n);case Z.ZodDefault:return WX(e,n);case Z.ZodBranded:return BX(e,n);case Z.ZodReadonly:return TZ(e,n);case Z.ZodCatch:return VX(e,n);case Z.ZodPipeline:return yZ(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>void 0)(t)}};function DZ(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==kX)return i}if(r&&!n){let e=OZ(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=EZ(e,e.typeName,t),o=typeof a==`function`?DZ(a(),t):a;if(o&&kZ(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const OZ=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:FX(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`),IX(t)):t.$refStrategy===`seen`?IX(t):void 0}},kZ=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),AZ=(e,t)=>{let n=MX(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:DZ(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??IX(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=DZ(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??IX(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 jZ(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function MZ(e,t){return jq(e)?va(e,{target:jZ(t?.target),io:t?.pipeStrategy??`input`}):AZ(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function NZ(e){let t=Fq(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Bq(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function PZ(e,t){let n=Nq(e,t);if(!n.success)throw n.error;return n.data}var FZ=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(gJ,e=>{this._oncancel(e)}),this.setNotificationHandler(PJ,e=>{this._onprogress(e)}),this.setRequestHandler(jJ,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(UJ,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new EX(uJ.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(GJ,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 EX(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 EX(uJ.InvalidParams,`Task not found: ${r}`);if(!OX(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(OX(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Uq]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(KJ,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 EX(uJ.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(JJ,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new EX(uJ.InvalidParams,`Task not found: ${e.params.taskId}`);if(OX(n.status))throw new EX(uJ.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 EX(uJ.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof EX?e:new EX(uJ.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),EX.fromError(uJ.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),lJ(e)||fJ(e)?this._onresponse(e):aJ(e)?this._onrequest(e,t):sJ(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=EX.fromError(uJ.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?.[Uq]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:uJ.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=Qq(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 EX(uJ.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:uJ.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),lJ(e)?n(e):n(new EX(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(lJ(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),lJ(e)?r(e):r(EX.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 EX?e:new EX(uJ.InternalError,String(e))}}return}let i;try{let r=await this.request(e,BJ,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new EX(uJ.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},OX(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new EX(uJ.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new EX(uJ.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 EX?e:new EX(uJ.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||{},[Uq]: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 EX?e:new EX(uJ.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Nq(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(EX.fromError(uJ.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},WJ,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},qJ,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},YJ,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||{},[Uq]: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||{},[Uq]: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||{},[Uq]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=NZ(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=PZ(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=NZ(e);this._notificationHandlers.set(n,n=>{let r=PZ(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`&&aJ(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new EX(uJ.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 EX(uJ.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new EX(uJ.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 EX(uJ.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=HJ.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),OX(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 EX(uJ.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(OX(a.status))throw new EX(uJ.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=HJ.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),OX(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function IZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function LZ(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];IZ(a)&&IZ(i)?n[r]={...a,...i}:n[r]=i}return n}var RZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),zZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=RZ();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),BZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=RZ(),n=zZ();var r=RZ();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=zZ();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=E(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=E(this.rhs,e,n),this}get names(){return ne(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=E(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(re(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>te(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ie(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=E(this.condition,e,t),this}get names(){let e=super.names;return ne(e,this.condition),this.else&&te(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=E(this.iteration,e,t),this}get names(){return te(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return ne(ne(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=E(this.iterable,e,t),this}get names(){return te(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&te(e,this.catch.names),this.finally&&te(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
1224
1224
  `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function te(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ne(e,n){return n instanceof t._CodeOrName?te(e,n.names):e}function E(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function re(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ie(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ue(e)}`}e.not=ie;let ae=le(e.operators.AND);function oe(...e){return e.reduce(ae)}e.and=oe;let se=le(e.operators.OR);function ce(...e){return e.reduce(se)}e.or=ce;function le(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ue(n)} ${e} ${ue(r)}`}function ue(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),VZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=BZ(),n=RZ();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),HZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=BZ();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),UZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=BZ(),n=VZ(),r=HZ();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),WZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=UZ(),n=BZ(),r=HZ(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),GZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),KZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),qZ=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=GZ(),n=KZ(),r=UZ(),i=BZ(),a=VZ();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
@@ -3259,6 +3259,6 @@ native-divergence-injected
3259
3259
  `).split(`
3260
3260
  `),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=Dge(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(ZE(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(!Mx(e))try{let{frontmatter:n,body:r}=cn(t),i=We(n?mt(n):``),a=Oge(r),o=new Set([...i,...a]),s=new Set;for(let e of o)for(let t of oi(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(Mx(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=Mr(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(()=>cI(`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([El(t),Cl(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 Cl(e,`utf-8`))}catch(e){return v9.warn({err:e},`Failed to load tag snapshot; falling back to full rebuild`),!1}if(!Ege(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(Mx(e))continue;let t=new Set(n),r=new Set;for(let e of t)for(let t of oi(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 $a(Rc(e),{recursive:!0}),await Xa(e,JSON.stringify(t,null,2),`utf-8`)}reconcileWithDisk(){return this.enqueue(()=>cI(`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 El(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 Cl(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 wl(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=kE(R(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!Fx(r.name))continue;let i=kE(R(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:Lx(i),filePath:n})}}};let S9=!1;function C9(){if(S9)return;let e=jee;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){I(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const kge=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function Age(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(z6).join(` `)} auth git-credential`]}function jge(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Pc(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],hA({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return I(`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 I(`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(`
3261
3261
  `)){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(!ME(a,t))continue;let s=tR(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:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=I(`server`),b=new O5,x=()=>b.getActiveBranch(),S=e=>b.getReconciledBase(e),C=(e,t)=>b.setReconciledBase(e,t),w=e=>b.deleteReconciledBase(e),ee=e=>b.switchReconciledBaseScope(e),te=e=>b.setBatchInProgress(e),ne=()=>b.isBatchInProgress();function E(){let e=Wa({absPath:qa(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=Da(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function re(){let e=Wa({absPath:qa(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let r=Wa({absPath:qa(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),r.value.autoSync?.default===!0}function ae(){let e=Wa({absPath:qa(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Un(e):Wr}function oe(){return aA(n,{configHomedirOverride:u,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function se(){let e=Wa({absPath:qa(`project-local`,n,u),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function ce(e){return`${Kk(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function le(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=re(),mt?.setEnabled(t).catch(n=>{y.warn({err:n,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let n=oe();je.applyConfig({enabled:n.enabled,providerFingerprint:ce(n)}),y.info({docName:e,autoSyncEnabled:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}yo();let de=Il(),D=ZE(n),fe=new Du({localDir:D,log:I(`acp-registry`)}),pe=new bu(D,I(`acp-permissions`));if(Jo(D,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{a9({lockDir:D,shadowRepoDir:$l(n)})}catch(e){throw zo(D),e}let me=Qr(),he=(e,t)=>me.resolveEmbed(e,t),ge=(e,n)=>{let r=me.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=z(t,r);if(!AE(i,z(t)))return null;try{let e=ul(i);return e.isFile()?e.size:null}catch{return null}},_e,ve,ye,be,xe,Se,Ce,we,Te=null,Ee=null,De=null,Oe=null,ke=null,Ae=oe(),je=new mA({loadEmbedder:e.embedderLoader??(()=>{let t=oe();return Xk({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:L(ZE(n),`embeddings`),enabled:Ae.enabled,providerFingerprint:ce(Ae)}),Me=null,Ne=new Set,Pe=!1,Fe=[],Ie,Le,Re,ze=new Promise((e,t)=>{Le=e,Re=t});function Be(e){Te?.signal(e)}let Ve=null;function He(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,ve.saveToDisk().catch(e=>{I(`backlinks`).warn({err:e},`Failed to persist debounced cache`)}),ye.saveToDisk().catch(e=>{I(`tag-index`).warn({err:e},`Failed to persist debounced tag snapshot`)})},2e3)}let Ue=null,We=!1,Ge=()=>{try{X7(n,Ke.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Ke=new Vhe(void 0,{onEviction:()=>Are(),onSizeChange:e=>jre(e),onMutate:()=>{!We||Ue!==null||(Ue=setTimeout(()=>{Ue=null,Ge()},2e3))}});for(let[e,r]of Whe(n))jx(e)||vG(e)&&([`.md`,`.mdx`].some(n=>{let r=z(t,`${e}${n}`);return AE(r,z(t))&&B(r)})||Ke.restore(e,r));We=!0;let qe=(e,t)=>{jx(e)||Ke.setRenamed(e,t)},Je=e=>{if(!jx(e)){if(Ke.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ke.setDeleted(e)}},Ye=e=>{jx(e)||Ke.delete(e)};try{_e=MM({projectDir:n,contentDir:t,singleDocRelPath:_,onAfterRebuild:()=>{ve.rebuildFromDisk(x()).catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),ye.init().catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),CR(ft).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?I(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):I(`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=>{I(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ve=new kI({projectDir:n,contentDir:t,contentFilter:_e}),ye=new x9({projectDir:n,contentDir:t,contentFilter:_e}),(async()=>{await ye.loadFromDisk()?await ye.reconcileWithDisk():await ye.init()})().catch(e=>{I(`server-factory`).warn({err:e},`[server-factory] tag-index warm boot failed; continuing with empty index`)}),be={current:f},xe=o?Xme({getShadow:()=>be.current??null,getCurrentBranch:()=>pt?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Ql(n)??void 0,isWriterLive:e=>{if(!De&&!we)return I(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(De?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of we?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,Se=U7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:l,shadowRef:be,ephemeral:v,contentRoot:p,backlinkIndex:ve,configHomedirOverride:u,getCurrentBranch:()=>pt?.getLastKnownBranch()??null,resolveEmbed:he,resolveSize:ge,getPrincipal:()=>Me,onAgentCommit:()=>Te?.signal(`session-activity`),onFlushCommit:()=>xe?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Te?.emitDiskAck(e,t),!jx(e)&&Jie(r,n)&&(Oe?.(),Be(`files`))},onConfigRejected:(e,t)=>Te?.emitConfigValidationRejected(e,t),onConfigPersisted:le,isRecentlyRemoved:e=>Ke.has(e),mdManager:e.mdManager,durabilityState:b}),Ce=new ume({quiet:r,debounce:i,maxDebounce:a,extensions:[Se.extension]});let c=Ce;Fe.push(bhe(()=>c.documents.size),xhe(()=>Se.getQueueDepths()),Che(()=>{let e=0;for(let t of c.documents.values())e+=t.directConnectionsCount;return{websocket:c.getConnectionsCount()-e,direct:e}})),The(),v||(ke=zhe({getLoadedDocuments:()=>c.documents,forceStore:(e,t)=>Se.forceStore(e,t),getBase:e=>b.getReconciledBase(e),isBatchActive:()=>b.isBatchInProgress(),peekInFlight:e=>b.peekInFlightFlush(e),readDiskBytes:e=>{let n=jE(e,t),r,i;try{r=ol(n),i=ul(r).size}catch(t){let n=Zo(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new G7(`symlink cycle at content path: ${e}`):t}if(!ME(r,t))throw new G7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new G7(`document exceeds the open byte limit: ${e}`);try{return V(r,`utf-8`)}catch(e){if(Zo(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let m=Ce.shouldUnloadDocument.bind(Ce);Ce.shouldUnloadDocument=e=>{if(Ne.has(e)||Pe&&m(e))return!0;let t=e.name;return jx(t)||S(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:m(e)},Ie=async e=>{Ne.add(e);try{await Ce.unloadDocument(e)}finally{Ne.delete(e)}},Te=new Px(Ce),Ee=new pw(Ce),De=new mw(Ce),we=new qS(Ce);let g=we;Fe.push(whe(()=>({active:g.liveSessionCount,limit:g.sessionLimit})));let y=M5({backlinkIndex:ve,tagIndex:ye,signalChannel:Be});Ce.configuration.extensions.push(y),Ce.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=AG(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==de)throw new kG(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${de}`);let i=n?.expectedBranch,a=x();if(typeof i==`string`&&i.length>0&&i!==a)throw new kG(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(Me&&n.principalId===Me.id?o.principalId=Me.id:Me?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Me.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),Ce.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!Ox(e.documentName)&&!kx(e.documentName))return;let t=e.request,n=t.socket?.remoteAddress;if(n!==void 0&&!zB(n))throw Error(`config-doc admission requires loopback peer (peer=${n}, doc=${e.documentName})`);let r=e.requestHeaders,i=(r&&typeof r.get==`function`?r.get(`host`):null)??t.headers?.host??void 0;if(!BB(i))throw Error(`config-doc admission requires loopback Host header (host=${i??`<absent>`}, doc=${e.documentName})`)}});let C=z(t);function w(e){if(!vG(e))return null;let t=z(C,Ux(e));return AE(t,C)?t:null}Ce.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await Hhe(e.documentName,{recentlyRemovedDocs:Ke,resolveFilePath:w,fileExists:B})}}),Ce.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=AG(e.token);Ome(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ce.documents.get(e)})}}),Ce.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new J8(e.update);if(t.readVarString(),t.readVarUint()===a5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${ue} rejected — server-only channel`)}});let T=bG({hocuspocus:Ce,durabilityState:b,sessionManager:we,contentDir:t,contentFilter:_e,serverInstanceId:de,getFileIndex:()=>ft?ft.getFileIndex():new Map,getAttachmentFolderPath:E,getAllFilesIndex:()=>ft?ft.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ft?.getFileIndexGeneration()??0,mutateFileIndex:e=>ft?.mutateFileIndex(e),getFolderIndex:()=>ft?ft.getFolderIndex():new Map,getAliasMap:()=>ft?ft.getAliasMap():new Map,getFolderAliasIndex:()=>ft?ft.getFolderAliasIndex():new Map,rescanFiles:()=>ft?.rescanFromDisk(),enableTestRoutes:d,shadowRef:be,flushGitCommit:()=>Se.flushPendingGitCommit(),flushContributors:()=>Se.flushContributors(),getCurrentBranch:()=>pt?.getLastKnownBranch()??null,getDiskAckSVs:()=>Te?.getLatestDiskAckSVsAsBase64()??{},contentRoot:p,backlinkIndex:ve,tagIndex:ye,signalChannel:Be,agentFocusBroadcaster:Ee,agentPresenceBroadcaster:De,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>mt,localOpCliArgs:h,projectDir:n,resolveEmbed:he,getPrincipal:()=>Me,acpRegistry:fe,loadAcpCustomAgents:()=>Ou(D,I(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Ie,ready:ze,recentlyRemovedDocs:Ke,serializeDoc:et,evictManagedArtifactLkg:e=>{Se.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:je,getSemanticSimilarityFloor:()=>oe().similarityFloor,getLinterBaseConfig:()=>ae(),getLinkPreviewsEnabled:se,embeddingsSecretsFile:$k(u),ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{Oe=e}});Ce.configuration.extensions.push(T),Ce.configuration.extensions.push(Q7({mdManager:Va,schema:Ba,shadowRef:be,contentRoot:p,getCurrentBranch:()=>pt?.getLastKnownBranch()??null,resolveEmbed:he,resolveSize:ge})),Ce.configuration.extensions.push(Tge()),Ce.configuration.extensions.push(Dme({getSyncEngine:()=>mt,projectDir:n,contentDir:t}))}catch(e){for(let e of Fe.splice(0))e();throw ke?.dispose(),ke=null,zo(D),e}let Xe=null,Ze=new Map,Qe=[];function $e(e,t){let n=z(e,`rescue`),r=z(n,Ux(t));return AE(r,n)?r:null}function et(e){let t=Ce.documents.get(e);return t?NL(t):null}let tt=(e,t)=>AL(b,Ce,e,t,he,ge);function nt(e){if(!$x(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let it=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Ce.documents){if(jx(n))continue;let r=Ce.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{FI(r,i,he,n)},PI)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},at=null,ot=e=>{e&&(at===null&&(at=new Set,setImmediate(()=>{let e=at;if(at=null,e)try{for(let t of e)it(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),at.add(e))};function st(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 LL(e)}}async function ct(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ve.updateDocumentFromMarkdown(e.docName,e.content),He(),ye.updateDocumentFromMarkdown(e.docName,e.content),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Ye(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=Ce.documents.get(t);if(!r){ve.updateDocumentFromMarkdown(t,n),He(),ye.updateDocumentFromMarkdown(t,n),Be(`backlinks`),Be(`graph`),Be(`tags`);return}let i=S(t)??``,a=et(t)??i,o=zI({docName:t,base:i,ours:a,theirs:n}),s=WL(i).slice(0,6),c=WL(a).slice(0,6),l=WL(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:nt(r),ve.updateDocumentFromMarkdown(t,n),He(),ye.updateDocumentFromMarkdown(t,n),Be(`backlinks`),Be(`graph`),Be(`tags`);break;case`clean`:try{tt(t,o.newContent),C(t,o.newContent),cx(),nt(r),ve.updateDocumentFromMarkdown(t,n),He(),ye.updateDocumentFromMarkdown(t,n),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),C(t,n),nt(r)}break;case`merged`:try{tt(t,o.newContent),C(t,n),cx(),nt(r),ve.updateDocumentFromMarkdown(t,n),He(),ye.updateDocumentFromMarkdown(t,n),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),C(t,n),nt(r)}break;case`conflicts`:try{tt(t,o.newContent),C(t,o.newContent),cx(),lx(),ve.updateDocumentFromMarkdown(t,n),He(),ye.updateDocumentFromMarkdown(t,n),Be(`backlinks`),Be(`graph`),Be(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),C(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{lx();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Ce.documents.get(t);if(!n){ve.deleteDocument(t),He(),ye.deleteDocument(t),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Je(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=S(t)??``,i=et(t)??``,a=i!==r;if(a&&be.current){let e=be.current,n=pt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{vL(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{dx(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),w(t),ve.deleteDocument(t),He(),ye.deleteDocument(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Ce.closeConnections(t),await Ie(n),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),Je(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=Ce.documents.get(t);if(w(t),C(n,r),ve.renameDocument(t,n,r),He(),ye.renameDocument(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`),qe(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=Ce.documents.get(t);if(!n)return;let r=et(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):C(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:me.add(e.relativePath),Be(`files`),ot(Ic(e.relativePath));break;case`asset-delete`:me.remove(e.relativePath),Be(`files`),ot(Ic(e.relativePath));break;case`folder-create`:case`folder-delete`:Be(`files`);break;case`file-create`:case`file-update`:case`file-delete`:Be(`files`);break;default:LL(e)}}catch(t){let n=st(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let lt=[];async function ut(e){if(ne()){lt.push(e);return}await ct(e)}async function dt(){let e=lt.splice(0,lt.length);for(let t of e)await ct(t)}let ft=null,pt=null,mt=null,ht=null;async function gt(e){if(Ce.documents.size===0)return;let t=!1,n=new Promise(e=>{Ce.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Ce.documents.keys());Ce.closeConnections(),Ce.flushPendingStores();for(let e of Ce.documents.values())e.getConnectionsCount()===0&&Ce.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(Ce.documents.keys()),i=[],o=[];if(be.current){for(let e of n)if(!jx(e))try{let t=et(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=$e(be.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:be.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}$c(Rc(n),{recursive:!0}),fl(n,t,`utf-8`),dx(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function _t(){return ht||(ht=(async()=>{let e=Date.now(),t=[];Pe=!0;for(let e of Fe.splice(0))e();try{await ke?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}ke=null;try{Yo(D)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Ve!==null&&(clearTimeout(Ve),Ve=null),ye.close(),Ue!==null&&(clearTimeout(Ue),Ue=null),We)try{X7(n,Ke.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([ze.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=Ce.documents.size;xe?.destroy();try{try{try{pt&&=(await pt.unsubscribe(),null),ft&&=(await ft.unsubscribe(),null);for(let{docName:e,cleanup:t}of Qe)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Qe.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Te?.destroy(),De?.destroy(),Xe&&=(await Xe.disconnect(),null);for(let[e,t]of Ze)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ze.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await we.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Zre()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await gt(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await Se.flushPendingGitCommit(),await Se.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)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{mt&&=(await mt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(be.current){try{let e=(await Ao({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&fl(z(be.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{$I(be.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{zo(D,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await vo()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),ht)}let vt=[];async function bt(){try{Me=await K7(n),y.info({principalId:Me.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!be.current)try{be.current=await QI(n),y.info({gitDir:be.current.gitDir},`[server] history repo initialized at ${be.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),vt.push(`shadow-repo`)}if(be.current){let e=null;try{e=MV(be.current.gitDir),tH(be.current.gitDir,e),LV(be.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([nH(be.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await xe?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(be.current)try{await YI(be.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{be.current=await QI(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),be.current=void 0,vt.includes(`shadow-repo`)||vt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(be.current)try{let e=z(be.current.gitDir,`last-known-head`),t=null;try{t=V(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Ao({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Ao({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await mL(be.current,p??``,t,r,e),ux()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{fl(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=vV(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),vt.push(`managed-rename-recovery`)}try{let e=Boe(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),vt.push(`upload-tempfile-sweep`)}try{Xe=await Ce.openDirectConnection(ue),Te?.emitServerInfo(de,x())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),vt.push(`cc1-push`)}let r=v?[]:ie;for(let e of r)try{let t=await Ce.openDirectConnection(e);Ze.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),vt.push(`config-doc:${e}`)}let i=new Map([[rt,qa(`project`,n)],[gr,qa(`project-local`,n)],[c,qa(`user`,n,u)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await gme(t,t=>{let n=Ce.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=D5(n??null,e,t,Se.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),le(e)});Qe.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),vt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=YB(e,Se.managedArtifactCtx);if(!n)return;let r=QB(Ce.documents.get(n)??null,n,t,Se.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),yt(n)&&ve.ingestGlobalSkillBundles(GB(Se.managedArtifactCtx),x()).then(()=>{Be(`backlinks`),Be(`graph`)}).catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=GB(Se.managedArtifactCtx),n=await W5(t,e);Qe.push({docName:`__skill-files__`,cleanup:n}),y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),vt.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of qD(n).templates)t.add(e.source_folder)}catch(e){y.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 W5(r,e,Qme);Qe.push({docName:`__template-files__`,cleanup:i}),y.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),vt.push(`managed-artifact-watcher:templates`)}}try{let e=z(t,`.okignore`),r=z(n,`.gitignore`),i=null;try{let e=Pc(`git`,[`rev-parse`,`--git-common-dir`],hA({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=L(z(n,e.stdout.trim()),`info`,`exclude`);B(Rc(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await _me(a,(t,r)=>{(async()=>{if(t===e)try{let e=D5(Ce.documents.get(`__config__/okignore`)??null,T,r,Se.configPersistenceCtx);o.info({docName:T,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 _e.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`),Te?.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`),Te?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:R(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Qe.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),vt.push(`ignore-files-watcher`)}let a=j5(n).branch??`main`;ee(a),ve.switchBranch(a);let o=performance.now();try{await Ya(`ok.boot.indexes`,void 0,async()=>{let e=x();try{if(await ve.loadFromDisk(e)){let t=await ve.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&y.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)jx(e)||Ke.peek(e)?.kind!==`renamed`&&(Ke.setDeleted(e),n++);n>0&&y.info({count:n},`[removal-guard] tombstoned docs deleted while the server was down`)}else await ve.rebuildFromDisk(e);try{await ve.ingestGlobalSkillBundles(GB(Se.managedArtifactCtx),e)}catch(t){y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}ve.saveToDisk().catch(t=>{I(`backlinks`).warn({branch:e,err:t},`Failed to persist startup cache for ${e}`)})}catch(t){y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let n=performance.now();ft=await Ya(`ok.boot.seed-walk`,void 0,async()=>SR(t,ut,_e)),NI(`seedWalkMs`,Math.round(performance.now()-n));{let e=z(t),n=0;for(let[t]of Ke.entries()){if(!vG(t))continue;let r=z(e,`${t}${Hx(t)}`);AE(r,e)&&B(r)&&(Ke.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{let e=await ye.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&y.info(e,`[tag-index] startup reconcile: offline changes applied`),ye.saveToDisk().catch(e=>{I(`tag-index`).warn({err:e},`Failed to persist startup tag snapshot`)})}catch(e){y.error({err:e},`[tag-index] startup reconcile failed; tag index updates incrementally via watcher events`),vt.push(`tag-index`)}let r=0;try{_===void 0?await CG({contentDir:t,contentFilter:_e,basenameIndex:me,onSkip:(e,t,n)=>{r++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):SG({contentDir:t,basenameIndex:me,onSkip:(e,t,n)=>{r++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),r>0&&(y.warn({count:r},`[basename-index] startup seed completed with ${r} skipped entries — embeds under inaccessible subtrees will not resolve`),vt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),vt.push(`basename-index`)}})}catch(e){y.error({err:e},`[server] disk bridge watcher failed to start`),vt.push(`file-watcher`)}finally{NI(`indexesMs`,Math.round(performance.now()-o)),ft&&Zoe(`fileCount`,ft.getFileIndex().size)}try{pt=await Nme(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),Gne(),Ce.flushPendingStores(),await Se.flushPendingGitCommit(),te(!0),be.current){let e=x(),t=j5(n).branch??e,r=[];for(let[e,t]of Ce.documents){if(jx(e))continue;let n=null;if(t.transact(()=>{n=et(e)},kge),n===null)continue;let i=S(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await wL(be.current,e,fL.id,r,t);n&&(Jne(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=lt.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(te(!1),await dt(),e.headMoved&&e.newHead){let r=jge(n,z(t),e.oldHead,e.newHead);if(r.size>0){ck(r.keys());for(let[e,t]of r)sk(e,Iee(t.email),t.name,t.email,pu(e));await Se.flushContributors()}}if(await Se.flushDeferredStores(`within-branch`),mt!==null)try{await mt.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{qne(),lt.splice(0,lt.length),ee(i),Ve!==null&&(clearTimeout(Ve),Ve=null),ve.switchBranch(i),_e.rebuildDirCount();try{let e=0;me.clear(),await CG({contentDir:t,contentFilter:_e,basenameIndex:me,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),vt.includes(`basename-index-partial`)||vt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of Ce.documents)if(!jx(e))try{let r=jE(e,t);if(!B(r)){let t=S(e)??``,r=et(e)??``;if(r!==t&&be.current){let t=be.current;queueMicrotask(()=>{vL(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{dx(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=V(r,`utf-8`);tt(e,a),C(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:Ce.documents.size},`[branch-switch] loaded branch ${i} (${Ce.documents.size} docs)`);try{if(await ve.loadFromDisk(i)){let e=await ve.reconcileWithDisk(i);(e.added>0||e.updated>0||e.deleted>0)&&y.info(e,`[backlinks] branch-switch reconcile for ${i}`)}else await ve.rebuildFromDisk(i);try{await ve.ingestGlobalSkillBundles(GB(Se.managedArtifactCtx),i)}catch(e){y.warn({err:e,branch:i},`[backlinks] branch-switch global skill bundle ingest failed`)}ve.saveToDisk(i).catch(e=>{I(`backlinks`).warn({branch:i,err:e},`Failed to persist branch cache for ${i}`)})}catch(e){y.error({err:e,branch:i},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}try{let e=await ye.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&y.info(e,`[tag-index] branch-switch reconcile for ${i}`)}catch(e){y.warn({err:e,branch:i},`[tag-index] branch-switch reconcile failed; falling back to full rebuild`),await ye.init()}if(ye.saveToDisk().catch(e=>{I(`tag-index`).warn({branch:i,err:e},`Failed to persist tag snapshot after branch switch`)}),be.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Ce.documents)if(!jx(t))try{let n=await EL(be.current,i,fL.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=S(t);if(!r)continue;let a=zI({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:tt(t,a.newContent),C(t,a.newContent),e++;break;case`conflicts`:tt(t,a.newContent),C(t,a.newContent),lx(),e++;{let e=Ce.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&be.current)try{let t=YI(be.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await WI(be.current).withMutator(async()=>{for(let e of n.split(`
3262
- `))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}te(!1),await Se.flushDeferredStores(`discard-stale`),Te?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&be.current&&r>0){let t=p??`.`;try{let n=await mL(be.current,t,e.oldHead,e.newHead,i);ux(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),vt.push(`head-watcher`)}function s(e){for(let r of e)try{let e=kE(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Lx(e),a=Ce.documents.get(i);if(!a)continue;let o=et(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):C(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}let l=Age(h);try{mt=new Cge({projectDir:n,contentDir:t,contentFilter:_e,contentRoot:p,syncEnabled:re(),credentialArgs:l,cc1Broadcaster:Te,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||Se.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:s,onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await oo({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ga(t.error),configPath:qa(`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 mt.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),mt=null}Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`);let d=MI();d!==void 0&&NI(`readyMs`,d)}return bt().then(Le,Re),{hocuspocus:Ce,durabilityState:b,sessionManager:we,cc1Broadcaster:Te,agentFocusBroadcaster:Ee,agentPresenceBroadcaster:De,maintenanceCoordinator:xe,contentFilter:_e,basenameIndex:me,serverInstanceId:de,destroy:_t,ready:ze,degraded:vt,lockDir:D,get syncEngine(){return mt},resolveEmbed:he,acpRegistry:fe,acpPermissions:pe}}function T9(e){return e/1048576}function Mge(){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;Ja(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function Nge(){if(E9)return;let e=bo().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}=Mge();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 Pge(){if(!D9){let e=bo().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=bee({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=bo().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=ZE(e);M9=new Do({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Fi(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,I(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){Fi(null),await M9?.drain(),M9=null,N9=!1}Ra();const Fge=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],Ige=[`cache`,`tmp`];function Lge(e){let t=z(e,ya);if(!(()=>{if(!B(t))return!0;try{return il(t).length===0}catch{return!0}})())return[];let n=[];for(let t of Fge)B(z(e,t))&&n.push(t);for(let t of Ige){let r=z(e,t);try{B(r)&&ul(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function Rge(e){let t=Zl(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 zge(e){Xoe();let t=e.projectDir??e.contentDir,n=qG({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}`)}Co.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}yo({localSink:n?.telemetry}),F9(t),Nge(),Pge();let{kind:r,gitdir:i}=Rge(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=lo(i));let o=zG(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ya(`ok.boot`,{attributes:a},async()=>Bge(e)),l=()=>{if(s)try{let e=Ia.extract(za.active(),{traceparent:s});return za.with(e,c)}catch(e){I(`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 Bge(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??I(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=e.lockKind??a??`interactive`,{createServer:s}=await import(`node:http`),{markServerLockDraining:c,releaseServerLock:l,updateServerLockPort:u}=await import(`./server-lock-CmiibuTm.mjs`),d=!1;if(!t&&e.autoInitFn)try{d=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let f=e.projectDir??e.contentDir,p=z(f,`.ok`);if(!B(z(p,`config.yml`)))throw new _8(B(p)?`config`:`okdir`,f);let m=z(p,`.gitignore`);B(m)||I(`boot`).warn({path:m},"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 h=e.gitPreflight??fF;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof lF||e instanceof uF){let t=e instanceof uF?e.detected:``,n=e instanceof uF?`too_old`:`not_available`;CB(e),i.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 vo(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let g=Lge(p);g.length>0&&I(`boot`).warn({files:g},`Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ya}/.`);let _=w9({contentDir:e.contentDir,projectDir:e.projectDir,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,onAgentWrite:e.onAgentWrite,lockKind:o,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:v,destroy:y,ready:b,degraded:x,lockDir:S,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:T,maintenanceCoordinator:ee}=_,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ne=e.port??0,E=e.ephemeral?void 0:d8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${te}:${ne}`,log:i}),re=s();re.headersTimeout=3e4,re.requestTimeout=6e4;let ie=e.serveContentAssets===!1?void 0:YE({contentFilter:_.contentFilter,contentSirv:Ro(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Ji,assetExtensions:Vi,blocklistExtensions:Zi}),ae=!1;if(e.reactShellDistDir)try{XF(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ae=!0}catch(e){if(e instanceof YF)i.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:S},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await y().catch(()=>{}),l(S),e}let oe=e.reactShellDistDir?Ro(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,se=e.ephemeral?null:new uw({contentDir:e.contentDir,localDir:S,registry:_.acpRegistry,permissions:_.acpPermissions,sessionManager:C,agentPresenceBroadcaster:T,resolveEmbed:_.resolveEmbed,isExcludedPath:e=>_.contentFilter.isExcluded(e),isIgnoredPath:e=>_.contentFilter.isPathIgnored(e),getLoadedDocText:e=>v.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${te}:${ne}`,getMcpStdioCommand:()=>lw(e.localOpCliArgs,ne),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:i});se!==null&&await se.init();let ce=p8({httpServer:re,hocuspocus:v,mcpHttpHandler:E,log:i,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:T,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ie,reactShellMiddleware:oe,ephemeral:e.ephemeral,acpThreadManager:se}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;r!==null&&(ue=BG({httpServer:re,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await R9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);re.once(`error`,r),re.listen(e.port,e.host,()=>{re.removeListener(`error`,r),t()})})}catch(e){if(ae)try{$F(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),l(S),e}let de=MI();de!==void 0&&NI(`httpListenMs`,de);let D=re.address(),fe=typeof D==`object`&&D?D.port:e.port??0;if(ne=fe,u(S,fe),ae&&ZF(S,fe),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let pe=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(pe)return;pe=!0;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{c(S),ae&&Ioe(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(se!==null&&await t(`acpThreads.destroy`,()=>se.destroy()),await t(`mount.shutdown`,()=>ce.shutdown()),E!==void 0&&await t(`mcpHttpHandler.close`,()=>E.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{re.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{re.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),ae&&await t(`releaseUiLock`,async()=>$F(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>vo()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Co.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await GF({projectDir:f,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&i.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){i.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:re,destroy:le,lockDir:S,contentDir:e.contentDir,port:fe,ready:b,degraded:x,didAutoInit:d,serverInstance:_,acpThreadManager:se}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new NG(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=null;try{let e=Ql(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!B(t)){i.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:a.length}));return}let r=Mo({baseDir:n,timeout:{block:5e3}});o=new Set(await wP(r,[`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(o!==null){let e=0;for(let t of a)o.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?.has(e.file)),a.length===0)return}for(let e of a){let n=Lx(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 Vge=ca;function Hge(e={}){let t=e.home??hl(),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(Eo(),1);const B9=L(hl(),`.ok`,`logs`),Uge=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function Wge(){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 Gge(e){$c(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function Kge(e){try{if(ul(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{sl(n,r)}catch{}}try{dl(`${e}.3`)}catch{}}function qge(e){try{let t=Date.now(),n=10080*60*1e3,r=il(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ul(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{dl(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{dl(L(e,t.name)),a-=t.size}catch{}}}catch{}}function Jge(e){Gge(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);Kge(n),(e._setTimeout??setTimeout)(()=>qge(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:Wge(),name:e.name,redact:{paths:Uge,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 Yge(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 Xge(e){return L(B9,`${e}.${V9()}.log`)}function Zge(){return B9}function Qge(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=Rc(t);if(r===t)return null;t=r,n+=1}return null}const H9=Hl(Mc),U9=I(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function $ge(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],hA({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function e_e(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!ul(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=fF()}catch(e){throw e instanceof lF||e instanceof uF?(CB(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof uF?`too_old`:`not_available`,detectedVersion:e instanceof uF?e.detected:``},e instanceof uF?`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 $ge(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],hA({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=I(`project-skill-git`),K9=/^[0-9a-f]{40}$/,t_e=Tn.map(e=>e.replace(/\/$/,``));async function n_e(e){let t=Ql(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(o_e(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=No(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await jo(async()=>{let t=await r_e(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await i_e(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=No(e,{gitIndexFile:L(vl(),`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 a_e(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await VR(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Fo(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 \`${Ti}\` 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 t_e){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function r_e(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 i_e(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function a_e(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function o_e(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 s_e(e,t){let n;try{n=jc(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=Rc(n),r=0;r<32;r+=1){let n=L(t,`package.json`);if(B(n))try{let t=JSON.parse(await Cl(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=Rc(t);if(r===t)return;t=r}}const c_e=[{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 c_e)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 l_e(e){if(!Fx(e))throw new $9(e);let t;try{t=ol(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ul(t).isFile())throw new Q9(e);let n=Rc(t),r=TR(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Lx(R(u_e(e),t).split(Uc).join(`/`)),canonicalFilePath:t}}let i=Ic(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Lx(i)}}function u_e(e){return z(e,Wa({absPath:qa(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function d_e(e){let t=el(z(vl(),`ok-ephemeral-`)),n=z(t,`.ok`);return $c(n,{recursive:!0}),fl(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),fl(z(n,`.gitignore`),`local/
3262
+ `))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}te(!1),await Se.flushDeferredStores(`discard-stale`),Te?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&be.current&&r>0){let t=p??`.`;try{let n=await mL(be.current,t,e.oldHead,e.newHead,i);ux(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),vt.push(`head-watcher`)}function s(e){for(let r of e)try{let e=kE(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Lx(e),a=Ce.documents.get(i);if(!a)continue;let o=et(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):C(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}let l=Age(h);try{mt=new Cge({projectDir:n,contentDir:t,contentFilter:_e,contentRoot:p,syncEnabled:re(),credentialArgs:l,cc1Broadcaster:Te,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||Se.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:s,onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await oo({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ga(t.error),configPath:qa(`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 mt.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),mt=null}Be(`files`),Be(`backlinks`),Be(`graph`),Be(`tags`);let d=MI();d!==void 0&&NI(`readyMs`,d)}return bt().then(Le,Re),{hocuspocus:Ce,durabilityState:b,sessionManager:we,cc1Broadcaster:Te,agentFocusBroadcaster:Ee,agentPresenceBroadcaster:De,maintenanceCoordinator:xe,contentFilter:_e,basenameIndex:me,serverInstanceId:de,destroy:_t,ready:ze,degraded:vt,lockDir:D,get syncEngine(){return mt},resolveEmbed:he,acpRegistry:fe,acpPermissions:pe}}function T9(e){return e/1048576}function Mge(){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;Ja(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function Nge(){if(E9)return;let e=bo().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}=Mge();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 Pge(){if(!D9){let e=bo().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=bee({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=bo().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=ZE(e);M9=new Do({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Fi(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,I(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){Fi(null),await M9?.drain(),M9=null,N9=!1}Ra();const Fge=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],Ige=[`cache`,`tmp`];function Lge(e){let t=z(e,ya);if(!(()=>{if(!B(t))return!0;try{return il(t).length===0}catch{return!0}})())return[];let n=[];for(let t of Fge)B(z(e,t))&&n.push(t);for(let t of Ige){let r=z(e,t);try{B(r)&&ul(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function Rge(e){let t=Zl(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 zge(e){Xoe();let t=e.projectDir??e.contentDir,n=qG({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}`)}Co.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}yo({localSink:n?.telemetry}),F9(t),Nge(),Pge();let{kind:r,gitdir:i}=Rge(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=lo(i));let o=zG(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ya(`ok.boot`,{attributes:a},async()=>Bge(e)),l=()=>{if(s)try{let e=Ia.extract(za.active(),{traceparent:s});return za.with(e,c)}catch(e){I(`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 Bge(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??I(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=e.lockKind??a??`interactive`,{createServer:s}=await import(`node:http`),{markServerLockDraining:c,releaseServerLock:l,updateServerLockPort:u}=await import(`./server-lock-BwO1WEYX.mjs`),d=!1;if(!t&&e.autoInitFn)try{d=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let f=e.projectDir??e.contentDir,p=z(f,`.ok`);if(!B(z(p,`config.yml`)))throw new _8(B(p)?`config`:`okdir`,f);let m=z(p,`.gitignore`);B(m)||I(`boot`).warn({path:m},"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 h=e.gitPreflight??fF;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof lF||e instanceof uF){let t=e instanceof uF?e.detected:``,n=e instanceof uF?`too_old`:`not_available`;CB(e),i.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 vo(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let g=Lge(p);g.length>0&&I(`boot`).warn({files:g},`Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ya}/.`);let _=w9({contentDir:e.contentDir,projectDir:e.projectDir,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,onAgentWrite:e.onAgentWrite,lockKind:o,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:v,destroy:y,ready:b,degraded:x,lockDir:S,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:T,maintenanceCoordinator:ee}=_,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ne=e.port??0,E=e.ephemeral?void 0:d8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${te}:${ne}`,log:i}),re=s();re.headersTimeout=3e4,re.requestTimeout=6e4;let ie=e.serveContentAssets===!1?void 0:YE({contentFilter:_.contentFilter,contentSirv:Ro(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Ji,assetExtensions:Vi,blocklistExtensions:Zi}),ae=!1;if(e.reactShellDistDir)try{XF(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ae=!0}catch(e){if(e instanceof YF)i.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:S},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await y().catch(()=>{}),l(S),e}let oe=e.reactShellDistDir?Ro(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,se=e.ephemeral?null:new uw({contentDir:e.contentDir,localDir:S,registry:_.acpRegistry,permissions:_.acpPermissions,sessionManager:C,agentPresenceBroadcaster:T,resolveEmbed:_.resolveEmbed,isExcludedPath:e=>_.contentFilter.isExcluded(e),isIgnoredPath:e=>_.contentFilter.isPathIgnored(e),getLoadedDocText:e=>v.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${te}:${ne}`,getMcpStdioCommand:()=>lw(e.localOpCliArgs,ne),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:i});se!==null&&await se.init();let ce=p8({httpServer:re,hocuspocus:v,mcpHttpHandler:E,log:i,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:T,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ie,reactShellMiddleware:oe,ephemeral:e.ephemeral,acpThreadManager:se}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;r!==null&&(ue=BG({httpServer:re,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await R9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);re.once(`error`,r),re.listen(e.port,e.host,()=>{re.removeListener(`error`,r),t()})})}catch(e){if(ae)try{$F(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),l(S),e}let de=MI();de!==void 0&&NI(`httpListenMs`,de);let D=re.address(),fe=typeof D==`object`&&D?D.port:e.port??0;if(ne=fe,u(S,fe),ae&&ZF(S,fe),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let pe=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(pe)return;pe=!0;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{c(S),ae&&Ioe(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(se!==null&&await t(`acpThreads.destroy`,()=>se.destroy()),await t(`mount.shutdown`,()=>ce.shutdown()),E!==void 0&&await t(`mcpHttpHandler.close`,()=>E.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{re.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{re.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),ae&&await t(`releaseUiLock`,async()=>$F(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>vo()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Co.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await GF({projectDir:f,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&i.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){i.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:re,destroy:le,lockDir:S,contentDir:e.contentDir,port:fe,ready:b,degraded:x,didAutoInit:d,serverInstance:_,acpThreadManager:se}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new NG(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=null;try{let e=Ql(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!B(t)){i.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:a.length}));return}let r=Mo({baseDir:n,timeout:{block:5e3}});o=new Set(await wP(r,[`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(o!==null){let e=0;for(let t of a)o.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?.has(e.file)),a.length===0)return}for(let e of a){let n=Lx(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 Vge=ca;function Hge(e={}){let t=e.home??hl(),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(Eo(),1);const B9=L(hl(),`.ok`,`logs`),Uge=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function Wge(){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 Gge(e){$c(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function Kge(e){try{if(ul(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{sl(n,r)}catch{}}try{dl(`${e}.3`)}catch{}}function qge(e){try{let t=Date.now(),n=10080*60*1e3,r=il(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ul(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{dl(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{dl(L(e,t.name)),a-=t.size}catch{}}}catch{}}function Jge(e){Gge(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);Kge(n),(e._setTimeout??setTimeout)(()=>qge(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:Wge(),name:e.name,redact:{paths:Uge,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 Yge(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 Xge(e){return L(B9,`${e}.${V9()}.log`)}function Zge(){return B9}function Qge(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=Rc(t);if(r===t)return null;t=r,n+=1}return null}const H9=Hl(Mc),U9=I(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function $ge(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],hA({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function e_e(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!ul(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=fF()}catch(e){throw e instanceof lF||e instanceof uF?(CB(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof uF?`too_old`:`not_available`,detectedVersion:e instanceof uF?e.detected:``},e instanceof uF?`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 $ge(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],hA({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=I(`project-skill-git`),K9=/^[0-9a-f]{40}$/,t_e=Tn.map(e=>e.replace(/\/$/,``));async function n_e(e){let t=Ql(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(o_e(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=No(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await jo(async()=>{let t=await r_e(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await i_e(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=No(e,{gitIndexFile:L(vl(),`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 a_e(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await VR(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Fo(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 \`${Ti}\` 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 t_e){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function r_e(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 i_e(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function a_e(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function o_e(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 s_e(e,t){let n;try{n=jc(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=Rc(n),r=0;r<32;r+=1){let n=L(t,`package.json`);if(B(n))try{let t=JSON.parse(await Cl(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=Rc(t);if(r===t)return;t=r}}const c_e=[{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 c_e)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 l_e(e){if(!Fx(e))throw new $9(e);let t;try{t=ol(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ul(t).isFile())throw new Q9(e);let n=Rc(t),r=TR(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Lx(R(u_e(e),t).split(Uc).join(`/`)),canonicalFilePath:t}}let i=Ic(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Lx(i)}}function u_e(e){return z(e,Wa({absPath:qa(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function d_e(e){let t=el(z(vl(),`ok-ephemeral-`)),n=z(t,`.ok`);return $c(n,{recursive:!0}),fl(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),fl(z(n,`.gitignore`),`local/
3263
3263
  `,`utf-8`),t}export{E0 as $,Sx as $i,YF as $n,Bj as $r,zB as $t,r9 as A,mw as Ai,jL as An,FP as Ar,dW as At,B5 as B,WS as Bi,QI as Bn,ON as Br,OH as Bt,w9 as C,lk as Ci,tR as Cn,GP as Cr,wG as Ct,n9 as D,YE as Di,sR as Dn,RP as Dr,AG as Dt,$7 as E,QE as Ei,SR as En,LP as Er,OG as Et,O7 as F,lw as Fi,aL as Fn,Hae as Fr,UH as Ft,O5 as G,Px as Gi,YI as Gn,vN as Gr,MH as Gt,Pme as H,Qx as Hi,_L as Hn,bN as Hr,bH as Ht,k7 as I,$re as Ii,mL as In,fP as Ir,BH as It,p8 as J,kx as Ji,zI as Jn,dN as Jr,EH as Jt,g8 as K,Ox as Ki,II as Kn,pN as Kr,wH as Kt,R7 as L,GS as Li,tL as Ln,WN as Lr,FH as Lt,Q7 as M,fw as Mi,uL as Mn,AP as Mr,PW as Mt,K7 as N,uw as Ni,dL as Nn,EP as Nr,bG as Nt,a9 as O,jE as Oi,BL as On,IP as Or,CG as Ot,U7 as P,uie as Pi,fL as Pn,Vae as Pr,TW as Pt,X6 as Q,wx as Qi,TI as Qn,Vj as Qr,BB as Qt,R5 as R,qS as Ri,cL as Rn,kN as Rr,gH as Rt,I9 as S,uk as Si,oR as Sn,KP as Sr,kG as St,x9 as T,XE as Ti,cR as Tn,qP as Tr,EG as Tt,M5 as U,G as Ui,vL as Un,CN as Ur,xH as Ut,z5 as V,IS as Vi,bL as Vn,xN as Vr,jH as Vt,j5 as W,Zx as Wi,DL as Wn,SN as Wr,kH as Wt,d8 as X,Dx as Xi,PI as Xn,MM as Xr,fH as Xt,m8 as Y,jx as Yi,RI as Yn,fN as Yr,SH as Yt,c8 as Z,Ex as Zi,kI as Zn,RM as Zr,pH as Zt,Vge as _,mk as _i,LL as _n,noe as _r,aJ as _t,l_e as a,Gm as aa,IA as ai,vB as an,uF as ar,J1 as at,F9 as b,dk as bi,UL as bn,JP as br,jG as bt,n_e as c,Ou as ca,hA as ci,$R as cn,bF as cr,O1 as ct,Qge as d,tu as da,iA as di,iz as dn,mF as dr,m1 as dt,hx as ea,BA as ei,DB as en,XF as er,D0 as et,Jge as f,au as fa,tA as fi,tz as fn,oF as fr,h1 as ft,Hge as g,Bk as gi,wR as gn,tF as gr,AJ as gt,Zge as h,Gl as ha,zk as hi,TR as hn,aF as hr,Vq as ht,d_e as i,Km as ia,HA as ii,yB as in,lF as ir,Y1 as it,i9 as j,pw as ji,xL as jn,kP as jr,NW as jt,e9 as k,OE as ki,AL as kn,NP as kr,fW as kt,W9 as l,bu as la,aA as li,ez as ln,dF as lr,k1 as lt,Xge as m,Kl as ma,nA as mi,nz as mn,rF as mr,pJ as mt,Z9 as n,Wm as na,UA as ni,SB as nn,$F as nr,N0 as nt,X9 as o,Du as oa,_A as oi,hB as on,sF as or,F1 as ot,Yge as p,$l as pa,rA as pi,qR as pn,iF as pr,v$ as pt,_8 as q,Mx as qi,LI as qn,_N as qr,CH as qt,$9 as r,Um as ra,VA as ri,CB as rn,ZF as rr,q1 as rt,s_e as s,xu as sa,wA as si,GR as sn,fF as sr,D1 as st,Q9 as t,Rre as ta,zA as ti,TB as tn,QF as tr,O0 as tt,e_e as u,nu as ua,eA as ui,YR as un,_F as ur,g1 as ut,zge as v,hk as vi,lR as vn,XP as vr,lJ as vt,C9 as w,ZE as wi,HL as wn,Xae as wr,DG as wt,P9 as x,sk as xi,uR as xn,YP as xr,TG as xt,R9 as y,fk as yi,WL as yn,Yae as yr,BG as yt,Kme as z,US as zi,SL as zn,AN as zr,AH as zt};
3264
- //# sourceMappingURL=src-DO_fYaAw.mjs.map
3264
+ //# sourceMappingURL=src-YSGKFci8.mjs.map