@inkeep/open-knowledge 0.42.0-beta.2 → 0.42.0-beta.4
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.
- package/dist/{acp-harness-probe-Du_PVB_P.mjs → acp-harness-probe-ChUiXq4Y.mjs} +2 -2
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +2 -2
- package/dist/assets/skills/project/references/components-and-visuals.md +4 -0
- package/dist/assets/skills/write-skill/SKILL.md +1 -1
- package/dist/assets/skills/write-skill/references/pressure-testing.md +1 -1
- package/dist/cli.mjs +7 -7
- package/dist/constants-Do1hpvs-.mjs +2 -0
- package/dist/{git-handle-JgY8Ytwb.mjs → git-handle-BFhoHYr0.mjs} +2 -2
- package/dist/git-handle-CRnnMEIm.mjs +1 -0
- package/dist/index.mjs +1 -1
- package/dist/init-BC0lVj9G.mjs +1 -0
- package/dist/{init-DEzyD1YK.mjs → init-o3oVQbkm.mjs} +3 -3
- package/dist/{launch-json-removal-CbMg4I0R.mjs → launch-json-removal-5A8Lrjdh.mjs} +2 -2
- package/dist/{loader-DO9rcR2q.mjs → loader-b0Jnp3-m.mjs} +2 -2
- package/dist/loader-xZjZfXpn.mjs +1 -0
- package/dist/md-manager-CAqfesEA.mjs +2 -0
- package/dist/{open-browser-BqBGMi_2.mjs → open-browser-Be1y1t9d.mjs} +2 -2
- package/dist/parse-worker.mjs +1 -1
- package/dist/preview-Bi-j3iwm.mjs +1 -0
- package/dist/{preview-7FhIhdGC.mjs → preview-Zqg7QABJ.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-5kzpB8WF.js → ActivityModeContent-CnhDNi-c.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CH_Uedi-.js → AgentDiffPane-BKvov9S5.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-D_oI6JYB.js → AgentThreadClientBinder-MaSL3zla.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-C5y2rXYX.js → CodeMirrorPropInput-ZGACWLSy.js} +1 -1
- package/dist/public/assets/{DocumentContext-fuUQIepk.js → DocumentContext-DDkluS7D.js} +4 -4
- package/dist/public/assets/{EditorModeToggle-v_8_QyqL.js → EditorModeToggle-D0Db8Ydu.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-DGzRLORN.js → EnableSyncConfirmDialog-B2sHRtLY.js} +1 -1
- package/dist/public/assets/FeedbackForm-DuEQbMOb.js +1 -0
- package/dist/public/assets/{GraphPanel-Bp-rgKAp.js → GraphPanel-1CKwHElx.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-P94jXYrX.js → LintConfigEditor-DKgxJcvl.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-fjWoKeUA.js → ManagedArtifactProperties-9e_jj3hZ.js} +1 -1
- package/dist/public/assets/{McpConsentDialogBody-DQKGlIrW.js → McpConsentDialogBody-CYOKF_sf.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-LMmhg9P3.js → MermaidDocEditor-BNURUYJE.js} +1 -1
- package/dist/public/assets/{PropertyPanel-DP1c3fMs.js → PropertyPanel-BMIcO_AS.js} +1 -1
- package/dist/public/assets/{ReportBugDialogBody-CN9m_7Kk.js → ReportBugDialogBody-ByMe7BRT.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-DgQ8bbvw.js → SchemaConfigEditor-D7xbhgl6.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-tm_Zr9wy.js → SettingsDialogBody-Bkz3Bpgp.js} +1 -1
- package/dist/public/assets/{ShareBranchSwitchDialog-C5BWlfbq.js → ShareBranchSwitchDialog-C6G5A_aK.js} +1 -1
- package/dist/public/assets/{ShareReceiveDialog-CI2Mloot.js → ShareReceiveDialog-DLEkjmkI.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-ohgoelQ3.js → ShareReceiveMissDialog-Ls1ECEge.js} +1 -1
- package/dist/public/assets/{SkillEditorActions-B3vkquAC.js → SkillEditorActions-AGeWFFyT.js} +1 -1
- package/dist/public/assets/{SourceEditor-BS9xKRLC.js → SourceEditor-DI6JkRTr.js} +1 -1
- package/dist/public/assets/{TerminalPanel-BNrFiNj3.js → TerminalPanel-Bf_h8SIB.js} +1 -1
- package/dist/public/assets/{TerminalSessionsHost-1SkLbZxP.js → TerminalSessionsHost-B2cWbpj-.js} +2 -2
- package/dist/public/assets/{TerminalWindowApp-CcIKz82K.js → TerminalWindowApp-2yCXBcQc.js} +1 -1
- package/dist/public/assets/{ThreadView-DbEiSAgi.js → ThreadView-D2BFrI_O.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-BRIL_hOz.js → TimelineDiffPane-B9KqEt7q.js} +1 -1
- package/dist/public/assets/{agent-diff-store-CL1zJhM8.js → agent-diff-store-Bi0IQPgd.js} +1 -1
- package/dist/public/assets/{agent-visibility-DboUkSIR.js → agent-visibility-HpfSUFqP.js} +1 -1
- package/dist/public/assets/{auth-state-cache-CnTQSDtz.js → auth-state-cache-BUVYaS5m.js} +1 -1
- package/dist/public/assets/{client-version-Cx5VddNZ.js → client-version-FVbajnsJ.js} +1 -1
- package/dist/public/assets/{config-provider-BvRqIV8_.js → config-provider-DIuwNlqX.js} +1 -1
- package/dist/public/assets/{dist-CRnLx168.js → dist-Cal4LUep.js} +148 -148
- package/dist/public/assets/{doc-hash-DaHNz5tZ.js → doc-hash-BSK-KaTu.js} +1 -1
- package/dist/public/assets/{documents-events-CO5GMB1j.js → documents-events-1HWCdfoh.js} +1 -1
- package/dist/public/assets/{file-tree-adapter-CMkAk18U.js → file-tree-adapter-Dw7Dgyj1.js} +1 -1
- package/dist/public/assets/{file-tree-utils-DW5kpGI7.js → file-tree-utils-DiUPuK3N.js} +1 -1
- package/dist/public/assets/{index-lO6NOXfq.js → index-Bh6-_Nba.js} +96 -96
- package/dist/public/assets/{lint-config-client-ClOK3XHG.js → lint-config-client-G_mrikOJ.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-BkNWMW9T.js → markdownlint-rule-browser-rS3aDGOb.js} +1 -1
- package/dist/public/assets/{navigation-targets-BvMgbXSl.js → navigation-targets-Ci2h-vaL.js} +1 -1
- package/dist/public/assets/{open-managed-artifact-tab-uWUnYmu7.js → open-managed-artifact-tab-DfGutPkc.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-ZP5ClzoO.js → pending-receive-nav-store-BuGLGemz.js} +1 -1
- package/dist/public/assets/{prop-types-CaVq0ILj.js → prop-types-B-N3_i3c.js} +1 -1
- package/dist/public/assets/{receive-store-O26Klsmj.js → receive-store-CL0RH8Oa.js} +1 -1
- package/dist/public/assets/{selection-context-D1dfmp_3.js → selection-context-zsjvL-8N.js} +1 -1
- package/dist/public/assets/{skill-actions-BOEtYQao.js → skill-actions-C_5-d4BC.js} +1 -1
- package/dist/public/assets/{skills-api-BxZRuTIF.js → skills-api-ChYiP1Zv.js} +1 -1
- package/dist/public/assets/{src-BPnSaHfB.js → src-D8jPu2QV.js} +1 -1
- package/dist/public/assets/{tag-pill-input-D3yKn_j2.js → tag-pill-input-B27HgfRy.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-DKN8qckv.js → target-navigation-intent-ClG4AlV8.js} +1 -1
- package/dist/public/assets/{terminal-launch-events-cbz64adZ.js → terminal-launch-events-N4CMVbPT.js} +1 -1
- package/dist/public/assets/{terminal-telemetry-B-8TrAWX.js → terminal-telemetry-DxTZB2oZ.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-u3Nddbn5.js → typing-burst-detector-BP7d86JP.js} +1 -1
- package/dist/public/assets/{uninstall-B_24eCu8.js → uninstall-DHjtqCbn.js} +1 -1
- package/dist/public/assets/{use-activity-panel-DfbfDD9Z.js → use-activity-panel-35_3901z.js} +1 -1
- package/dist/public/assets/{use-apply-config-color-theme-CsOxA7Ln.js → use-apply-config-color-theme-CK97Jvup.js} +1 -1
- package/dist/public/assets/{use-collab-url-DKVO0F_k.js → use-collab-url-D0INpn_f.js} +1 -1
- package/dist/public/assets/{use-live-xterm-theme-DxXMX-ZB.js → use-live-xterm-theme-C-fHLeXw.js} +1 -1
- package/dist/public/assets/{use-settings-route-R3f95s9q.js → use-settings-route-CXFzIfYo.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-FmmwhtBs.js → use-terminal-enabled-fhwpyN81.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-B4mNkRPy.js → use-timeline-entry-diff-CHWJnnz2.js} +1 -1
- package/dist/public/assets/{use-workspace-DQ7VjlT1.js → use-workspace-3T40FR83.js} +1 -1
- package/dist/public/assets/{workspace-paths-CFyvLimb.js → workspace-paths-B-NChZS2.js} +1 -1
- package/dist/public/index.html +35 -35
- package/dist/public/uninstall.html +2 -2
- package/dist/{repair-launch-json-LkGq6bbj.mjs → repair-launch-json-4OYtLMnw.mjs} +2 -2
- package/dist/{repair-mcp-configs-xbGF2ooR.mjs → repair-mcp-configs-BLJJ9tZq.mjs} +2 -2
- package/dist/repair-skills-B1Zc-g_X.mjs +1 -0
- package/dist/{repair-skills-C0Geadpr.mjs → repair-skills-CBmnNSO7.mjs} +2 -2
- package/dist/server-lock-DKRUWCqU.mjs +1 -0
- package/dist/{server-lock-rqh-yT8R.mjs → server-lock-vdpThyb4.mjs} +2 -2
- package/dist/{src-Dex2lDDb.mjs → src-D5V8i8YL.mjs} +2 -2
- package/dist/{src-Q2mWJGdH.mjs → src-DtcKZLt0.mjs} +116 -116
- package/dist/{src-phea8qFf.mjs → src-mOlBaMpr.mjs} +8 -6
- package/dist/{src-DF_K89lg.mjs → src-o9XsfdYT.mjs} +1 -1
- package/dist/{start-BprUXI6x.mjs → start-9cYd5WRC.mjs} +2 -2
- package/dist/start-JsQQrTQk.mjs +1 -0
- package/dist/{write-project-skill-CG87XS-d.mjs → write-project-skill-B_HecSEZ.mjs} +2 -2
- package/package.json +4 -4
- package/dist/constants-Jq21Pm6p.mjs +0 -2
- package/dist/git-handle-maG17s4k.mjs +0 -1
- package/dist/init-BBYxg46o.mjs +0 -1
- package/dist/loader-DtiWOOTx.mjs +0 -1
- package/dist/md-manager-BHEZ9tjn.mjs +0 -2
- package/dist/preview-Bt_EkZoA.mjs +0 -1
- package/dist/public/assets/FeedbackForm-CZgsAWY7.js +0 -1
- package/dist/repair-skills-D19a_XVe.mjs +0 -1
- package/dist/server-lock-DUfHjP3M.mjs +0 -1
- package/dist/start-kk-goUtr.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,$a as i,$i as a,$n as o,$r as s,$t as c,A as l,Aa as u,Ai as d,An as f,Ar as p,At as m,B as h,Ba as g,Bi as _,Bn as v,Br as y,Bt as b,Ci as x,Cn as S,Cr as C,Ct as w,D as ee,Da as te,Di as ne,Dn as re,Dr as ie,Dt as ae,E as oe,Ea as se,Ei as ce,En as le,Er as ue,Et as de,F as fe,Fi as pe,Fn as me,Fr as he,Ft as ge,G as _e,Ga as ve,Gi as ye,Gn as be,Gr as xe,Gt as Se,H as Ce,Ha as we,Hi as Te,Hn as Ee,Hr as De,Ht as Oe,In as ke,Ir as Ae,It as je,J as Me,Ja as Ne,Ji as Pe,Jn as Fe,Jr as Ie,Jt as Le,K as Re,Ki as ze,Kn as Be,Kr as Ve,Kt as He,La as Ue,Li as We,Ln as Ge,Lr as Ke,Lt as qe,M as Je,Ma as Ye,Mi as Xe,Mn as Ze,Mr as Qe,Mt as $e,N as et,Ni as tt,Nn as nt,Nr as rt,Nt as it,O as at,Oa as ot,Oi as st,On as ct,Or as lt,Ot as ut,Pa as dt,Pi as T,Pn as ft,Pr as pt,Pt as mt,Q as ht,Qa as gt,Qi as _t,Qn as vt,Qr as yt,Qt as bt,R as xt,Ra as St,Ri as Ct,Rn as wt,Rr as Tt,Rt as Et,S as Dt,Sa as Ot,Si as kt,Sn as eee,Sr as At,St as jt,T as Mt,Ta as Nt,Ti as Pt,Tn as Ft,Tr as It,Tt as Lt,U as Rt,Ua as zt,Ui as Bt,Un as Vt,Ur as Ht,Ut,V as Wt,Va as Gt,Vi as tee,Vn as nee,Vr as ree,Vt as iee,W as Kt,Wa as qt,Wi as Jt,Wn as Yt,Wr as Xt,Wt as Zt,X as Qt,Xa as $t,Xi as en,Xn as tn,Xr as nn,Xt as rn,Y as an,Ya as on,Yi as sn,Yn as cn,Yr as ln,Yt as un,Z as dn,Za as fn,Zi as pn,Zn as mn,Zr as hn,Zt as gn,_ as _n,_a as vn,_i as yn,_n as bn,_r as xn,_t as Sn,a as Cn,aa as wn,ai as Tn,an as En,ao as Dn,ar as On,at as kn,b as An,bi as jn,bn as Mn,br as Nn,bt as Pn,c as Fn,ca as In,ci as Ln,cn as aee,co as Rn,cr as oee,d as zn,da as Bn,di as Vn,dn as Hn,do as Un,dr as Wn,dt as Gn,ea as Kn,ei as qn,en as Jn,eo as Yn,er as see,et as Xn,f as Zn,fa as Qn,fi as $n,fn as er,fo as tr,fr as nr,ft as rr,g as ir,ga as ar,gi as or,gn as sr,gr as cr,gt as lr,h as ur,hi as dr,hn as fr,ho as pr,hr as mr,ht as hr,i as gr,ia as _r,ii as vr,in as yr,io as br,ir as xr,it as Sr,j as Cr,ji as wr,jn as Tr,jr as Er,jt as Dr,k as Or,ka as kr,ki as Ar,kn as jr,kr as Mr,kt as Nr,l as Pr,li as Fr,ln as Ir,lo as Lr,lr as Rr,m as zr,mi as Br,mn as Vr,mr as Hr,mt as Ur,n as Wr,na as Gr,ni as Kr,nn as qr,no as Jr,nr as Yr,nt as Xr,o as Zr,oa as Qr,oi as $r,on as ei,oo as ti,or as ni,ot as ri,pi as ii,pn as ai,pr as oi,pt as si,q as ci,qa as li,qi as ui,qn as di,qr as cee,qt as lee,r as fi,ra as uee,ri as pi,rn as dee,ro as mi,rr as fee,rt as hi,s as gi,sa as _i,si as vi,sn as yi,so as bi,sr as xi,st as Si,t as Ci,ta as pee,ti as wi,tn as mee,to as Ti,tr as hee,tt as Ei,u as Di,ua as Oi,ui as ki,un as Ai,uo as ji,ur as Mi,ut as Ni,v as Pi,va as Fi,vi as Ii,vn as gee,vr as _ee,vt as Li,w as vee,wi as Ri,wn as zi,wr as Bi,wt as Vi,x as Hi,xa as Ui,xi as Wi,xn as Gi,xr as Ki,xt as qi,y as Ji,ya as Yi,yi as Xi,yn as Zi,yr as Qi,yt as $i,z as ea,za as ta,zi as na,zn as ra,zr as ia,zt as aa}from"./src-Q2mWJGdH.mjs";import{$ as oa,At as sa,B as ca,C as la,Ct as ua,Dt as da,E as fa,Et as pa,G as ma,H as ha,I as ga,J as _a,K as va,Mt as ya,N as ba,Nt as xa,Ot as Sa,Pt as Ca,Q as wa,S as Ta,T as Ea,Tt as Da,V as Oa,W as ka,Y as Aa,Z as ja,_ as Ma,_t as E,at as Na,bt as Pa,ct as D,dt as O,ft as Fa,g as Ia,gt as k,h as La,ht as A,i as Ra,it as za,jt as Ba,kt as Va,l as Ha,lt as Ua,m as Wa,mt as j,n as Ga,nt as M,ot as Ka,pt as qa,r as Ja,rt as Ya,t as Xa,tt as N,u as Za,ut as P,v as Qa,vt as $a,w as eo,wt as to,yt as no,z as ro}from"./sleep-B2L0pvp4.mjs";import{c as io,i as ao,l as oo,n as so,s as co}from"./esm-CItKw7Y6.mjs";import{n as lo,t as uo}from"./md-manager-BHEZ9tjn.mjs";import{A as fo,C as po,D as mo,E as ho,N as go,O as _o,S as vo,T as yo,_ as bo,a as xo,b as So,c as Co,d as wo,f as To,g as Eo,h as Do,i as Oo,j as ko,k as Ao,l as jo,m as Mo,n as No,o as Po,p as Fo,r as Io,s as Lo,t as Ro,u as zo,v as Bo,w as Vo,x as Ho,y as Uo}from"./fs-traced-Cc6WsRtP.mjs";import{D as yee,E as bee,S as Wo,T as xee,a as Go,b as Ko,l as qo,p as Jo,r as F,s as Yo,x as Xo,y as Zo}from"./logger-B7Z8XO-z.mjs";import{a as Qo,i as $o,o as es,r as ts,s as ns,t as rs}from"./git-handle-JgY8Ytwb.mjs";import{t as is}from"./libesm-CG75CrN9.mjs";import{n as as,t as os}from"./build-fAc55Z_L.mjs";import{S as See,a as ss,c as cs,d as ls,f as us,g as ds,h as fs,i as ps,l as ms,m as hs,n as gs,r as _s,v as vs,x as ys,y as bs}from"./server-lock-rqh-yT8R.mjs";import{t as xs}from"./yazl-BafwB467.mjs";import{t as Ss}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Cs,c as ws,d as Ts,f as Es,h as Ds,i as Os,l as ks,m as As,n as js,o as Ms,p as Ns,r as Ps,s as Fs,t as Is,u as Ls}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as Rs,B as zs,C as Bs,D as Vs,E as Hs,F as Us,H as Ws,I as Gs,L as Ks,M as qs,N as Js,O as Ys,P as Xs,S as Zs,T as Qs,V as $s,_ as ec,a as tc,b as nc,c as rc,d as ic,f as ac,g as oc,h as sc,i as cc,j as lc,k as uc,l as dc,m as fc,n as pc,o as mc,p as hc,r as gc,s as _c,t as vc,u as yc,v as bc,w as xc,x as Sc,y as Cc,z as wc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Tc,c as Ec,d as Dc,i as Oc,l as kc,n as Ac,o as jc,r as Mc,s as Nc,t as Pc,u as Fc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as Ic,r as Lc,t as Rc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as zc}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as Bc}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as Vc,t as Hc}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Uc,t as Wc}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Gc,r as Kc,t as qc}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Jc,t as Yc}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Xc}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Zc}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Qc}from"./wrapper-BcpqREsI.mjs";import{createRequire as $c}from"node:module";import{execFile as el,spawn as tl,spawnSync as nl}from"node:child_process";import*as rl from"node:path";import{basename as il,delimiter as al,dirname as I,extname as ol,isAbsolute as sl,join as L,normalize as cl,posix as ll,relative as R,resolve as z,sep as ul,win32 as dl}from"node:path";import*as fl from"node:fs";import{appendFileSync as pl,chmodSync as ml,closeSync as hl,constants as gl,createReadStream as _l,createWriteStream as vl,existsSync as B,lstatSync as yl,mkdirSync as bl,mkdtempSync as xl,openSync as Sl,readFile as Cl,readFileSync as V,readSync as wl,readdirSync as Tl,readlinkSync as El,realpathSync as Dl,renameSync as Ol,rmSync as kl,rmdirSync as Al,statSync as jl,unlinkSync as Ml,writeFileSync as Nl,writeSync as Pl}from"node:fs";import{arch as Fl,availableParallelism as Il,homedir as Ll,hostname as Rl,platform as zl,tmpdir as Bl}from"node:os";import{access as Vl,chmod as Hl,constants as Ul,lstat as Wl,readFile as Gl,readdir as Kl,realpath as ql,stat as Jl,writeFile as Cee}from"node:fs/promises";import{Readable as Yl,Transform as wee,Writable as Tee}from"node:stream";import{URLSearchParams as Eee,fileURLToPath as Xl,pathToFileURL as Dee}from"node:url";import Zl,{createHash as Ql,randomUUID as $l,webcrypto as eu}from"node:crypto";import Oee from"crypto";import{Readable as tu}from"stream";import{Worker as kee}from"node:worker_threads";import{monitorEventLoopDelay as Aee,performance as nu}from"node:perf_hooks";import{createInterface as jee}from"node:readline";import{pipeline as ru}from"node:stream/promises";import{setTimeout as iu}from"node:timers/promises";import{promisify as au}from"node:util";import{lookup as Mee}from"node:dns/promises";import{request as Nee}from"node:http";import{request as Pee}from"node:https";import{createBrotliDecompress as Fee,createGunzip as Iee,createInflate as Lee}from"node:zlib";import{Http2ServerRequest as ou,constants as Ree}from"http2";import{AsyncLocalStorage as zee}from"node:async_hooks";import{lookup as Bee}from"node:dns";import Vee from"node:tls";var su=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=sl(t)?t:z(this.gitDir,t))}catch(e){if(!du(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 du(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]}:pu(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 du(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Hee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!fu(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(`..`)||sl(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Gee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!du(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return du(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 pu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function cu(e){return uu(z(e),``)}function lu(e){let t=z(e),n=z(Ll());if(t===n)return{kind:`absent`};let r=uu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=I(i);if(e===i||e===n)return{kind:`absent`};let r=uu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function uu(e,t){let n=L(e,`.git`),r;try{r=jl(n)}catch(e){return du(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new su(`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=sl(o)?o:z(e,o);try{if(!jl(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 su(`linked`,e,t,n,s)}}function Hee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Uee(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=Wee(i[1]);if(a.length>0)return a}return null}function Uee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Wee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function du(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function fu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Gee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?fu(t[1])?{kind:`symbolic`,target:t[1]}:null:pu(e)?{kind:`oid`,oid:e}:null}function pu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Kee(e){return`git-author-${pr(e.trim().toLowerCase())}`}const qee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function mu(e){let t=lu(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 hu(e){let t=mu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function gu(e){let t=mu(e);switch(t.kind){case`directory`:return z(t.path,_u(t.projectSubPath));case`linked`:if(!B(t.path))throw new vu(t.gitPath,t.path);return z(t.path,_u(t.projectSubPath));case`malformed-pointer`:throw new vu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new yu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function _u(e){return e===``?`ok`:`ok-${Jee(e)}`}function Jee(e){let t=e.split(ul).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Yee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Yee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var vu=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}},yu=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 Xee(e){let t;try{t=gu(e)}catch(e){if(e instanceof vu||e instanceof yu)return null;throw e}return B(z(t,`HEAD`))?t:null}function bu(e){return`refs/wip/${e}/`}function Zee(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
1
|
+
import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$a as i,$i as a,$n as o,$r as s,$t as c,A as l,Aa as u,Ai as d,An as f,Ar as p,At as m,B as h,Ba as g,Bi as _,Bn as v,Br as y,Bt as b,Ci as x,Cn as S,Cr as C,Ct as w,D as ee,Da as te,Di as ne,Dn as re,Dr as ie,Dt as ae,E as oe,Ea as se,Ei as ce,En as le,Er as ue,Et as de,F as fe,Fi as pe,Fn as me,Fr as he,Ft as ge,G as _e,Ga as ve,Gi as ye,Gn as be,Gr as xe,Gt as Se,H as Ce,Ha as we,Hi as Te,Hn as Ee,Hr as De,Ht as Oe,In as ke,Ir as Ae,It as je,J as Me,Ja as Ne,Ji as Pe,Jn as Fe,Jr as Ie,Jt as Le,K as Re,Ki as ze,Kn as Be,Kr as Ve,Kt as He,La as Ue,Li as We,Ln as Ge,Lr as Ke,Lt as qe,M as Je,Ma as Ye,Mi as Xe,Mn as Ze,Mr as Qe,Mt as $e,N as et,Ni as tt,Nn as nt,Nr as rt,Nt as it,O as at,Oa as ot,Oi as st,On as ct,Or as lt,Ot as ut,Pa as dt,Pi as T,Pn as ft,Pr as pt,Pt as mt,Q as ht,Qa as gt,Qi as _t,Qn as vt,Qr as yt,Qt as bt,R as xt,Ra as St,Ri as Ct,Rn as wt,Rr as Tt,Rt as Et,S as Dt,Sa as Ot,Si as kt,Sn as eee,Sr as At,St as jt,T as Mt,Ta as Nt,Ti as Pt,Tn as Ft,Tr as It,Tt as Lt,U as Rt,Ua as zt,Ui as Bt,Un as Vt,Ur as Ht,Ut,V as Wt,Va as Gt,Vi as tee,Vn as nee,Vr as ree,Vt as iee,W as Kt,Wa as qt,Wi as Jt,Wn as Yt,Wr as Xt,Wt as Zt,X as Qt,Xa as $t,Xi as en,Xn as tn,Xr as nn,Xt as rn,Y as an,Ya as on,Yi as sn,Yn as cn,Yr as ln,Yt as un,Z as dn,Za as fn,Zi as pn,Zn as mn,Zr as hn,Zt as gn,_ as _n,_a as vn,_i as yn,_n as bn,_r as xn,_t as Sn,a as Cn,aa as wn,ai as Tn,an as En,ao as Dn,ar as On,at as kn,b as An,bi as jn,bn as Mn,br as Nn,bt as Pn,c as Fn,ca as In,ci as Ln,cn as aee,co as Rn,cr as oee,d as zn,da as Bn,di as Vn,dn as Hn,do as Un,dr as Wn,dt as Gn,ea as Kn,ei as qn,en as Jn,eo as Yn,er as see,et as Xn,f as Zn,fa as Qn,fi as $n,fn as er,fo as tr,fr as nr,ft as rr,g as ir,ga as ar,gi as or,gn as sr,gr as cr,gt as lr,h as ur,hi as dr,hn as fr,ho as pr,hr as mr,ht as hr,i as gr,ia as _r,ii as vr,in as yr,io as br,ir as xr,it as Sr,j as Cr,ji as wr,jn as Tr,jr as Er,jt as Dr,k as Or,ka as kr,ki as Ar,kn as jr,kr as Mr,kt as Nr,l as Pr,li as Fr,ln as Ir,lo as Lr,lr as Rr,m as zr,mi as Br,mn as Vr,mr as Hr,mt as Ur,n as Wr,na as Gr,ni as Kr,nn as qr,no as Jr,nr as Yr,nt as Xr,o as Zr,oa as Qr,oi as $r,on as ei,oo as ti,or as ni,ot as ri,pi as ii,pn as ai,pr as oi,pt as si,q as ci,qa as li,qi as ui,qn as di,qr as cee,qt as lee,r as fi,ra as uee,ri as pi,rn as dee,ro as mi,rr as fee,rt as hi,s as gi,sa as _i,si as vi,sn as yi,so as bi,sr as xi,st as Si,t as Ci,ta as pee,ti as wi,tn as mee,to as Ti,tr as hee,tt as Ei,u as Di,ua as Oi,ui as ki,un as Ai,uo as ji,ur as Mi,ut as Ni,v as Pi,va as Fi,vi as Ii,vn as gee,vr as _ee,vt as Li,w as vee,wi as Ri,wn as zi,wr as Bi,wt as Vi,x as Hi,xa as Ui,xi as Wi,xn as Gi,xr as Ki,xt as qi,y as Ji,ya as Yi,yi as Xi,yn as Zi,yr as Qi,yt as $i,z as ea,za as ta,zi as na,zn as ra,zr as ia,zt as aa}from"./src-DtcKZLt0.mjs";import{$ as oa,At as sa,B as ca,C as la,Ct as ua,Dt as da,E as fa,Et as pa,G as ma,H as ha,I as ga,J as _a,K as va,Mt as ya,N as ba,Nt as xa,Ot as Sa,Pt as Ca,Q as wa,S as Ta,T as Ea,Tt as Da,V as Oa,W as ka,Y as Aa,Z as ja,_ as Ma,_t as E,at as Na,bt as Pa,ct as D,dt as O,ft as Fa,g as Ia,gt as k,h as La,ht as A,i as Ra,it as za,jt as Ba,kt as Va,l as Ha,lt as Ua,m as Wa,mt as j,n as Ga,nt as M,ot as Ka,pt as qa,r as Ja,rt as Ya,t as Xa,tt as N,u as Za,ut as P,v as Qa,vt as $a,w as eo,wt as to,yt as no,z as ro}from"./sleep-B2L0pvp4.mjs";import{c as io,i as ao,l as oo,n as so,s as co}from"./esm-CItKw7Y6.mjs";import{n as lo,t as uo}from"./md-manager-CAqfesEA.mjs";import{A as fo,C as po,D as mo,E as ho,N as go,O as _o,S as vo,T as yo,_ as bo,a as xo,b as So,c as Co,d as wo,f as To,g as Eo,h as Do,i as Oo,j as ko,k as Ao,l as jo,m as Mo,n as No,o as Po,p as Fo,r as Io,s as Lo,t as Ro,u as zo,v as Bo,w as Vo,x as Ho,y as Uo}from"./fs-traced-Cc6WsRtP.mjs";import{D as yee,E as bee,S as Wo,T as xee,a as Go,b as Ko,l as qo,p as Jo,r as F,s as Yo,x as Xo,y as Zo}from"./logger-B7Z8XO-z.mjs";import{a as Qo,i as $o,o as es,r as ts,s as ns,t as rs}from"./git-handle-BFhoHYr0.mjs";import{t as is}from"./libesm-CG75CrN9.mjs";import{n as as,t as os}from"./build-fAc55Z_L.mjs";import{S as See,a as ss,c as cs,d as ls,f as us,g as ds,h as fs,i as ps,l as ms,m as hs,n as gs,r as _s,v as vs,x as ys,y as bs}from"./server-lock-vdpThyb4.mjs";import{t as xs}from"./yazl-BafwB467.mjs";import{t as Ss}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Cs,c as ws,d as Ts,f as Es,h as Ds,i as Os,l as ks,m as As,n as js,o as Ms,p as Ns,r as Ps,s as Fs,t as Is,u as Ls}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as Rs,B as zs,C as Bs,D as Vs,E as Hs,F as Us,H as Ws,I as Gs,L as Ks,M as qs,N as Js,O as Ys,P as Xs,S as Zs,T as Qs,V as $s,_ as ec,a as tc,b as nc,c as rc,d as ic,f as ac,g as oc,h as sc,i as cc,j as lc,k as uc,l as dc,m as fc,n as pc,o as mc,p as hc,r as gc,s as _c,t as vc,u as yc,v as bc,w as xc,x as Sc,y as Cc,z as wc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Tc,c as Ec,d as Dc,i as Oc,l as kc,n as Ac,o as jc,r as Mc,s as Nc,t as Pc,u as Fc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as Ic,r as Lc,t as Rc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as zc}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as Bc}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as Vc,t as Hc}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Uc,t as Wc}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Gc,r as Kc,t as qc}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Jc,t as Yc}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Xc}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Zc}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Qc}from"./wrapper-BcpqREsI.mjs";import{createRequire as $c}from"node:module";import{execFile as el,spawn as tl,spawnSync as nl}from"node:child_process";import*as rl from"node:path";import{basename as il,delimiter as al,dirname as I,extname as ol,isAbsolute as sl,join as L,normalize as cl,posix as ll,relative as R,resolve as z,sep as ul,win32 as dl}from"node:path";import*as fl from"node:fs";import{appendFileSync as pl,chmodSync as ml,closeSync as hl,constants as gl,createReadStream as _l,createWriteStream as vl,existsSync as B,lstatSync as yl,mkdirSync as bl,mkdtempSync as xl,openSync as Sl,readFile as Cl,readFileSync as V,readSync as wl,readdirSync as Tl,readlinkSync as El,realpathSync as Dl,renameSync as Ol,rmSync as kl,rmdirSync as Al,statSync as jl,unlinkSync as Ml,writeFileSync as Nl,writeSync as Pl}from"node:fs";import{arch as Fl,availableParallelism as Il,homedir as Ll,hostname as Rl,platform as zl,tmpdir as Bl}from"node:os";import{access as Vl,chmod as Hl,constants as Ul,lstat as Wl,readFile as Gl,readdir as Kl,realpath as ql,stat as Jl,writeFile as Cee}from"node:fs/promises";import{Readable as Yl,Transform as wee,Writable as Tee}from"node:stream";import{URLSearchParams as Eee,fileURLToPath as Xl,pathToFileURL as Dee}from"node:url";import Zl,{createHash as Ql,randomUUID as $l,webcrypto as eu}from"node:crypto";import Oee from"crypto";import{Readable as tu}from"stream";import{Worker as kee}from"node:worker_threads";import{monitorEventLoopDelay as Aee,performance as nu}from"node:perf_hooks";import{createInterface as jee}from"node:readline";import{pipeline as ru}from"node:stream/promises";import{setTimeout as iu}from"node:timers/promises";import{promisify as au}from"node:util";import{lookup as Mee}from"node:dns/promises";import{request as Nee}from"node:http";import{request as Pee}from"node:https";import{createBrotliDecompress as Fee,createGunzip as Iee,createInflate as Lee}from"node:zlib";import{Http2ServerRequest as ou,constants as Ree}from"http2";import{AsyncLocalStorage as zee}from"node:async_hooks";import{lookup as Bee}from"node:dns";import Vee from"node:tls";var su=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=sl(t)?t:z(this.gitDir,t))}catch(e){if(!du(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 du(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]}:pu(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 du(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Hee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!fu(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(`..`)||sl(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Gee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!du(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return du(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 pu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function cu(e){return uu(z(e),``)}function lu(e){let t=z(e),n=z(Ll());if(t===n)return{kind:`absent`};let r=uu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=I(i);if(e===i||e===n)return{kind:`absent`};let r=uu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function uu(e,t){let n=L(e,`.git`),r;try{r=jl(n)}catch(e){return du(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new su(`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=sl(o)?o:z(e,o);try{if(!jl(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 su(`linked`,e,t,n,s)}}function Hee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Uee(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=Wee(i[1]);if(a.length>0)return a}return null}function Uee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Wee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function du(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function fu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Gee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?fu(t[1])?{kind:`symbolic`,target:t[1]}:null:pu(e)?{kind:`oid`,oid:e}:null}function pu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Kee(e){return`git-author-${pr(e.trim().toLowerCase())}`}const qee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function mu(e){let t=lu(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 hu(e){let t=mu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function gu(e){let t=mu(e);switch(t.kind){case`directory`:return z(t.path,_u(t.projectSubPath));case`linked`:if(!B(t.path))throw new vu(t.gitPath,t.path);return z(t.path,_u(t.projectSubPath));case`malformed-pointer`:throw new vu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new yu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function _u(e){return e===``?`ok`:`ok-${Jee(e)}`}function Jee(e){let t=e.split(ul).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Yee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Yee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var vu=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}},yu=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 Xee(e){let t;try{t=gu(e)}catch(e){if(e instanceof vu||e instanceof yu)return null;throw e}return B(z(t,`HEAD`))?t:null}function bu(e){return`refs/wip/${e}/`}function Zee(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 xu=`ok-checkpoint-v1: `;function Su(e){if(!e)return null;for(let t of e.split(`
|
|
3
3
|
`)){let e=t.trim();if(!e.startsWith(xu))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 Cu(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${xu}${JSON.stringify(t)}`}const wu=`ok-actor: `;function Tu(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),`${wu}${JSON.stringify(i)}`}function Eu(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=Qee(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 Qee(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 $ee(e){if(!e)return null;for(let t of e.split(`
|
|
4
4
|
`)){let e=t.trim();if(!e.startsWith(wu))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:Eu(n)}return null}function Du(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
@@ -1222,7 +1222,7 @@ tags: [lore, history]
|
|
|
1222
1222
|
`),i=n.nextFenced+(r?`
|
|
1223
1223
|
`:``)+t;Xx(b.dc.document,i,`agent`,void 0,S),eC(`mcp-write`),te=!0}ee=!0},b.origin)})}finally{tt?.touchMode(l,`idle`)}if(w){let e;switch(w.kind){case`invalid_value`:e={[w.key]:w.reason};break;case`reserved_key`:e={[w.key]:`'${w.key}' is reserved`};break;case`unknown_key`:e={[w.key]:`'${w.key}' is not a recognized key`};break;case`duplicate_target`:e={[w.key]:`'${w.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${w.expected.join(`, `)}; got: ${w.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${w.bytes} > ${w.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${w.reason}`};break;case`invalid_path`:e={[w.path.map(String).join(`.`)||`__path__`]:w.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(w)})`}}G(a,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(Wk(c,l,u,d,void 0,pi({clientName:f,clientVersion:p,label:m}),y),sS(),_i(_),te){let e=await ur(c);if(e?.kind===`failure`){pr(a,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){hr(a,`frontmatter-patch`);return}}lr(c,`frontmatter-patch`)}Xe?.setFocus(l,{agentName:u,currentDoc:c,writeKind:`write`,ts:Date.now()}),at?.();let re=er(c),ie=rr();ie===0&&cG().add(1,{"shadow.writer":`agent`,"agent.type":Vh(f)});let ae=gr(x);Cr(c,b.dc.document.getText(`source`).toString());let oe=br();oe.add(c);let se=kL(b.dc.document.getText(`source`).toString(),c,oe,Sr);q(a,200,hn,{timestamp:C,subscriberCount:re,systemSubscriberCount:ie,appliedKeys:ne,...v?{summary:v}:{},...ae?{warning:ae,warnings:[ae]}:{},brokenLinks:se},{handler:`frontmatter-patch`})}catch(e){if(e instanceof IC){G(a,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:LS(i)},`[frontmatter-patch] handler failed`),G(a,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ai(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 Ni=J(ke,async(e,t)=>{try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!MK(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let i=Qn(r);if(_S(i)||vS(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,rt,{docName:i,content:a.getText(`source`).toString(),lifecycle:Ai(a)},{handler:`document-read`});return}if(!B(aK(o,`file`,i))){G(t,404,`urn:ok:error:doc-not-found`,`Document not found: ${i}.`,{handler:`document-read`});return}let s=await n.openDirectConnection(i);try{let e=s.document;if(!e){G(t,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}q(t,200,rt,{docName:i,content:e.getText(`source`).toString(),lifecycle:Ai(e)},{handler:`document-read`})}finally{await s.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}),Pi=J(ke,async(e,t)=>{try{Nt&&await Nt.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`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(r)try{zG(o,r)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(i&&Tt&&YG(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=HS(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=HG(),n=XG({contentDir:o,contentFilter:Tt,dirFilter:r,maxEntries:t,maxDepth:s,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:${s===1?`d1:`:``}${a?`ok:`:``}${r??``}`,n=dn.get(e);if(!n){let t=new AbortController,i=(async()=>{let e=[],n=HG(),{truncated:i}=await ZG({contentDir:o,contentFilter:Tt,dirFilter:r,documents:e,maxEntries:n,maxDepth:s,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;dn.set(e,c),i.finally(()=>{dn.get(e)===c&&dn.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(),dn.get(e)===i&&dn.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await i.promise;if(c)return;q(t,200,Qe,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=l(),u=h(),d=ne?.()??new Map,f=[];for(let[e,t]of d)r&&!e.startsWith(`${r}/`)&&e!==r||f.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let p=[];try{let e=Nn(c);Sn?.signature!==e&&(Sn={signature:e,assets:Yie({contentDir:o,fileIndex:c,readMarkdown:e=>{try{return V(e,`utf-8`)}catch{return null}},isExcluded:Tt?e=>Tt.isPathIgnored(e):void 0})}),p=Sn?.assets??[]}catch(e){Sn=null,Y.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let m=new Set;for(let e of p)r&&!e.path.startsWith(`${r}/`)&&e.path!==r||(m.add(e.path),f.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 u){if(t.kind===`markdown`){if(r&&!e.startsWith(`${r}/`)&&e!==r)continue;let n=MS(e);f.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=cD(R(o,t.canonicalPath));f.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=BG(e);f.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=cD(R(o,t.canonicalPath)),a=BG(n);f.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=d.get(n),i=t?cD(R(o,t.canonicalPath)):n;for(let a of r)e(a)&&f.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 d)n(e,n=>{f.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:cD(R(o,t.canonicalPath))})});for(let[e,t]of u)n(e,n=>{let r=cD(R(o,t.canonicalPath));if(t.kind===`markdown`)f.push({kind:`document`,docName:n,docExt:MS(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=BG(n);f.push({kind:`file`,docName:n,path:n,docExt:`.${i}`,assetExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r})}})}f.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,Qe,{documents:f},{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}),Li=J(ke,async(e,t)=>{if(!We){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(!MK(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}q(t,200,Er,{docName:n,backlinks:We.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:Vn(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}),Ri=J(ke,async(e,t)=>{if(!We){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||!MK(t)||(r[t]=We.getBacklinkCount(t))}q(t,200,p,{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}),Hi=J(ke,async(e,t)=>{if(!We){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(!MK(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=br();q(t,200,pt,{docName:n,forwardLinks:We.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Hn(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}),Ui=J(ke,async(e,t)=>{if(!We){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&&!MK(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}=We.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=We.getLinkGraph());let s=br();q(t,200,he,{nodes:a.map(e=>{if(e.kind===`doc`){let t=Yn(e.docName,s);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Hn(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}),Ji=J(ke,async(e,t)=>{if(!We){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(!u(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}q(t,200,_ee,{orphans:We.getOrphans([...l().keys()],n).map(e=>({docName:e,title:Vn(e)}))},{handler:`orphans`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),$i=J(ke,async(e,t)=>{if(!We){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=br();q(t,200,xn,{hubs:We.getHubs(i).map(e=>({docName:e.docName,title:Hn(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}),ea=J(ke,async(e,t)=>{if(!We){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||!MK(e))){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>Qn(e)))]:void 0;q(t,200,cr,{deadLinks:We.getDeadLinks(br(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Vn(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}),ta=J(ia,async(i,a,s)=>{try{let{find:i,replace:c,offset:l}=s,u=rK(s.docName,a,`agent-patch`);if(u===null)return;let d=Qn(u),{agentId:f,agentName:p,colorSeed:m,clientName:h,clientVersion:g,label:_}=fi(s);if(dG(i)){uG().add(1,{result:`rejected`}),G(a,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(_S(d)||vS(d)){G(a,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`agent-patch`});return}let v=oD(s.summary),b=await r.getSession(d,f,{displayName:p,colorSeed:m,clientName:h}),x=qR(t,n,d,o,e.resolveEmbed),S=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,C;{let{frontmatter:e,body:t}=Fi(b.dc.document.getText(`source`).toString()),n=vn(e,t),r=l==null?n.indexOf(i):n.slice(l,l+i.length)===i?l:-1;if(r!==-1&&r>=e.length){let e=n.slice(0,r)+c+n.slice(r+i.length);C=await OC(b.dc.document,Fi(e).body,`patch`,S)}}let w=new Date().toISOString(),ee=!1,te=!1,ne=!1,re;try{let e=zn(h),t=Fn[e]??Pr(m??f);if(tt?.setPresence(f,{displayName:p,icon:e,color:t,currentDoc:d,mode:`writing`,ts:Date.now()}),nD(b.dc.document.getText(`source`),f,m,h),b.dc.document.transact(()=>{let{frontmatter:e,body:t}=Fi(b.dc.document.getText(`source`).toString()),n=vn(e,t),r=l==null?n.indexOf(i):n.slice(l,l+i.length)===i?l:-1;if(r===-1){l==null?ee=!0:te=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":d,findLength:i.length,replaceLength:c.length,hadOffset:l!=null})),Zne();return}if(r<e.length){ne=!0;return}let{body:a}=Fi(n.slice(0,r)+c+n.slice(r+i.length)),o=jC(b.dc.document);re=AC(b.dc.document,a,`patch`,S,C);let s=Un(o,jC(b.dc.document))??void 0;b.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Patched (${p}): ${i.slice(0,50)}`,...s===void 0?{}:{changedBlocks:s}})},b.origin),re!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":d,position:`patch`,intendedBytes:re.intendedBytes,actualBytes:re.actualBytes,byteDelta:re.byteDelta,"agent.id":f,"agent.client_name":h})),!ee&&!te&&!ne){let{stored:e}=hi(v);Wk(d,f,p,m,void 0,pi({clientName:h,clientVersion:g,label:_}),e),sS(),_i(v),SG(`agent-patch`,re)}}finally{tt?.touchMode(f,`idle`)}if(te){G(a,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ee){G(a,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ne){uG().add(1,{result:`rejected`}),G(a,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 ie=await ur(d);if(ie?.kind===`failure`){pr(a,ie.failure,`agent-patch`);return}if(ie?.kind===`divergence`){hr(a,`agent-patch`);return}lr(d,`agent-patch`),Xe?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`edit`,ts:Date.now()}),at?.();let ae=er(d),oe=rr();oe===0&&cG().add(1,{"shadow.writer":`agent`,"agent.type":Vh(h)});let{response:se}=hi(v),ce=b.dc.document.getText(`source`).toString();Cr(d,ce);let le=await JP(ce,d),ue=br();ue.add(d);let de=kL(ce,d,ue,Sr),fe=gr(x),pe=re===void 0?void 0:YS(re),me=[...pe?[pe]:[],...fe?[fe]:[],...le??[],...await nl(b.dc.document.getText(`source`).toString(),d)];q(a,200,y,{timestamp:w,subscriberCount:ae,systemSubscriberCount:oe,...se?{summary:se}:{},...pe?{warning:pe}:fe?{warning:fe}:{},...me.length>0?{warnings:me}:{},brokenLinks:de},{handler:`agent-patch`})}catch(e){if(e instanceof GS){KS(a,e,`agent-patch`);return}if(e instanceof XS){QS(a,e,`agent-patch`);return}if(e instanceof IC){G(a,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:LS(i)},`[agent-patch] handler failed`),G(a,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),oa=J(ree,async(t,n,i)=>{try{let t=rK(i.docName,n,`agent-undo`);if(t===null)return;let a=Qn(t),{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=fi(i);if(_S(a)||vS(a)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=i,p,m;if(i.scope===`count`?(p=`count`,m=i.count):p=i.scope===`session`||i.scope===`file`?`session`:`last`,!r.hasSession(a,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 r.getSession(a,f),g=!1;try{let t=zn(l),n=Fn[t]??Pr(c??o);tt?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:a,mode:`writing`,ts:Date.now()}),g=PC(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0,m),g&&Wk(a,f,s,c,void 0,pi({clientName:l,clientVersion:u,label:d}))}finally{tt?.touchMode(o,`idle`)}if(g){let e=await ur(a);if(e?.kind===`failure`){pr(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){hr(n,`agent-undo`);return}ar(a,`agent-undo`)}Xe?.setFocus(f,{agentName:f,currentDoc:a,writeKind:`undo`,ts:Date.now()}),q(n,200,De,{docName:a,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof GS){KS(n,e,`agent-undo`);return}Y.error({err:e,requestId:LS(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`}),sa=J(ke,async(e,t)=>{try{let n=Rh(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,be,Aie(r,n),{handler:`agent-activity`})}catch(n){Y.error({err:n,requestId:LS(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}),la=J(ke,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=Rh(n.searchParams.get(`agentId`)),a=n.searchParams.get(`docName`),o=n.searchParams.get(`keptCount`);if(i===null){G(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!a||a.trim()===``){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!MK(a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=Qn(a);if(_S(s)||vS(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=r.getLiveSession(s,i);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}=Die(u.undoStack,c,d,s);q(t,200,Be,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){Y.error({err:n,requestId:LS(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}),ua=J(ke,async(e,t)=>{try{await we?.(),q(t,200,see,{},{handler:`test-flush-git`})}catch(n){Y.error({err:n,requestId:LS(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}),da=J(ke,async(e,t)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=Qn(i.searchParams.get(`docName`)??`test-doc`),s;try{s=uD(a,o)}catch(e){Y.error({err:e,docName:a},`[test-reset] safeContentPath rejected docName`),G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await r.closeAll(a),n.closeConnections(a);let c=`onStoreDocument-${a}`;n.debouncer.isDebounced(c)&&await n.debouncer.executeNow(c);let l=n.documents.get(a);if(l&&await(Ot??n.unloadDocument.bind(n))(l),Nl(s,``,`utf-8`),We&&(We.deleteDocument(a),We.saveToDisk().catch(e=>{Y.warn({docName:a,err:e},`[backlinks] Failed to persist cache after test-reset for ${a}`)}),Ye?.(`backlinks`),Ye?.(`graph`)),i.searchParams.get(`reset-okignore`)!==`false`)try{let e=z(o,`.okignore`),t=n.documents.get(Ne);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},MD)}B(e)&&Nl(e,``,`utf-8`),Tt&&await Tt.rebuildIgnorePatterns()}catch(e){Y.warn({err:e},`[test-reset] okignore reset partial failure`)}Ye?.(`files`),q(t,200,fee,{},{handler:`test-reset`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),pa=J(ke,async(e,t)=>{try{if(!We){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await We.rebuildFromDisk(),await We.ingestGlobalSkillBundles([z(Ns,`.ok`,`skills`)]),We.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist cache after test-rescan-backlinks`)}),Ye?.(`backlinks`),Ye?.(`graph`),q(t,200,hee,{},{handler:`test-rescan-backlinks`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),ma=J(ke,async(e,t)=>{try{if(!pe){G(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await pe(),Ye?.(`files`),q(t,200,Yr,{},{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}),ga=J(ue,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=fi(n),o=Ce?.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=Re?.()??`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 uR(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[TR],l=!0}let d=Ue??`.`,f=oD(typeof n.summary==`string`?n.summary:void 0),p=await BR(o,d,c,u,f.kind===`value`?f.value:void 0,l?{includeUpstream:!1}:void 0);F(`history`).info({checkpointRef:p.checkpointRef},`checkpoint`);try{await gU(o,QH(o.gitDir))}catch(e){Y.warn({err:e},`[rename-log] post-saveVersion GC failed`)}q(t,200,ie,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(n){Y.error({err:n,requestId:LS(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`}),_a=J(ke,async(e,t)=>{let n=Ce?.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 we?.();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`)??Re?.()??`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=hs(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}=fn.run(u,()=>iG(n,e.folderRel,Ue??`.`,{branch:o,limit:s,offset:l}));f&&zW(`folder`),q(t,200,C,{...await d},{handler:`history`});return}let s=Ue??`.`,c=OG(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}=fn.run(_,()=>rG(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&zW(`doc`);let a=await e,c=Date.now()-v;F(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),q(t,200,C,{...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 va(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=Ce?.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=Ue??`.`,o=OG(i,a);if(`error`in o){G(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=cR(r),c=Re?.()??`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 xU(r,i,n,c,QH(r.gitDir),e=>{let t=OG(e,a);return`error`in t?`${e}.md`:t.path},nU());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,Bi,{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 ya=J(nee,async(t,r,i)=>{let a=JR(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&&US(o)){KS(r,new GS({file:NS(i.docName)}),`rollback`);return}let s=Ce?.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=Ue??`.`,d=OG(c,u);if(`error`in d){G(r,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=cR(s),p=Date.now();try{let t=QH(s.gitDir),i=nU(),o=await xU(s,c,l,Re?.()??`main`,t,e=>{let t=OG(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 AR(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 wC(d,g),v;h.transact(()=>{Zx(h,d,g,_),v=JS(h.getText(`source`).toString(),d,`rollback`)},TG),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}:{}})),SG(`rollback`,v);let y;switch(a.kind){case`agent`:{let e=l.slice(0,8),t=a.summary.kind===`value`,n=t?a.summary:oD(`Restored to ${e}`),r=hi(n);y=t||!r.response?r.response:gi(r.response),Wk(c,a.writerId,a.displayName,a.colorSeed,ju(c,l),a.actor,r.stored),sS(),_i(n,!t);break}case`principal`:{let e=hi(a.summary);y=e.response,Wk(c,a.writerId,a.displayName,a.colorSeed,ju(c,l),a.actor,e.stored),_i(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)}`)}pG().add(1,{kind:`rollback`,attribution_kind:a.kind});let b=await ur(c);if(b?.kind===`failure`){pr(r,b.failure,`rollback`);return}if(b?.kind===`divergence`){hr(r,`rollback`);return}ar(c,`rollback`);let x=Date.now()-p;F(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),a.kind===`agent`&&Xe?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:YS(v);q(r,200,Ee,{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`}),xa=J(ke,async(e,t)=>{try{q(t,200,mn,gS(),{handler:`metrics-reconciliation`})}catch(n){Y.error({err:n,requestId:LS(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}),Sa=J(ke,async(e,t)=>{try{q(t,200,tn,na(),{handler:`metrics-parse-health`})}catch(n){Y.error({err:n,requestId:LS(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}),Ca=J(ke,async(e,n)=>{try{Nt&&await Nt.catch(e=>{Y.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=ze?.(),i=VL();q(n,200,ye,{serverInstanceId:s,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}),Ta=O({agents:N(O({id:A(),name:A(),version:A(),description:A().optional(),license:A().optional(),iconUrl:A().optional(),website:A().optional(),source:wa([`registry`,`custom`]),supported:M(),featured:M(),harness:O({cli:wa([`claude`,`codex`,`cursor`,`opencode`,`pi`]),availability:wa([`present`,`not-found`,`unknown`])}).optional()})),stale:M(),maxThreads:P()}),Da=J(ke,async(e,t)=>{if(bt===void 0){G(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=Gu(),{agents:n,stale:r}=await bt.getCatalog(),i=await xt?.()??[],a=await Ct();q(t,200,Ta,{agents:[...n.map(t=>{let n=tD[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:Hu.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 ka(e,t){if(!$V(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!eH(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,Bt,n,{handler:`principal`})}async function Aa(e,t){if(!$V(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!eH(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=tt?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);q(t,200,cn,{presence:r},{handler:`metrics-agent-presence`})}catch(n){Y.error({err:n,requestId:LS(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 ja(e,t){if(!$V(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!eH(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(_S(t)||vS(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,Fe,{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 Ma(e,t){if(!$V(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!eH(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,vt,{decisions:uz().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:LS(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 E(e,t){if(!$V(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!eH(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=eA.read();q(t,200,Mr,{entries:n,count:n.length,detection:oA(n[0])},{handler:`embed-detect`})}async function Na(e,t){if(!$V(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!eH(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(o),r=n,i=!0;try{r=Dl(n)}catch(e){let r=ys(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,lt,{contentDir:r,pathSeparator:ul,symlinkResolved:i},{handler:`workspace`})}let Pa=J(ke,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=Xie(n),i=ol(n).slice(1).toLowerCase();if(!r||!ba.has(i)){G(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let a=Dl(o),s=z(a,n),c;try{c=Dl(s)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!dD(c,a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let l;try{l=jl(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=DD(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=ha.has(i),f={"Content-Type":r,"Content-Length":String(l.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":ro.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`]=Oa),t.writeHead(200,f);try{await ru(_l(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}),D=1048576,Fa=J(ke,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=Dl(o),i=z(r,n),a;try{a=Dl(i)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!dD(a,r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let s;try{s=jl(a)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!s.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(DD(r,a)!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(s.size>D){G(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${D}-byte text-viewer cap.`,{handler:`asset-text`});return}let c=(await Gl(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}),Ia=J(ke,async(e,t)=>{try{if(!Ce?.current){q(t,200,It,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=z(Ce.current.gitDir,`rescue`);if(B(r))try{let t=Tl(r).filter(e=>TS(e));for(let i of t){let t=z(r,i),a=jl(t);if(e-a.mtimeMs>864e5){try{Ml(t)}catch(e){Y.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:DS(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=Re?.()??`main`,t=await NR(Ce.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,It,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}),k=J(f,async(e,t,n)=>{try{let e=JR(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(!TS(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(o),a=z(i,r);if(!lD(a,i)){G(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let s=DS(r);if(_S(s)||vS(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`create-page`});return}if($G(r)||mi(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' 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=``,u;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=DO(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),d;try{d=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=ir(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;l=Dk(f,{date:kk(),user:p}),u=o.scope}bl(I(a),{recursive:!0});try{Nl(a,l,{encoding:`utf-8`,flag:`wx`})}catch(e){if(uK(e)){G(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let d=DS(r);switch(Rt?.delete(d),Tt&&Tt.incrementMdDir(I(d)),tz(a,rz(l)),e.kind){case`agent`:case`principal`:Wk(d,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}_?.({kind:`create`,path:a,docName:d,content:l}),We&&(We.updateDocumentFromMarkdown(d,l),We.saveToDisk().catch(e=>{Y.warn({docName:d,err:e},`[backlinks] Failed to persist create-page cache for ${d}`)}),Ye?.(`backlinks`),Ye?.(`graph`)),Ye?.(`files`),u!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:c,templateScope:u,docName:d})),q(t,200,Tr,{docName:d},{handler:`create-page`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),La=J(ct,async(e,t,n)=>{try{if(JR(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(!QG(e)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if($G(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=aK(o,`folder`,e);if(B(r)){G(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}jo(r,{recursive:!0}),Dn(e),Ye?.(`files`),q(t,200,jr,{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`}),Ra=J(ft,async(e,t,r)=>{try{let e=JR(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,s=i===`file`?DS(a):a;if(!QG(a)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if($G(a)||i===`file`&&(_S(s)||vS(s))||i===`folder`&&eK(a)){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}i===`file`&&xK(o,a);let c=aK(o,i,a);if(!B(c)){if(i===`file`){let e=aK(o,`folder`,a);if(B(e)&&jl(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=jl(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`?[hK(o,a)]:ai(aK(o,`folder`,a)),d=ot?.(),f=new Set(d?d.getConflicts().map(e=>e.file):[]);for(let e of u){let r=e,i=n.documents.get(r),a=NS(r),o=i!==void 0&&US(i),s=f.has(a);if(o||s){KS(t,new GS({file:a}),`duplicate-path`);return}}let p,m=[];if(i===`file`){let e=ol(c);if(p=_K(o,s).docName,_S(p)||vS(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=gK(o,p,e),r=V(c,`utf-8`),i=I(n),a=B(i);try{jo(i,{recursive:!0}),Bo(n,r,{encoding:`utf-8`,flag:`wx`})}catch(e){if(uK(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{Mo(i)}catch(e){let t=ys(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{jS(p,e),Rt?.delete(p),Tt&&(Tt.incrementMdDir(I(p)),l=!0),tz(n,rz(r)),_?.({kind:`create`,path:n,docName:p,content:r}),We?.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 PS(p),Tt&&l&&Tt.decrementMdDir(I(p)),_?.({kind:`delete`,path:n,docName:p}),e}}else{if(p=vK(o,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=aK(o,`folder`,p);try{Po(c,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(uK(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 bK(o,p))Dn(e);let e=yK(o,p);m=e.map(e=>e.docName);for(let t of e){let e=ol(t.fullPath);jS(DS(t.docName),e),Rt?.delete(t.docName),Tt&&Tt.incrementMdDir(I(t.docName)),tz(t.fullPath,rz(t.content)),_?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),We?.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)Wk(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)}`)}We&&m.length>0&&(We.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist duplicate-path cache`)}),Ye?.(`backlinks`),Ye?.(`graph`)),Ye?.(`files`),q(t,200,me,{kind:i,path:p,duplicatedDocNames:m},{handler:`duplicate-path`})}catch(e){if(e instanceof lK){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=dK(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`}),za=J(ke,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(!MK(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=Ln(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,Ge,{docName:n,headings:jK(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}),Ba=J(ra,async(e,t,r)=>{try{let e=JR(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:s}=r;if(!QG(a)||!QG(s)){G(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(i===`file`&&(_S(a)||_S(s)||vS(a)||vS(s))){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if($G(a)||$G(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(a===s){q(t,200,v,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let c=i===`asset`&&TS(a)&&TS(s)?`file`:i;if(c===`asset`){let n;try{n=TS(a)&&!TS(s)?await li(a,s):await ci(a,s)}catch(e){if(e instanceof GS){KS(t,e,`rename-path`);return}let{status:n,type:r,error:i}=Ar(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} → ${s}`;r=vi(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{Y.debug({kind:`asset`,fromPath:a,toPath:s,affectedDocs:n.rewrittenDocs.length,affectedAssets:n.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(pG().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Me)try{await Me()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}q(t,200,v,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}c===`file`&&xK(o,a);let l=c===`file`?[hK(o,a)]:ai(aK(o,`folder`,a)),u=ot?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of l){let r=e,i=n.documents.get(r),a=NS(r),o=i!==void 0&&US(i),s=d.has(a);if(o||s){KS(t,new GS({file:a}),`rename-path`);return}}if(Tt){let e=TS(a)?ol(a):MS(a);if(c===`file`?Tt.isExcluded(TS(s)?s:`${s}${e}`):Tt.isDirExcluded(s)){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 di(a,s,c,f?{actor:f}:{})}catch(e){if(e instanceof BM){G(t,409,`urn:ok:error:doc-already-exists`,kr(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,v,{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=vi(e,`Renamed ${a} → ${s}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Nu(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{Y.debug({kind:i,fromPath:a,toPath:s,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),pG().add(1,{kind:`rename-${c}`,attribution_kind:e.kind}),Me)try{await Me()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}q(t,200,v,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=Ar(e);G(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Va=J(Ze,async(e,t,r)=>{try{fi(r);let{kind:e,path:i}=r;if(!QG(i)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let a=e===`asset`?ii(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 s=a.path,c=e===`asset`&&TS(s)?`file`:e;if(c===`file`&&xK(o,s),$G(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let l=c===`asset`?aK(o,`folder`,s):aK(o,c,s);if(!B(l)){G(t,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`});return}let u=jl(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`?[hK(o,s)]:ai(aK(o,`folder`,s)),f=ot?.(),p=new Set(f?f.getConflicts().map(e=>e.file):[]);for(let e of d){let r=e,i=n.documents.get(r),a=NS(r),o=i!==void 0&&US(i),s=p.has(a);if(o||s){KS(t,new GS({file:a}),`delete-path`);return}}if(await Fr(d,`deleted-upstream`),Rt)for(let e of d)_S(e)||vS(e)||(Rt.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));c===`file`||c===`asset`?Eo(l):(Fo(l,{recursive:!0,force:!1}),kn(s)),Pn();for(let e of d)_?.({kind:`delete`,path:z(o,NS(e)),docName:e});Ye?.(`files`),q(t,200,nt,{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`}),Ha=J(Vt,async(e,t,n)=>yo(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":No(n.path),"ok.cleanup.path.role":Ro(n.path)}},async()=>{try{if(JR(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(!QG(r)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&TS(r)?`file`:e,a=DS(r);i===`file`&&xK(o,r);let s=i===`folder`&&eK(r);if(i===`file`&&(_S(a)||vS(a))||s||$G(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(i===`asset`){Pn(),Ye?.(`files`),q(t,200,Yt,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let c=l(),u=i===`file`?c.has(a)?[a]:[]:tK(c,i,r);if(Pn(),u.length===0){q(t,200,Yt,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Fr(u,`deleted-upstream`),Rt)for(let e of u)_S(e)||vS(e)||(Rt.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of u)_?.({kind:`delete`,path:z(o,NS(e)),docName:e});i===`folder`&&kn(r),Ye?.(`files`),q(t,200,Yt,{deletedDocNames:u},{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`}),Ua=J(ke,async(e,t)=>{try{let e=l(),n=[];for(let[t,r]of e){let e=MS(t),i,a;if(r.title!==void 0)i=r.title,a=r.icon;else{i=t;try{let n=V(z(o,`${t}${e}`),`utf-8`);i=eF(n,t),a=tF(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,wt,{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}),Wa=J(ke,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(!MK(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(_S(r)||vS(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`suggest-links`});return}q(t,200,Qi,await jW({hocuspocus:n,fileIndex:l(),docName:r}),{handler:`suggest-links`})}catch(e){if(e instanceof uW){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 j(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 RG(e,T??o)}catch(e){if(e instanceof XI){G(t,ZI(e.reason),e.reason,$I(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:s,parentDocName:c,placement:l}=n,u=()=>{if(B(i))try{Ml(i)}catch{}},f=Oj(Pe,{parentDocName:c,placement:l||void 0},t,{handler:`upload-asset`});if(!f.ok){u();return}let{parentDocName:p,placement:m}=f.value,{agentId:h,agentName:g}=fi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(s===0){u(),G(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(p.includes(`\0`)||p.includes(`..`)||p.startsWith(`/`)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let _=z(o),v;try{v=m===`parent-dir`?`./`:d?.()??`./`}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(!Ea(v)){u(),G(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let y=NG(p,fa(v),_);if(!dD(y,_)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{iK(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{bl(y,{recursive:!0})}catch(e){if(!uK(e)){u();let n=QI(e);G(t,ZI(n),n,$I(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=Dl(y),n;try{n=Dl(_)}catch{n=_}if(!dD(e,n)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(ys(e)!==`ENOENT`){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let b=PG(i,4100),x=await bie(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 LG(y,a,s);if(n){u();let r=cD(R(o,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!0,mime:S??null,size:s,destPath:r,httpStatus:200},`[upload] dedup hit`),q(t,200,ui,{src:n,path:r,deduped:!0},{handler:`upload-asset`});return}}let w;if(!r||r===`upload`||kG.test(r)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=r?ol(r).slice(1):``,n=C??t??``;w=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else w=MG(r);try{let n=$oe(i,y,w),r=cD(R(o,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!1,mime:S??null,size:s,destPath:r,httpStatus:200},`[upload] write ok`),q(t,200,ui,{src:n,path:r,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof XI?n.reason:`urn:ok:error:storage-error`;Y.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:LS(e),agentId:h,agentName:g,filename:w,size:s,reason:r,httpStatus:ZI(r),err:n},`[upload] write failed`),G(t,ZI(r),r,$I(r),{handler:`upload-asset`,cause:n})}}let Ga=`/api/local-op/clone`,Ka=`/api/local-op/ok-init`,qa=600*1e3,Ja={stdio:[`ignore`,`ignore`,`pipe`]},Ya={stdio:[`ignore`,`pipe`,`pipe`]},Xa={stdio:`ignore`},Za=`local-op-clone`,Qa=J(Te,$a,{handler:Za,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Za})});async function $a(e,t,n){let{url:r,dir:i,branch:a}=n;if(!vV(r)){G(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Za,cause:Error(`url=${r}`)});return}if(!SV(i)){G(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Za,cause:Error(`dir=${i}`)});return}if(!ln.tryAcquire(Ga)){G(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Za,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=HS(t,Za),s=null,c=VV({cliArgs:st,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:vF(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=FV(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(vF(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 eo(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:Za},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),ln.release(Ga)}})(),t.on(`close`,()=>{c.cancel()})}async function eo(e,t){let n=z(yV(e)),r=AD(n),i=JI(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=st,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=tl(a,s(e),uj({...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 iu(500);let t=JI(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=ps(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=ps(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 to=`local-op-ok-init`,no=J(Hr,async(e,t,n)=>{let{projectPath:r}=n;if(!sl(r)){G(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:to,cause:Error(`projectPath=${r}`)});return}let i;try{i=Dl(r)}catch(e){q(t,200,mr,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:to});return}if(!SV(i)){G(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:to,cause:Error(`projectPath=${r}`)});return}let a=mu(i).kind;if(a!==`directory`&&a!==`linked`){Y.warn({project:il(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${il(i)} result=not-a-git-worktree kind=${a}`),q(t,200,mr,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:to});return}if(Rz(i)){Y.warn({project:il(i),result:`already-initialized`},`[ok-init] action=init project=${il(i)} result=already-initialized`),q(t,200,mr,{ok:!0,projectPath:i},{handler:to});return}if(!ln.tryAcquire(Ka)){G(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:to,extraHeaders:{"Retry-After":`2`}});return}try{await $o(async()=>{hB(i)}),Y.warn({project:il(i),result:`success`},`[ok-init] action=init project=${il(i)} result=success`),q(t,200,mr,{ok:!0,projectPath:i},{handler:to})}catch(e){let n=e instanceof Error?e.message:String(e);Y.warn({project:il(i),result:`failed`,reason:n},`[ok-init] action=init project=${il(i)} result=failed reason=${n}`),q(t,200,mr,{ok:!1,reason:`init-failed`,message:n},{handler:to})}finally{ln.release(Ka)}},{handler:to,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:to})}),so=`/api/local-op/auth/login`,lo=`/api/local-op/auth/status`,uo=`/api/local-op/auth/repos`,fo=`/api/local-op/auth/signout`,po=`/api/local-op/auth/pat`,mo=`/api/local-op/auth/gh-login`,go=dt??15e3,_o=960*1e3,vo=()=>cF(T??o),bo={current:null},xo={current:null};function Co(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!ln.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=HS(t,n),l=e=>{if(!(t.writableEnded||t.destroyed))try{t.write(e)}catch{}},u=setInterval(()=>{l(`${JSON.stringify({type:`ping`})}\n`)},go);u.unref();let d=()=>{u!==null&&(clearInterval(u),u=null)},f=s(e=>{if(e.type===`error`){c(500,`urn:ok:error:auth-failed`,o,{cause:e.message?Error(e.message):void 0});return}wG(e,ot),l(`${JSON.stringify(e)}\n`)});i.current=f;let p=()=>{d(),i.current===f&&console.warn(JSON.stringify({event:`ok-local-op:auth-stream-detached`,channel:`auth`,transport:`http`,handler:n}))};t.on(`close`,p),f.done.finally(()=>{if(d(),t.off(`close`,p),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===f&&(i.current=null,ln.release(r))})}let wo=`local-op-auth-login`,To=J(ni,Do,{handler:wo,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:wo})});async function Do(e,t,n){let r=n.host??vo();Co({res:t,handler:wo,guardKey:so,inFlight:bo,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>kV({cliArgs:st,host:r,timeoutMs:_o,onEvent:e})})}let Oo=`local-op-auth-gh-login`,ko=J(ni,async(e,t,n)=>{let r=n.host??vo(),i=await YV();if(i===null){G(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:Oo});return}Co({res:t,handler:Oo,guardKey:mo,inFlight:xo,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>QV({host:r,ghPath:i,timeoutMs:_o,onEvent:e})})},{handler:Oo,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Oo})}),Ao=`local-op-auth-cancel`,Io=J(xr,rB(async(e,t,n)=>{let r=n.channel===`gh-login`?{inFlight:xo,guardKey:mo}:{inFlight:bo,guardKey:so},i=r.inFlight.current;i&&(i.cancel(),r.inFlight.current=null,ln.release(r.guardKey)),q(t,200,On,{},{handler:Ao})},{handler:Ao,title:`Failed to cancel the sign-in.`}),{handler:Ao,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Ao})}),Lo=`local-op-auth-status`,zo=J(ni,async(e,t,n)=>{let r=n.host??vo();if(!ln.tryAcquire(lo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Lo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=st,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=tl(e,i,uj({...Ya,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(`
|
|
1224
1224
|
`).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 YV()!==null;o===null?q(t,200,Mi,{authenticated:!1,ghAvailable:s},{handler:Lo}):q(t,200,Mi,{...o,ghAvailable:s},{handler:Lo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Lo,cause:e})}finally{ln.release(lo)}},{handler:Lo,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Lo})}),Vo=`local-op-auth-pat`,Ho=J(xi,async(e,t,n)=>{let r=n.host??vo();if(!ln.tryAcquire(po)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:Vo,extraHeaders:{"Retry-After":`5`}});return}try{let e=await AV({cliArgs:st,host:r,token:n.token});e.ok?(CG(ot),q(t,200,oee,{host:e.host,login:e.login},{handler:Vo})):G(t,400,`urn:ok:error:auth-failed`,e.error,{handler:Vo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:Vo,cause:e})}finally{ln.release(po)}},{handler:Vo,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Vo})}),Uo=`local-op-auth-repos`,Go=J(ni,qo,{handler:Uo,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Uo})});async function qo(e,t,n){let r=n.host??vo();if(!ln.tryAcquire(uo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Uo,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=HS(t,Uo),[a,...o]=st,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=tl(a,s,uj({...Ya,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},qa);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
|
|
1225
|
-
`);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(),ln.release(uo))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),ln.release(uo))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),ln.release(uo))})}let Jo=`local-op-auth-signout`,Yo=J(ni,async(e,t,n)=>{let r=n.host??vo();if(!ln.tryAcquire(fo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Jo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=st,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=tl(e,i,uj({...Xa,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,On,{},{handler:Jo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Jo,cause:e})}finally{ln.release(fo)}},{handler:Jo,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Jo})}),Zo=`/api/local-op/auth/set-identity`,es=`local-op-auth-set-identity`,ts=J(Rr,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!T){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:es});return}if(!ln.tryAcquire(Zo)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:es,extraHeaders:{"Retry-After":`5`}});return}try{nB(T,r,i),ot?.()?.refreshIdentity().catch(()=>{}),q(t,200,On,{},{handler:es})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:es,cause:e})}finally{ln.release(Zo)}},{handler:es,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:es})});async function ns(e,t){if(TV(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=ot?.();if(!e){q(t,200,Ft,{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,Ft,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 rs=J(le,async(e,t,n)=>{let r=ot?.();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,re,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:`sync-trigger`})?ot?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function is(e,t){if(TV(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=ot?.();q(t,200,eee,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let as=J(S,async(e,t,n)=>{let r=ot?.();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,zi,{},{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)=>TV(e,t,{handler:`sync-resolve-conflict`})?ot?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function os(e,t){if(!TV(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!T){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let 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=DS(i),o=n.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=ot?.(),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=Qo({baseDir:T,timeout:{block:15e3}}),d=s?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(d){try{let e=async e=>{if(!e)return``;try{return await u.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},r=await e(d.theirsSha),a=await e(d.baseSha),o=DS(i),s=n.documents.get(o),c=``,l=!1,f=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);f=typeof e==`string`&&e.length>0?e:null;let t=zt?zt(o):null;t!==null&&(c=t,l=!0)}else{WI(L(T,i),T);try{c=V(L(T,i),`utf-8`),l=!0}catch{l=!1}}let p=l?r.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,Gi,{file:i,base:a,ours:c,theirs:r,kind:p,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})}return}async function f(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([f(1),f(2),f(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:``,d=null;if(l===`ytext`){let e=DS(i),t=n.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=zt?zt(e):null;t!==null&&!DG(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,Gi,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function ss(e,t){if(!TV(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=RU(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,Mn,{plan:await eW({projectDir:o,rootDir:r,packId:a})},{handler:`seed-plan`})}catch(e){if(e instanceof EU){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof DU){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 cs=J(bn,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,s=RU(a);if(typeof a==`string`&&a.length>0&&s===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,gee,{result:await YU(i,{projectDir:o,packId:s})},{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)=>TV(e,t,{handler:`seed-apply`})});async function ls(e,t){if(TV(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,Zi,{packs:BU()},{handler:`seed-packs`})}}let us=J(fr,async(e,t,n)=>{if(n.out!==void 0&&!SV(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,sr,await XF({...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)=>TV(e,t,{handler:`install-skill`})});async function ds(e,t){if(TV(e,t,{handler:`installed-agents`}))try{await vj(e,t,In.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:LS(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let fs=J(ke,async(e,t)=>{if(!Je){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,Jn,{tags:Je.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 ms(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(!Je){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=Je.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:Vn(e),matchingTags:t,snippet:null}));q(t,200,c,{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 hs(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(o),s=i===``?a:z(a,i);return s!==a&&!s.startsWith(`${a}${ul}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let gs=/^[A-Za-z0-9_-]+$/;function _s(e,t,n=`template`){return!e||!gs.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 vs(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}${ul}`))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 bs(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 xs=iB({GET:J(ke,async(e,t)=>{try{let n=hs(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await XO(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,eD.parse)(await Gl(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,qi,{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(jt,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=JR(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=hs(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=tk({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`&&(Si(e,bi(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Ci(`folder-config-put`))}q(t,200,w,{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 Ss(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&&US(o)?(KS(i,new GS({file:`${a}.md`}),r),!0):!1}function Cs(e,t,r){let i=n.documents.get(e);return i&&US(i)?(KS(r,new GS({file:`${e}.md`}),t),!0):!1}let ws=J(ke,rB(async(e,t)=>{let n=OO(z(o));q(t,200,Ir,{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}),Ts=e=>{let{body:t}=Fi(e);return{frontmatter:et(e)??{},body:t}},Es=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!_s(r,t,`template-get`))return;let i=hs(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=vs(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=_n(await Gl(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,qr,{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}),Ds=J(yi,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=JR(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 i=n.name;if(!_s(i,t,`template-put`))return;let a=hs(n.folder,t,`folder`,`template-put`);if(!a||Ss(a.folderRel,i,`template-put`,t))return;let o=jk({name:i,body:typeof n.body==`string`?n.body:``,frontmatter:bs(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(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`),c=!B(s),l=R(a.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=zs(a.folderRel,i),{agentId:d,agentName:f,colorSeed:p,clientName:m}=fi(n),h=await r.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Xx(h.dc.document,o.content,`agent`)},h.origin);let g=await ur(u);if(g?.kind===`failure`){pr(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){hr(t,`template-put`);return}Si(e,bi(`template`,a.folderRel,i),`${c?`template-create`:`template-edit`}: ${l}`),await Ci(`template-put`),q(t,200,aee,{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`}),Os=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!_s(r,t,`template-delete`))return;let i=hs(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=JR({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(Ss(i.folderRel,r,`template-delete`,t))return;await Fr([zs(i.folderRel,r)],`deleted-upstream`);let s=Nk({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&&(Si(o,bi(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Ci(`template-delete`)),q(t,200,mee,{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}),ks=iB({GET:Es,PUT:Ds,POST:J(En,async(e,t,n)=>{try{let e=JR(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(!_s(n.fromName,t,`template-move`)||!_s(n.toName,t,`template-move`))return;let r=hs(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=hs(n.toFolder,t,`folder`,`template-move`);if(!i||Ss(r.folderRel,n.fromName,`template-move`,t))return;await Fr([zs(r.folderRel,n.fromName)],`renamed`);let a=await Fk({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await kK(T,e,t);return n||OK(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=vs(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=ir(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=Mk({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:bs(n.frontmatter)});t.ok||(o=t.error)}}if(Si(e,bi(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Ci(`template-move`),Ye?.(`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,ei,{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:Os},{handler:`template`}),As=J(dee,async(e,t,i)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=JR(i,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let a=i.sourcePath;if(!MK(a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let s=Qn(a);if(_S(s)||vS(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`template-import`});return}let c=aK(o,`file`,s);if(!B(c)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${s}.`,{handler:`template-import`});return}let l=n.documents.get(s);if(i.deleteSource){let e=ot?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),r=l!==void 0&&US(l),i=n.has(a);if(r||i){KS(t,new GS({file:a}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await n.openDirectConnection(s);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=i.name;if(!d){let{basename:e}=oK(a);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!_s(d,t,`template-import`))return;let f=hs(i.targetFolder,t,`folder`,`template-import`);if(!f||Ss(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=Fi(u),h=Yi(p),g={};try{h.trim()&&(g=(0,eD.parse)(h))}catch{}let v=i.title||g?.title||eF(u,d),y=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,eD.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=jk({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),ee=!B(w),te=R(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),ne=zs(f.folderRel,d),{agentId:re,agentName:ie,colorSeed:ae,clientName:oe}=fi(i),se=await r.getSession(ne,re,{displayName:ie,colorSeed:ae,clientName:oe});se.dc.document.transact(()=>{Xx(se.dc.document,C.content,`agent`)},se.origin);let ce=await ur(ne);if(ce?.kind===`failure`){pr(t,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){hr(t,`template-import`);return}Si(e,bi(`template`,f.folderRel,d),`template-import: ${te}`),i.deleteSource&&(await Fr([s],`deleted-upstream`),Rt&&Rt.setDeleted(s),Eo(c),_?.({kind:`delete`,path:c,docName:s})),await Ci(`template-import`),Ye?.(`files`),q(t,200,yr,{path:te,created:ee,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 js(e,t,n){return!e||e.length>64||!Vi.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 Ms(e,t,n){let r=Ut.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 Ns=yt??Ll();function Ps(e){return z(e===`global`?Ns:o,`.ok`,`skills`)}let Fs=SF.project;function Is(){if(!T)return null;let e=[],t=null;for(let n of g){let r=St[n];if(!r)continue;let i=z(T,...r.split(`/`),Fs);B(z(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=z(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:R(T,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Ls(){let e=Is();if(!e)return null;let t;try{let{frontmatter:n}=Ts(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Fs,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Rs(e,t,n){return wF(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 zs(e,t){return`${i}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Bs(e){return e===`navigation`||e===`relevance`?e:void 0}function Vs(e,t){return R(t===`global`?Ns:o,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Hs(e){return e===`global`?Ns:T}async function Us(e,t){let n=await lM(e,t);return wI(t,e,g),n!==null}function Ws(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=Tl(e,{withFileTypes:!0})}catch(r){return F(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!Vi.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}=Ts(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:Vs(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Gs=J(ke,rB(async(e,t)=>{let n=Ws(Ps(`project`),`project`),r=Ws(Ps(`global`),`global`),i=T?oM(T).skills:{},a=oM(Ns).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=zoe(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Fs)?null:Ls();q(t,200,gn,{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}),Ks=O({managed:M().nullable(),importable:P().int().nonnegative()}),qs=()=>({managed:T?$F(T)?.manageEditorSkills??null:null,importable:T?Woe({projectDir:T,skillsRoot:Ps(`project`)}):0}),Js=iB({GET:J(ke,async(e,t)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Ks,qs(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:J(O({manageEditorSkills:M()}),async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await eI(T,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await BI({projectDir:T,skillsRoot:Ps(`project`)});e.adopted.length+e.collided.length>0&&Ye?.(`files`)}q(t,200,Ks,qs(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),Ys=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!js(r,t,`skill-get`))return;let i=Ms(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Fs&&i===`project`){let e=Is();if(e){let{frontmatter:n,body:a}=Ts(await Gl(e.skillMd,`utf-8`));q(t,200,it,{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:EI(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Ps(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}=Ts(await Gl(o,`utf-8`));q(t,200,it,{skill:{name:r,scope:i,path:Vs(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:EI(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}),Xs=J(aa,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-put`)||Rs(n.name,t,`skill-put`))return;let i=ck({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!i.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:i.error.code,cause:Error(i.error.message)});return}let a=Ps(n.scope),o=z(a,n.name,`SKILL.md`),s=!B(o),c=R(a,o).split(/[\\/]/).filter(Boolean).join(`/`),l=ji(n.scope,n.name);if(Cs(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=fi(n),m=await r.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Xx(m.dc.document,i.content,`agent`)},m.origin);let h=await ur(l);if(h?.kind===`failure`){pr(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){hr(t,`skill-put`);return}n.scope===`project`&&(Si(e,bi(`skill`,``,n.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Ci(`skill-put`)),Ye?.(`files`),q(t,200,b,{path:c,created:s,warnings:i.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`}),Zs=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!js(r,t,`skill-delete`)||Rs(r,t,`skill-delete`))return;let i=Ms(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Ps(i),o=n.searchParams,s=JR({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 Fr([ji(i,r)],`deleted-upstream`);let c=mk({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`&&(Si(s,bi(`skill`,``,r),`skill-delete: ${c.path}`),await Ci(`skill-delete`)),Ye?.(`files`));let l=Hs(i);l&&await Us(l,r),q(t,200,ut,{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}),Qs=iB({GET:Ys,PUT:Xs,POST:J(qe,async(e,t,n)=>{try{let e=JR(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(!js(n.fromName,t,`skill-move`)||!js(n.toName,t,`skill-move`)||Rs(n.fromName,t,`skill-move`)||Rs(n.toName,t,`skill-move`))return;let r=Ps(n.scope);await Fr([ji(n.scope,n.fromName)],`renamed`);let i=await hk({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await kK(T,e,t);return n||OK(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=Ts(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=lk({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{rc(r,n.fromName,n.toName)}catch(e){F(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let f=Vs(z(r,n.fromName),n.scope),p=Vs(z(r,n.toName),n.scope);n.scope===`project`&&(Si(e,bi(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Ci(`skill-move`));let m=Hs(n.scope);if(m){let e=await lM(m,n.fromName);if(e){let t=gI(e.hosts);wI(n.fromName,m,t);let i=CI(z(r,n.toName),n.toName,m,t);await cM(m,n.toName,{...e,hosts:i})}}if(Ye?.(`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,Et,{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:Zs},{handler:`skill`});function $s(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 ec(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function tc(e,t){let n=t.replace(/\.md$/i,``);return`${Rn(e).replace(/\/SKILL$/,``)}/${n}`}function nc(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of Tl(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 rc(e,t,n){if(!We)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{We.deleteDocument(e),Je?.deleteDocument(e);return}We.renameDocument(e,t,r),Je?.renameDocument(e,t,r)};r(Rn(t),Rn(n),z(e,n,`SKILL.md`));for(let i of nc(e,n))r(tc(t,i),tc(n,i),z(e,n,i));Ye?.(`backlinks`),Ye?.(`graph`)}let ic=iB({GET:J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!js(r,t,`skill-file-get`))return;let i=Ms(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Fs&&i===`project`?Is():null,s=o&&a===`SKILL.md`?`reference`:$s(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(Ps(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${ul}`)){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?ve.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 Gl(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,m,{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(Dr,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-file-put`)||Rs(n.name,t,`skill-file-put`))return;let i=$s(n.path);if(i===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 a=Ps(n.scope);if(!B(z(a,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=ec(n.scope,i,o),c;if(s){let e=tc(n.name,o);if(Cs(e,`skill-file-put`,t))return;if(c=!B(z(a,n.name,o)),c&&dk(z(a,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:i,agentName:s,colorSeed:l,clientName:u}=fi(n),d=await r.getSession(e,i,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{Xx(d.dc.document,n.content,`agent`)},d.origin);let f=await ur(e);if(f?.kind===`failure`){pr(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){hr(t,`skill-file-put`);return}}else{let e=fk({skillsRoot:a,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`&&(Si(e,bi(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${o}`),await Ci(`skill-file-put`)),Ye?.(`files`),q(t,200,$e,{path:o,created:c,kind:i,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(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!js(r,t,`skill-file-delete`)||Rs(r,t,`skill-file-delete`))return;let i=Ms(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=$s(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=JR({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=Ps(i);ec(i,o,a)&&await Fr([tc(r,a)],`deleted-upstream`);let l=pk({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`&&(Si(s,bi(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Ci(`skill-file-delete`)),l.existed&&Ye?.(`files`),q(t,200,Nr,{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`}),ac=J(mt,async(e,t,n)=>{try{let e=Ps(n.scope);if(!js(n.name,t,`skill-install`)||Rs(n.name,t,`skill-install`))return;if(n.scope===`project`&&!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Hs(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=yI(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?g.filter(e=>n.targets?.some(t=>t===e)):[...g]:n.targets===void 0?bI(r,UI(r)??void 0):g.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=gI(oM(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&wI(n.name,r,l);let u=CI(i,n.name,r,o);u.length===0?await lM(r,n.name):await cM(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),Ye?.(`files`),q(t,200,je,{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`}),oc=J(lee,async(e,t,n)=>{try{if(!js(n.name,t,`skill-uninstall`)||Rs(n.name,t,`skill-uninstall`))return;let e=Hs(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 Us(e,n.name);Ye?.(`files`),q(t,200,Le,{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`}),sc=iB({GET:J(ke,rB(async(e,t)=>{let n=T?UI(T):null;q(t,200,Zt,{targets:bI(T??``,n??void 0),configured:n!==null},{handler:`skill-targets-get`})},{handler:`skill-targets-get`,title:`Failed to read skill targets.`}),{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(Se,rB(async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let r=n.targets,i=new Set(r),a=bI(T,UI(T)??void 0),o=Ps(`project`);await Joe(T,r);let{reprojected:s,bundleHosts:c}=await Koe({projectDir:T,skillsRoot:o,targets:r});Ye?.(`files`),q(t,200,He,{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`}),cc=J(iee,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-restore`)||Rs(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=Ce?.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 sW({shadow:r,contentDir:o,contentRoot:Ue??`.`,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=[],s=yI(z(o,`.ok`,`skills`,n.name),n.name);s.ok||a.push(`Restored, but the skill no longer validates: ${s.errors.join(` `)}`),a.push("Run `install` to push the restored version to your editors."),Si(e,bi(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Ci(`skill-restore`),Ye?.(`files`),q(t,200,Oe,{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`}),lc=J(un,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-update`)||Rs(n.name,t,`skill-update`))return;if(!DI(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 i=Loe(n.name);if(i===null||i.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 a=z(Ps(`project`),n.name,`SKILL.md`);if(!B(a)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let o;try{o=OI(V(a,`utf-8`))}catch{}let s,c=Ce?.current;if(c)try{let e=Re?.()??`main`;s=(await BR(c,Ue??`.`,[TR],e,`Before updating ${n.name} (${o??`unversioned`} → ${i.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=ji(`project`,n.name);if(Cs(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=fi(n),m=await r.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Xx(m.dc.document,i.content,`agent`)},m.origin);let h=await ur(l);if(h?.kind===`failure`){pr(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){hr(t,`skill-update`);return}Si(e,bi(`skill`,``,n.name),`skill-pack-update: ${n.name} (${o??`unversioned`} → ${i.version})`),await Ci(`skill-update`),Ye?.(`files`),q(t,200,rn,{name:n.name,version:i.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 uc(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])=>Mt({kind:`folder`,path:e,modifiedTs:t}))}function dc(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 fc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function pc(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 mc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function hc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function gc(e,t,n,r){let i=r.documents.filter(e=>!Bn(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Gt?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Gt.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Gt.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Kt?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Gt.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function _c(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`?dc(e.document.content,t):void 0}}async function vc(e){let t=performance.now();if(Dc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await Oc(),i=await gc(e.query,e.intent,e.semanticParam,n),a=oe(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>_c(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},xA({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 yc(){let e=Ps(`project`);if(!B(e))return[];let t;try{t=Tl(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!Vi.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=jl(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function bc(){let e=[];for(let t of yc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=Ts(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(Mt({kind:`page`,path:ji(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function xc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Sc=new Map;async function Cc(){let e=[],t=[],n=new Set;for(let[r,i]of h()){if(_S(r)||vS(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(Mt({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=xc(i),o=Sc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await Gl(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=eF(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=Mt({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Sc.set(r,{key:a,doc:u}),e.push(u)}for(let e of Sc.keys())n.has(e)||Sc.delete(e);let r=WG(),i=t,a=!1;return t.length>r&&(a=!0,i=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,r),F(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),yG().add(1)),{documents:[...e,...bc(),...i,...uc([...e,...i])],truncated:a}}function wc(){return yc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Tc(){return te?`gen:${te()}|skills${wc()}`:`${[...h()].filter(([e])=>!_S(e)&&!vS(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${xc(t)}`).join(``)}|skills${wc()}`}let Ec=Nt===void 0;Nt?.then(()=>{Ec=!0},e=>{Ec=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Dc(){return!Ec}async function Oc(){let e=`${o}${T??``}`,t=Tc(),n=AK.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 Cc();if(!e)return xG().add(1,{mode:`cold`}),{corpus:vee(t),truncated:n};let a=ee(e,t);if(a.rebuilt){xG().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;F(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else xG().add(1,{mode:`incremental`}),F(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();AK.set(e,{fingerprint:t,pending:a});try{let n=await a;return AK.get(e)?.pending===a&&AK.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw AK.get(e)?.pending===a&&AK.delete(e),t}}function kc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Oc().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}kc();let Ac=iB({GET:J(ke,rB(async(e,t)=>{let n=See(e),r=n.get(`limit`),i=n.get(`query`)??``,a=fc(n.get(`intent`)),o=Bs(n.get(`ranking`)),s=pc(n.get(`scope`)??n.get(`scopes`)),c=mc(n.get(`semantic`)),l=hc(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,de,await vc({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(Lt,rB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=fc(n.intent),a=Bs(n.ranking),o=pc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=mc(n.semantic),l=hc(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,de,await vc({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`}),jc=J(ke,rB(async(e,t)=>{q(t,200,ge,{...await GF(Ll())},{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)=>TV(e,t,{handler:`skill-install-state`})});async function Mc(e,t){if(TV(e,t,{handler:`handoff`}))try{await Wj(e,t,{contentDir:o,platform:process.platform,isSchemeRegistered:In.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:LS(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Nc(e,t){if(TV(e,t,{handler:`spawn-cursor`}))try{await Pj(e,t,{contentDir:o,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:LS(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Pc=J(a,async(e,t,n)=>{try{if(!T){rF(`no-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`no-remote`},{handler:nF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!kae(e,n.kind)){rF(`invalid-path`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`invalid-path`},{handler:nF});return}let r=Pae(T);if(r===null){if(sF(T).kind===`no-remote`){rF(`no-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`no-remote`},{handler:nF});return}rF(`detached-head`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`detached-head`},{handler:nF});return}let i=sF(T);if(i.kind===`no-remote`){rF(`no-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`no-remote`},{handler:nF});return}if(i.kind===`non-github`){rF(`non-github-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`non-github-remote`},{handler:nF});return}if(!zae(T,r)){rF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,Kn,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:nF});return}let a=SK(T,o);if(a===null)throw Error(`content dir is not contained within the project dir`);let s=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&s&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=Aae(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=jae(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Nh(c)}`,u=await Mae(T,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);rF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,Kn,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:nF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:nF,cause:e})}},{handler:nF,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:nF})}),Fc=J(ke,async(e,t)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Uz});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(!Oi(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:Uz});return}if(!Vz(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:Uz});return}q(t,200,en,await Hz(T,r,i,a),{handler:Uz})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Uz,cause:e})}},{handler:Uz,method:`GET`,skipBodyParse:!0}),Ic=J(wn,async(e,t,n)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:xF});return}if(!Vz(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:xF});return}let e=SK(T,o);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,Qr,await eoe(T,n.branch,r,n.kind),{handler:xF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xF,cause:e})}},{handler:xF,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:xF})}),Lc=J(pn,async(e,t,n)=>{if(JR(n,ht).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:Jz});return}if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Jz});return}try{q(t,200,_t,await $o(()=>Xz(T,n.branch,{fastForward:n.fastForward===!0})),{handler:Jz})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Jz,cause:e})}},{handler:Jz,method:`POST`});async function Rc(e){let[t,...n]=st,r=[...n,...e];return await new Promise((e,n)=>{let i=tl(t,r,uj({...Ya,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},fF),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 ${fF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=vF(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 zc=J(ke,async(e,t)=>{if(!ln.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:lF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Rc([`share`,`owners`,`--json`]),n=Bae(hF(e));_F(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,Gr,n,{handler:lF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lF,cause:e})}finally{ln.release(`/api/share/publish/owners`)}},{handler:lF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>TV(e,t,{handler:lF})}),Bc=J(ke,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!mF(r)||!pF(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:uF});return}if(!ln.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:uF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Rc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Vae(hF(e));_F(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,pee,n,{handler:uF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:uF,cause:e})}finally{ln.release(`/api/share/publish/name-check`)}},{handler:uF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>TV(e,t,{handler:uF})}),Vc=J(uee,async(e,t,n)=>{if(!T){_F(`publish-create`,`no-project`),q(t,200,_r,{ok:!1,error:`no-project`},{handler:dF});return}if(!mF(n.owner)||!pF(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:dF});return}if(!ln.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:dF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,T,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Rc(e),i=Wae(hF(r));_F(`publish-create`,i.ok?`ok`:i.error),i.ok&&ot?.()?.refreshRemote().catch(()=>{}),q(t,200,_r,i,{handler:dF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:dF,cause:e})}finally{ln.release(`/api/share/publish`)}},{handler:dF,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:dF})}),Hc=J(Ae,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,Ke,{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)=>TV(e,t,{handler:`client-logs`})}),Uc=T?AD(T):null;async function Wc(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:Uc?ps(Uc)?.port??0:0,singleFile:an};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,tee,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 Gc=`local-op-embeddings-set-key`,Kc=`local-op-embeddings-clear-key`,qc=`/api/local-op/embeddings`;function Jc(){let e=Jt?.();return{projectDir:T??o,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Yc=J(nr,async(e,t,n)=>{if(!ln.tryAcquire(qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Gc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Jc();await new qA(qt).setForProject(e,r,n.key),Gt?.reloadCredential(),q(t,200,Wn,{keyPresent:!0},{handler:Gc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Gc,cause:e})}finally{ln.release(qc)}},{handler:Gc,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Gc})}),Xc=J(ke,async(e,t)=>{if(!ln.tryAcquire(qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Kc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Jc();await new qA(qt).clearForProject(e,n),Gt?.reloadCredential(),q(t,200,Wn,{keyPresent:!1},{handler:Kc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Kc,cause:e})}finally{ln.release(qc)}},{handler:Kc,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Kc})}),Zc=`local-op-embeddings-test`,Qc=`/api/local-op/embeddings/test`,$c=J(ke,async(e,t)=>{if(!ln.tryAcquire(Qc)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Zc,extraHeaders:{"Retry-After":`5`}});return}try{let e=Jt?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await IA(new qA(qt),T??o,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await RA({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,oi,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Zc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Zc,cause:e})}finally{ln.release(Qc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Zc})}),el=J(ke,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Gt){let t=Gt.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Jt?.()?.baseUrl??`https://api.openai.com/v1`,s=await IA(new qA(qt),T??o,a),c=s.apiKey!==null,u=!c&&s.keyless,d=c?s.source:null,f=s.apiKey&&s.apiKey.length>=8?s.apiKey.slice(-4):null,p=0;for(let[e]of l())!_S(e)&&!vS(e)&&!Bn(e)&&(p+=1);q(t,200,ae,{enabled:e,keyPresent:c,keyNotRequired:u,keySource:d,keyHint:f,ready:n,capable:r,embedded:i,total:p},{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 nl(e,t){let n=Qt?.()??Pt;try{let r=await $r(e,MP(o,n,{docName:t,projectDir:T??o,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=$t?.()??`warning`;if(We&&a!==`off`&&!SS(t)){We.updateDocumentFromMarkdown(t,e);let r=GP({projectDir:T??o,contentDir:o,baseConfig:n,backlinkIndex:We,linksValidation:a,admittedDocNames:br,docFilePathFor:e=>pK(o,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:pK(o,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function rl(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=FP({projectDir:T??o,contentDir:o});return RN(t.schemas,n)}let al=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!MK(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Qt?.()??Pt,i=[],a=kP(o,n??void 0,e=>i.push(e)),s=jP(T??o,AP(r,a),e=>i.push(e));n===null&&i.push(...rl(s)),q(t,200,Ii,{effective:s,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}),cl=J(kt,async(e,t,n)=>{let r;try{r=WP(z(o),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}Ye?.(`lint-config`);try{let e=Qt?.()??Pt,n=[],r=kP(o,void 0,e=>n.push(e)),i=jP(T??o,AP(e,r),e=>n.push(e));n.push(...rl(i)),q(t,200,Ii,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),ll=J(dr,async(e,t,n)=>{let r;try{let e=z(T??o),t=n.parentPath??[];r=n.delete?pae(e,n.file):n.field!==void 0&&n.removeField?dae(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?fae(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?lae(e,n.file,n.field,n.constraint,t):uae(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Ye?.(`files`),Ye?.(`lint-config`);try{let e=Qt?.()??Pt,n=[],r=kP(o,void 0,e=>n.push(e)),i=jP(T??o,AP(e,r),e=>n.push(e));n.push(...rl(i)),q(t,200,Ii,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),dl=J(ke,async(e,t)=>{try{let e=z(T??o),{schemas:n,truncated:r}=IN(e),i=new Set(n),a=!1;if(Tt!==void 0){let t=XG({contentDir:o,contentFilter:Tt,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&$n(a)){let t=R(e,z(o,a));!t.startsWith(`..`)&&!sl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let s=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,or,{schemas:s.slice(0,500),truncated:r||a||s.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),fl=e=>{let t=e.replace(/\.(md|mdx)$/i,``),r=n.documents.get(t);return r===void 0?null:r.getText(`source`).toString()},pl=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!MK(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=pK(o,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Qt?.()??Pt,a=[],s=await NP({projectDir:T??o,contentDir:o,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:fl});q(t,200,Xi,a.length>0?{...s,warnings:a}:s,{handler:`lint`})}catch(e){if(e instanceof KM){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}),ml=J(ke,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&&!QG(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Qt?.()??Pt;q(t,200,yn,await IP({projectDir:T??o,contentDir:o,baseConfig:i,targetPath:r,liveSourceFor:fl}),{handler:`lint-audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),hl=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!QG(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),s=a===null||a===``?void 0:a;if(s!==void 0){if(i!==void 0||!QG(s)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=pK(o,s)??`${s}.md`}let c=Qt?.()??Pt;q(t,200,x,await gae(GP({projectDir:T??o,contentDir:o,baseConfig:c,liveSourceFor:fl,backlinkIndex:We??null,linksValidation:$t?.(),admittedDocNames:br,docFilePathFor:e=>pK(o,e)}),{targetPath:i}),{handler:`audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),gl=J(jn,async(t,n,i)=>{try{let t=rK(i.docName,n,`lint-fix`);if(t===null)return;let a=Qn(t),s=JR(i,ht);if(s.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=s.kind===`anonymous`?`principal-anonymous`:s.writerId,l=s.kind===`anonymous`?`Anonymous`:s.displayName,u=s.kind===`anonymous`?c:s.colorSeed,d=s.kind===`agent`?s.clientName:void 0;if(_S(a)||vS(a)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`lint-fix`});return}let f=pK(o,a);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}iK(z(o,f),o);let p=Qt?.()??Pt,{stored:m}=hi(s.summary),h=await r.getSession(a,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await PP({projectDir:T??o,contentDir:o,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=zn(d),n=Fn[t]??Pr(u??c);tt?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:a,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{AC(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0)},h.origin),s.kind!==`anonymous`&&Wk(a,c,l,u,void 0,s.kind===`agent`?pi({clientName:s.clientName,clientVersion:s.clientVersion,label:s.label}):s.actor,m)}finally{tt?.touchMode(c,`idle`)}let t=await ur(a);if(t?.kind===`failure`){pr(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){hr(n,`lint-fix`);return}lr(a,`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,Wi,{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 KM){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof GS){KS(n,e,`lint-fix`);return}if(e instanceof XS){QS(n,e,`lint-fix`);return}if(e instanceof IC){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`}),vl=`link-preview`,yl=new dV({cacheDir:an?null:z(T??o,`.ok`,`local`,`link-previews`)}),xl=null,Sl=()=>(xl??=yl.init(),xl),Cl=on??nV;async function wl(e){let t=await Cl(e);return t.ok?{ok:!0,metadata:await sV({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Cl})}:{ok:!1,reason:t.reason}}let El=()=>{try{return sn?.()===!0}catch{return!1}},Ol={"/api/config":Wc,"/api/asset":Pa,"/api/asset-text":Fa,"/api/document":Ni,"/api/documents":Pi,"/api/backlinks":Li,"/api/backlink-counts":Ri,"/api/link-preview":J(Ki,async(e,t,n)=>{try{if(!El()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,At,{ok:!1,reason:`disabled`},{handler:vl});return}await Sl();let e=!1,r=await yl.load(n.url,()=>(e=!0,wl(n.url)));yl.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,At,i,{handler:vl})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vl,cause:e})}},{handler:vl,method:`POST`,preBodyGate:(e,t)=>{let n=mV({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:vl}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:vl}),!1)}}),"/api/forward-links":Hi,"/api/link-graph":Ui,"/api/dead-links":ea,"/api/orphans":Ji,"/api/hubs":$i,"/api/tags":fs,"/api/pages":Ua,"/api/folder-config":xs,"/api/template":ks,"/api/template/import":As,"/api/templates":ws,"/api/skill":Qs,"/api/skill-file":ic,"/api/skills":Gs,"/api/skills/management":Js,"/api/skill/install":ac,"/api/skill/uninstall":oc,"/api/skill/restore":cc,"/api/skill/update":lc,"/api/skill-targets":sc,"/api/search":Ac,"/api/semantic-status":el,"/api/lint/config":al,"/api/lint/markdownlint-config":cl,"/api/lint/frontmatter-schema":ll,"/api/lint/frontmatter-schemas":dl,"/api/lint":pl,"/api/lint/audit":ml,"/api/lint/fix":gl,"/api/audit":hl,"/api/suggest-links":Wa,"/api/page-headings":za,"/api/create-page":k,"/api/create-folder":La,"/api/duplicate-path":Ra,"/api/rename-path":Ba,"/api/delete-path":Va,"/api/trash/cleanup":Ha,"/api/upload":j,"/api/agent-write":wi,"/api/agent-write-md":Ti,"/api/agent-write-batch":Di,"/api/frontmatter-patch":ki,"/api/agent-patch":ta,"/api/agent-undo":oa,"/api/agent-activity":sa,"/api/agent-burst-diff":la,"/api/save-version":ga,"/api/history":_a,"/api/rollback":ya,"/api/metrics/reconciliation":xa,"/api/metrics/parse-health":Sa,"/api/metrics/agent-presence":Aa,"/api/metrics/agent-effects":ja,"/api/metrics/watcher-recent":Ma,"/api/__embed-detect":E,"/api/server-info":Ca,"/api/acp/catalog":Da,"/api/share/construct-url":Pc,"/api/share/target-status":Ic,"/api/git/branch-info":Fc,"/api/git/checkout":Lc,"/api/share/publish/owners":zc,"/api/share/publish/name-check":Bc,"/api/share/publish":Vc,"/api/principal":ka,"/api/rescue":Ia,"/api/workspace":Na,"/api/sync/status":ns,"/api/sync/trigger":rs,"/api/sync/conflicts":is,"/api/sync/conflict-content":os,"/api/sync/resolve-conflict":as,"/api/local-op/clone":Qa,"/api/local-op/ok-init":no,"/api/local-op/auth/login":To,"/api/local-op/auth/status":zo,"/api/local-op/auth/pat":Ho,"/api/local-op/auth/gh-login":ko,"/api/local-op/auth/cancel":Io,"/api/local-op/auth/repos":Go,"/api/local-op/auth/signout":Yo,"/api/local-op/auth/set-identity":ts,"/api/local-op/embeddings/set-key":Yc,"/api/local-op/embeddings/clear-key":Xc,"/api/local-op/embeddings/test":$c,"/api/installed-agents":ds,"/api/spawn-cursor":Nc,"/api/handoff":Mc,"/api/install-skill":us,"/api/skill/install-state":jc,"/api/seed/plan":ss,"/api/seed/apply":cs,"/api/seed/packs":ls,"/api/client-logs":Hc};_e&&(Ol[`/api/test-reset`]=da,Ol[`/api/test-flush-git`]=ua,Ol[`/api/test-rescan-backlinks`]=pa,Ol[`/api/test-rescan-files`]=ma);let kl=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Al=[`/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};tA({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`:Ol[n]||(a=`/api/*`);let o=n.startsWith(`/api/`)?wre(e):void 0;if(o!==void 0&&(Tre(e,o),typeof t.setHeader==`function`&&t.setHeader(FS,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&&!sD(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, ${FS}, ${tr.protocol}, ${tr.runtime}, ${tr.kind}`),t.setHeader(`Access-Control-Expose-Headers`,FS)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(kl.has(n)||Al.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!$V(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!eH(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(an&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!$V(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!eH(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=ao.extract(co.active(),e.headers),c=So(),l=Date.now();await co.with(s,()=>c.startActiveSpan(`HTTP ${i} ${a}`,{kind:oo.SERVER,attributes:{[Ko]:i,[Wo]:a,[xee]:n,[bee]:`http`,[yee]:e.headers[`user-agent`]??``,"ok.request.id":o}},async r=>{try{let a=Ol[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 va(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await ms(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(Xo,s),s>=500&&r.setStatus({code:io.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:io.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;oG().record(e,{[Ko]:i,[Wo]:a,[Xo]:t.statusCode})}}))}}}function FK(e){let t=e?.code;return typeof t==`string`?t:void 0}function IK(e){let t;try{t=Tl(e.contentDir,{withFileTypes:!0})}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&ES(n.name,ba)&&e.basenameIndex.add(n.name)}async function LK(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Kl(i,{withFileTypes:!0})}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=cD(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Wl(a)}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await ql(a)}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!lD(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Jl(i)}catch(t){let n=FK(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()&&ES(a,ca)&&!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()&&ES(a,ca)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const RK=O({principalId:A().optional(),tabSessionId:A().optional(),expectedServerInstanceId:A().optional(),expectedBranch:A().optional(),expectedDocLineageEpoch:A().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:A().optional(),clientKind:A().optional()}).loose(),zK=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function BK(e){return zK.includes(e)}function VK(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function HK(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!BK(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 UK=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=VK(e,this.payload)}};function WK(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=RK.safeParse(t);return n.success?n.data:void 0}var GK=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const KK=F(`conflict-storage`);var qK=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(AD(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){KK.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){KK.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||bl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Nl(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return KK.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-maG17s4k.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!lD(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);WI(r,t),Bo(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),KK.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await bF(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){KK.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}),KK.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=z(this.projectDir),a=z(i,e.file);if(!lD(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(WI(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-maG17s4k.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);WI(a,i),Bo(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);Bo(a,n,`utf-8`);break;case`delete`:B(a)&&Eo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function JK(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 YK(e,t){let n=AD(e);try{bl(n,{recursive:!0}),Nl(L(n,fe),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=qo(e);bl(I(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};Nl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const XK=new Map;let ZK=!1;function QK(e,t){try{let n=JK(e,t);for(let e of XK.keys())YK(e,n)}catch{}}function $K(e){XK.set(e,(XK.get(e)??0)+1),ZK||(ZK=!0,process.on(`uncaughtExceptionMonitor`,QK));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=XK.get(e)??0;n<=1?XK.delete(e):XK.set(e,n-1)}}}function eq(e){let t=e.scheduler??h,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 tq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nq(e){if(!B(e))return{};let t;try{t=(0,eD.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(!tq(t))return{};let n=t.telemetry;if(!tq(n))return{};let r=n.localSink;return tq(r)?r:{}}function rq(e){return typeof e==`boolean`?e:void 0}function iq(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function aq(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function oq(e){if(tq(e))return iq(e.maxBytes)}function sq(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=nq(_o(`project`,e.projectDir)),n=nq(_o(`project-local`,e.projectDir));if((rq(n.enabled)??rq(t.enabled)??!0)===!1)return null;let r=oq(n.spans)??oq(t.spans)??52428800,i=oq(n.logs)??oq(t.logs)??26214400,a=aq(n.attributeDenylist)??aq(t.attributeDenylist)??Ta;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var cq;(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})(cq||={});var lq;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(lq||={});const uq=cq.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),dq=e=>{switch(typeof e){case`undefined`:return uq.undefined;case`string`:return uq.string;case`number`:return Number.isNaN(e)?uq.nan:uq.number;case`boolean`:return uq.boolean;case`function`:return uq.function;case`bigint`:return uq.bigint;case`symbol`:return uq.symbol;case`object`:return Array.isArray(e)?uq.array:e===null?uq.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?uq.promise:typeof Map<`u`&&e instanceof Map?uq.map:typeof Set<`u`&&e instanceof Set?uq.set:typeof Date<`u`&&e instanceof Date?uq.date:uq.object;default:return uq.unknown}},X=cq.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 fq=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,cq.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()}};fq.create=e=>new fq(e);const pq=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===uq.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,cq.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${cq.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${cq.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${cq.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}"`:cq.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,cq.assertNever(e)}return{message:n}};let mq=pq;function hq(){return mq}const gq=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 _q(e,t){let n=hq(),r=gq({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===pq?void 0:pq].filter(e=>!!e)});e.common.issues.push(r)}var vq=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 yq;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 yq;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 yq=Object.freeze({status:`aborted`}),bq=e=>({status:`dirty`,value:e}),xq=e=>({status:`valid`,value:e}),Sq=e=>e.status===`aborted`,Cq=e=>e.status===`dirty`,wq=e=>e.status===`valid`,Tq=e=>typeof Promise<`u`&&e instanceof Promise;var Eq;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(Eq||={});var Dq=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const Oq=(e,t)=>{if(wq(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 fq(e.common.issues);return this._error=t,this._error}}};function kq(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 Aq=class{get description(){return this._def.description}_getType(e){return dq(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:dq(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vq,ctx:{common:e.parent.common,data:e.data,parsedType:dq(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Tq(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:dq(e)};return Oq(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:dq(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return wq(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=>wq(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:dq(e)},r=this._parse({data:e,path:n.path,parent:n});return Oq(n,await(Tq(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 MJ({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 NJ.create(this,this._def)}nullable(){return PJ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pJ.create(this)}promise(){return jJ.create(this,this._def)}or(e){return gJ.create([this,e],this._def)}and(e){return bJ.create(this,e,this._def)}transform(e){return new MJ({...kq(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new FJ({...kq(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new RJ({typeName:Z.ZodBranded,type:this,...kq(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new IJ({...kq(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 zJ.create(this,e)}readonly(){return BJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const jq=/^c[^\s-]{8,}$/i,Mq=/^[0-9a-z]+$/,Nq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Pq=/^[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,Fq=/^[a-z0-9_-]{21}$/i,Iq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Lq=/^[-+]?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)?)??$/,Rq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let zq;const Bq=/^(?:(?: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])$/,Vq=/^(?:(?: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])$/,Hq=/^(([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]))$/,Uq=/^(([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])$/,Wq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kq=`((\\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])))`,qq=RegExp(`^${Kq}$`);function Jq(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 Yq(e){return RegExp(`^${Jq(e)}$`)}function Xq(e){let t=`${Kq}T${Jq(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Zq(e,t){return!!((t===`v4`||!t)&&Bq.test(e)||(t===`v6`||!t)&&Hq.test(e))}function Qq(e,t){if(!Iq.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 $q(e,t){return!!((t===`v4`||!t)&&Vq.test(e)||(t===`v6`||!t)&&Uq.test(e))}var eJ=class e extends Aq{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==uq.string){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.string,received:t.parsedType}),yq}let t=new vq,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),_q(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),_q(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?_q(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&_q(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Rq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)zq||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),zq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Pq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Fq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)jq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Mq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Nq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(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),_q(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),_q(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),_q(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),_q(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),_q(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Xq(r).test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?qq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Yq(r).test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Lq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Zq(e.data,r.version)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Qq(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?$q(e.data,r.version)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Wq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Gq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):cq.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,...Eq.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...Eq.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...Eq.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...Eq.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...Eq.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...Eq.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...Eq.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...Eq.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...Eq.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...Eq.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...Eq.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...Eq.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...Eq.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...Eq.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,...Eq.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,...Eq.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...Eq.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...Eq.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...Eq.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...Eq.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...Eq.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...Eq.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...Eq.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...Eq.errToObj(t)})}nonempty(e){return this.min(1,Eq.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}};eJ.create=e=>new eJ({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...kq(e)});function tJ(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 nJ=class e extends Aq{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)!==uq.number){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.number,received:t.parsedType}),yq}let t,n=new vq;for(let r of this._def.checks)r.kind===`int`?cq.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),_q(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),_q(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),_q(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?tJ(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),_q(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),_q(t,{code:X.not_finite,message:r.message}),n.dirty()):cq.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,Eq.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Eq.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Eq.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Eq.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Eq.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:Eq.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:Eq.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:Eq.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:Eq.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:Eq.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Eq.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:Eq.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:Eq.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:Eq.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`&&cq.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)}};nJ.create=e=>new nJ({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...kq(e)});var rJ=class e extends Aq{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)!==uq.bigint)return this._getInvalidInput(e);let t,n=new vq;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),_q(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),_q(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),_q(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):cq.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.bigint,received:t.parsedType}),yq}gte(e,t){return this.setLimit(`min`,e,!0,Eq.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Eq.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Eq.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Eq.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Eq.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:Eq.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:Eq.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:Eq.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:Eq.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Eq.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}};rJ.create=e=>new rJ({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...kq(e)});var iJ=class extends Aq{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==uq.boolean){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.boolean,received:t.parsedType}),yq}return xq(e.data)}};iJ.create=e=>new iJ({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...kq(e)});var aJ=class e extends Aq{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==uq.date){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.date,received:t.parsedType}),yq}if(Number.isNaN(e.data.getTime()))return _q(this._getOrReturnCtx(e),{code:X.invalid_date}),yq;let t=new vq,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),_q(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),_q(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):cq.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:Eq.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:Eq.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)}};aJ.create=e=>new aJ({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...kq(e)});var oJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.symbol){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.symbol,received:t.parsedType}),yq}return xq(e.data)}};oJ.create=e=>new oJ({typeName:Z.ZodSymbol,...kq(e)});var sJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.undefined){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.undefined,received:t.parsedType}),yq}return xq(e.data)}};sJ.create=e=>new sJ({typeName:Z.ZodUndefined,...kq(e)});var cJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.null){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.null,received:t.parsedType}),yq}return xq(e.data)}};cJ.create=e=>new cJ({typeName:Z.ZodNull,...kq(e)});var lJ=class extends Aq{constructor(){super(...arguments),this._any=!0}_parse(e){return xq(e.data)}};lJ.create=e=>new lJ({typeName:Z.ZodAny,...kq(e)});var uJ=class extends Aq{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xq(e.data)}};uJ.create=e=>new uJ({typeName:Z.ZodUnknown,...kq(e)});var dJ=class extends Aq{_parse(e){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.never,received:t.parsedType}),yq}};dJ.create=e=>new dJ({typeName:Z.ZodNever,...kq(e)});var fJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.undefined){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.void,received:t.parsedType}),yq}return xq(e.data)}};fJ.create=e=>new fJ({typeName:Z.ZodVoid,...kq(e)});var pJ=class e extends Aq{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==uq.array)return _q(t,{code:X.invalid_type,expected:uq.array,received:t.parsedType}),yq;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(_q(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&&(_q(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&&(_q(t,{code:X.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Dq(t,e,t.path,n)))).then(e=>vq.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Dq(t,e,t.path,n)));return vq.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:Eq.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:Eq.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:Eq.toString(n)}})}nonempty(e){return this.min(1,e)}};pJ.create=(e,t)=>new pJ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...kq(t)});function mJ(e){if(e instanceof hJ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=NJ.create(mJ(r))}return new hJ({...e._def,shape:()=>t})}else if(e instanceof pJ)return new pJ({...e._def,type:mJ(e.element)});else if(e instanceof NJ)return NJ.create(mJ(e.unwrap()));else if(e instanceof PJ)return PJ.create(mJ(e.unwrap()));else if(e instanceof xJ)return xJ.create(e.items.map(e=>mJ(e)));else return e}var hJ=class e extends Aq{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=cq.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==uq.object){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.object,received:t.parsedType}),yq}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof dJ&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Dq(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof dJ){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&&(_q(n,{code:X.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Dq(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>vq.mergeObjectSync(t,e)):vq.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return Eq.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:Eq.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 cq.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 cq.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return mJ(this)}partial(t){let n={};for(let e of cq.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 cq.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof NJ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return OJ(cq.objectKeys(this.shape))}};hJ.create=(e,t)=>new hJ({shape:()=>e,unknownKeys:`strip`,catchall:dJ.create(),typeName:Z.ZodObject,...kq(t)}),hJ.strictCreate=(e,t)=>new hJ({shape:()=>e,unknownKeys:`strict`,catchall:dJ.create(),typeName:Z.ZodObject,...kq(t)}),hJ.lazycreate=(e,t)=>new hJ({shape:e,unknownKeys:`strip`,catchall:dJ.create(),typeName:Z.ZodObject,...kq(t)});var gJ=class extends Aq{_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 fq(e.ctx.common.issues));return _q(t,{code:X.invalid_union,unionErrors:n}),yq}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 fq(e));return _q(t,{code:X.invalid_union,unionErrors:i}),yq}}get options(){return this._def.options}};gJ.create=(e,t)=>new gJ({options:e,typeName:Z.ZodUnion,...kq(t)});const _J=e=>e instanceof EJ?_J(e.schema):e instanceof MJ?_J(e.innerType()):e instanceof DJ?[e.value]:e instanceof kJ?e.options:e instanceof AJ?cq.objectValues(e.enum):e instanceof FJ?_J(e._def.innerType):e instanceof sJ?[void 0]:e instanceof cJ?[null]:e instanceof NJ?[void 0,..._J(e.unwrap())]:e instanceof PJ?[null,..._J(e.unwrap())]:e instanceof RJ||e instanceof BJ?_J(e.unwrap()):e instanceof IJ?_J(e._def.innerType):[];var vJ=class e extends Aq{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==uq.object)return _q(t,{code:X.invalid_type,expected:uq.object,received:t.parsedType}),yq;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}):(_q(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),yq)}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=_J(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,...kq(r)})}};function yJ(e,t){let n=dq(e),r=dq(t);if(e===t)return{valid:!0,data:e};if(n===uq.object&&r===uq.object){let n=cq.objectKeys(t),r=cq.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=yJ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===uq.array&&r===uq.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=yJ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===uq.date&&r===uq.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var bJ=class extends Aq{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Sq(e)||Sq(r))return yq;let i=yJ(e.value,r.value);return i.valid?((Cq(e)||Cq(r))&&t.dirty(),{status:t.value,value:i.data}):(_q(n,{code:X.invalid_intersection_types}),yq)};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}))}};bJ.create=(e,t,n)=>new bJ({left:e,right:t,typeName:Z.ZodIntersection,...kq(n)});var xJ=class e extends Aq{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==uq.array)return _q(n,{code:X.invalid_type,expected:uq.array,received:n.parsedType}),yq;if(n.data.length<this._def.items.length)return _q(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),yq;!this._def.rest&&n.data.length>this._def.items.length&&(_q(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Dq(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>vq.mergeArray(t,e)):vq.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};xJ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new xJ({items:e,typeName:Z.ZodTuple,rest:null,...kq(t)})};var SJ=class e extends Aq{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!==uq.object)return _q(n,{code:X.invalid_type,expected:uq.object,received:n.parsedType}),yq;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Dq(n,e,n.path,e)),value:a._parse(new Dq(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?vq.mergeObjectAsync(t,r):vq.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Aq?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...kq(r)}):new e({keyType:eJ.create(),valueType:t,typeName:Z.ZodRecord,...kq(n)})}},CJ=class extends Aq{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!==uq.map)return _q(n,{code:X.invalid_type,expected:uq.map,received:n.parsedType}),yq;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Dq(n,e,n.path,[a,`key`])),value:i._parse(new Dq(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return yq;(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 yq;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};CJ.create=(e,t,n)=>new CJ({valueType:t,keyType:e,typeName:Z.ZodMap,...kq(n)});var wJ=class e extends Aq{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==uq.set)return _q(n,{code:X.invalid_type,expected:uq.set,received:n.parsedType}),yq;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(_q(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&&(_q(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 yq;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Dq(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:Eq.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:Eq.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};wJ.create=(e,t)=>new wJ({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...kq(t)});var TJ=class e extends Aq{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==uq.function)return _q(t,{code:X.invalid_type,expected:uq.function,received:t.parsedType}),yq;function n(e,n){return gq({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,hq(),pq].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return gq({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,hq(),pq].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 jJ){let e=this;return xq(async function(...t){let o=new fq([]),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 xq(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new fq([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new fq([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:xJ.create(t).rest(uJ.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||xJ.create([]).rest(uJ.create()),returns:n||uJ.create(),typeName:Z.ZodFunction,...kq(r)})}},EJ=class extends Aq{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})}};EJ.create=(e,t)=>new EJ({getter:e,typeName:Z.ZodLazy,...kq(t)});var DJ=class extends Aq{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return _q(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),yq}return{status:`valid`,value:e.data}}get value(){return this._def.value}};DJ.create=(e,t)=>new DJ({value:e,typeName:Z.ZodLiteral,...kq(t)});function OJ(e,t){return new kJ({values:e,typeName:Z.ZodEnum,...kq(t)})}var kJ=class e extends Aq{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return _q(t,{expected:cq.joinValues(n),received:t.parsedType,code:X.invalid_type}),yq}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return _q(t,{received:t.data,code:X.invalid_enum_value,options:n}),yq}return xq(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})}};kJ.create=OJ;var AJ=class extends Aq{_parse(e){let t=cq.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==uq.string&&n.parsedType!==uq.number){let e=cq.objectValues(t);return _q(n,{expected:cq.joinValues(e),received:n.parsedType,code:X.invalid_type}),yq}if(this._cache||=new Set(cq.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=cq.objectValues(t);return _q(n,{received:n.data,code:X.invalid_enum_value,options:e}),yq}return xq(e.data)}get enum(){return this._def.values}};AJ.create=(e,t)=>new AJ({values:e,typeName:Z.ZodNativeEnum,...kq(t)});var jJ=class extends Aq{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==uq.promise&&t.common.async===!1?(_q(t,{code:X.invalid_type,expected:uq.promise,received:t.parsedType}),yq):xq((t.parsedType===uq.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};jJ.create=(e,t)=>new jJ({type:e,typeName:Z.ZodPromise,...kq(t)});var MJ=class extends Aq{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=>{_q(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 yq;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?yq:r.status===`dirty`||t.value===`dirty`?bq(r.value):r});{if(t.value===`aborted`)return yq;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?yq:r.status===`dirty`||t.value===`dirty`?bq(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`?yq:(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`?yq:(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(!wq(e))return yq;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=>wq(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):yq);cq.assertNever(r)}};MJ.create=(e,t,n)=>new MJ({schema:e,typeName:Z.ZodEffects,effect:t,...kq(n)}),MJ.createWithPreprocess=(e,t,n)=>new MJ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...kq(n)});var NJ=class extends Aq{_parse(e){return this._getType(e)===uq.undefined?xq(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};NJ.create=(e,t)=>new NJ({innerType:e,typeName:Z.ZodOptional,...kq(t)});var PJ=class extends Aq{_parse(e){return this._getType(e)===uq.null?xq(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};PJ.create=(e,t)=>new PJ({innerType:e,typeName:Z.ZodNullable,...kq(t)});var FJ=class extends Aq{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===uq.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};FJ.create=(e,t)=>new FJ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...kq(t)});var IJ=class extends Aq{_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 Tq(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new fq(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new fq(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};IJ.create=(e,t)=>new IJ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...kq(t)});var LJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.nan){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.nan,received:t.parsedType}),yq}return{status:`valid`,value:e.data}}};LJ.create=e=>new LJ({typeName:Z.ZodNaN,...kq(e)});var RJ=class extends Aq{_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}},zJ=class e extends Aq{_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`?yq:e.status===`dirty`?(t.dirty(),bq(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`?yq: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})}},BJ=class extends Aq{_parse(e){let t=this._def.innerType._parse(e),n=e=>(wq(e)&&(e.value=Object.freeze(e.value)),e);return Tq(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};BJ.create=(e,t)=>new BJ({innerType:e,typeName:Z.ZodReadonly,...kq(t)}),hJ.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||={}),eJ.create,nJ.create,LJ.create,rJ.create,iJ.create,aJ.create,oJ.create,sJ.create,cJ.create,lJ.create,uJ.create,dJ.create,fJ.create,pJ.create;const VJ=hJ.create;hJ.strictCreate,gJ.create,vJ.create,bJ.create,xJ.create,SJ.create,CJ.create,wJ.create,TJ.create,EJ.create,DJ.create,kJ.create,AJ.create,jJ.create,MJ.create,NJ.create,PJ.create,MJ.createWithPreprocess,zJ.create;const HJ=xa(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);to.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Da(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>da(e,t,n),e.parseAsync=async(t,n)=>pa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Sa(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)=>sa(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),UJ=xa(`ZodMiniObject`,(e,t)=>{ua.init(e,t),HJ.init(e,t),Ba(e,`shape`,()=>t.shape)});function WJ(e,t){return new UJ({type:`object`,shape:e??{},...ya(t)})}function GJ(e){return!!e._zod}function KJ(e){let t=Object.values(e);if(t.length===0)return WJ({});let n=t.every(GJ),r=t.every(e=>!GJ(e));if(n)return WJ(e);if(r)return VJ(e);throw Error(`Mixed Zod versions detected in object shape.`)}function qJ(e,t){return GJ(e)?da(e,t):e.safeParse(t)}async function JJ(e,t){return GJ(e)?await Sa(e,t):await e.safeParseAsync(t)}function YJ(e){if(!e)return;let t;if(t=GJ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function XJ(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 KJ(e)}}if(GJ(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 ZJ(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 QJ(e){return e.description}function $J(e){if(GJ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function eY(e){if(GJ(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 tY=`2025-11-25`,nY=[tY,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],rY=`io.modelcontextprotocol/related-task`,iY=Ya(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),aY=k([A(),P().int()]),oY=A();Ua({ttl:P().optional(),pollInterval:P().optional()});const sY=O({ttl:P().optional()}),cY=O({taskId:A()}),lY=Ua({progressToken:aY.optional(),[rY]:cY.optional()}),uY=O({_meta:lY.optional()}),dY=uY.extend({task:sY.optional()}),fY=e=>dY.safeParse(e).success,pY=O({method:A(),params:uY.loose().optional()}),mY=O({_meta:lY.optional()}),hY=O({method:A(),params:mY.loose().optional()}),gY=Ua({_meta:lY.optional()}),_Y=k([A(),P().int()]),vY=O({jsonrpc:D(`2.0`),id:_Y,...pY.shape}).strict(),yY=e=>vY.safeParse(e).success,bY=O({jsonrpc:D(`2.0`),...hY.shape}).strict(),xY=e=>bY.safeParse(e).success,SY=O({jsonrpc:D(`2.0`),id:_Y,result:gY}).strict(),CY=e=>SY.safeParse(e).success;var wY;(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`})(wY||={});const TY=O({jsonrpc:D(`2.0`),id:_Y.optional(),error:O({code:P().int(),message:A(),data:E().optional()})}).strict(),EY=e=>TY.safeParse(e).success,DY=k([vY,bY,SY,TY]);k([SY,TY]);const OY=gY.strict(),kY=mY.extend({requestId:_Y.optional(),reason:A().optional()}),AY=hY.extend({method:D(`notifications/cancelled`),params:kY}),jY=O({icons:N(O({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:wa([`light`,`dark`]).optional()})).optional()}),MY=O({name:A(),title:A().optional()}),NY=MY.extend({...MY.shape,...jY.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),PY=qa(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ka(O({form:Ka(O({applyDefaults:M().optional()}),j(A(),E())).optional(),url:iY.optional()}),j(A(),E()).optional())),FY=Ua({list:iY.optional(),cancel:iY.optional(),requests:Ua({sampling:Ua({createMessage:iY.optional()}).optional(),elicitation:Ua({create:iY.optional()}).optional()}).optional()}),IY=Ua({list:iY.optional(),cancel:iY.optional(),requests:Ua({tools:Ua({call:iY.optional()}).optional()}).optional()}),LY=O({experimental:j(A(),iY).optional(),sampling:O({context:iY.optional(),tools:iY.optional()}).optional(),elicitation:PY.optional(),roots:O({listChanged:M().optional()}).optional(),tasks:FY.optional(),extensions:j(A(),iY).optional()}),RY=uY.extend({protocolVersion:A(),capabilities:LY,clientInfo:NY}),zY=pY.extend({method:D(`initialize`),params:RY}),BY=e=>zY.safeParse(e).success,VY=O({experimental:j(A(),iY).optional(),logging:iY.optional(),completions:iY.optional(),prompts:O({listChanged:M().optional()}).optional(),resources:O({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:O({listChanged:M().optional()}).optional(),tasks:IY.optional(),extensions:j(A(),iY).optional()}),HY=gY.extend({protocolVersion:A(),capabilities:VY,serverInfo:NY,instructions:A().optional()}),UY=hY.extend({method:D(`notifications/initialized`),params:mY.optional()}),WY=e=>UY.safeParse(e).success,GY=pY.extend({method:D(`ping`),params:uY.optional()}),KY=O({progress:P(),total:Fa(P()),message:Fa(A())}),qY=O({...mY.shape,...KY.shape,progressToken:aY}),JY=hY.extend({method:D(`notifications/progress`),params:qY}),YY=uY.extend({cursor:oY.optional()}),XY=pY.extend({params:YY.optional()}),ZY=gY.extend({nextCursor:oY.optional()}),QY=wa([`working`,`input_required`,`completed`,`failed`,`cancelled`]),$Y=O({taskId:A(),status:QY,ttl:k([P(),oa()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Fa(P()),statusMessage:Fa(A())}),eX=gY.extend({task:$Y}),tX=mY.merge($Y),nX=hY.extend({method:D(`notifications/tasks/status`),params:tX}),rX=pY.extend({method:D(`tasks/get`),params:uY.extend({taskId:A()})}),iX=gY.merge($Y),aX=pY.extend({method:D(`tasks/result`),params:uY.extend({taskId:A()})});gY.loose();const oX=XY.extend({method:D(`tasks/list`)}),sX=ZY.extend({tasks:N($Y)}),cX=pY.extend({method:D(`tasks/cancel`),params:uY.extend({taskId:A()})}),lX=gY.merge($Y),uX=O({uri:A(),mimeType:Fa(A()),_meta:j(A(),E()).optional()}),dX=uX.extend({text:A()}),fX=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),pX=uX.extend({blob:fX}),mX=wa([`user`,`assistant`]),hX=O({audience:N(mX).optional(),priority:P().min(0).max(1).optional(),lastModified:no({offset:!0}).optional()}),gX=O({...MY.shape,...jY.shape,uri:A(),description:Fa(A()),mimeType:Fa(A()),size:Fa(P()),annotations:hX.optional(),_meta:Fa(Ua({}))}),_X=O({...MY.shape,...jY.shape,uriTemplate:A(),description:Fa(A()),mimeType:Fa(A()),annotations:hX.optional(),_meta:Fa(Ua({}))}),vX=XY.extend({method:D(`resources/list`)}),yX=ZY.extend({resources:N(gX)}),bX=XY.extend({method:D(`resources/templates/list`)}),xX=ZY.extend({resourceTemplates:N(_X)}),SX=uY.extend({uri:A()}),CX=SX,wX=pY.extend({method:D(`resources/read`),params:CX}),TX=gY.extend({contents:N(k([dX,pX]))}),EX=hY.extend({method:D(`notifications/resources/list_changed`),params:mY.optional()}),DX=SX,OX=pY.extend({method:D(`resources/subscribe`),params:DX}),kX=SX,AX=pY.extend({method:D(`resources/unsubscribe`),params:kX}),jX=mY.extend({uri:A()}),MX=hY.extend({method:D(`notifications/resources/updated`),params:jX}),NX=O({name:A(),description:Fa(A()),required:Fa(M())}),PX=O({...MY.shape,...jY.shape,description:Fa(A()),arguments:Fa(N(NX)),_meta:Fa(Ua({}))}),FX=XY.extend({method:D(`prompts/list`)}),IX=ZY.extend({prompts:N(PX)}),LX=uY.extend({name:A(),arguments:j(A(),A()).optional()}),RX=pY.extend({method:D(`prompts/get`),params:LX}),zX=O({type:D(`text`),text:A(),annotations:hX.optional(),_meta:j(A(),E()).optional()}),BX=O({type:D(`image`),data:fX,mimeType:A(),annotations:hX.optional(),_meta:j(A(),E()).optional()}),VX=O({type:D(`audio`),data:fX,mimeType:A(),annotations:hX.optional(),_meta:j(A(),E()).optional()}),HX=O({type:D(`tool_use`),name:A(),id:A(),input:j(A(),E()),_meta:j(A(),E()).optional()}),UX=O({type:D(`resource`),resource:k([dX,pX]),annotations:hX.optional(),_meta:j(A(),E()).optional()}),WX=k([zX,BX,VX,gX.extend({type:D(`resource_link`)}),UX]),GX=O({role:mX,content:WX}),KX=gY.extend({description:A().optional(),messages:N(GX)}),qX=hY.extend({method:D(`notifications/prompts/list_changed`),params:mY.optional()}),JX=O({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),YX=O({taskSupport:wa([`required`,`optional`,`forbidden`]).optional()}),XX=O({...MY.shape,...jY.shape,description:A().optional(),inputSchema:O({type:D(`object`),properties:j(A(),iY).optional(),required:N(A()).optional()}).catchall(E()),outputSchema:O({type:D(`object`),properties:j(A(),iY).optional(),required:N(A()).optional()}).catchall(E()).optional(),annotations:JX.optional(),execution:YX.optional(),_meta:j(A(),E()).optional()}),ZX=XY.extend({method:D(`tools/list`)}),QX=ZY.extend({tools:N(XX)}),$X=gY.extend({content:N(WX).default([]),structuredContent:j(A(),E()).optional(),isError:M().optional()});$X.or(gY.extend({toolResult:E()}));const eZ=dY.extend({name:A(),arguments:j(A(),E()).optional()}),tZ=pY.extend({method:D(`tools/call`),params:eZ}),nZ=hY.extend({method:D(`notifications/tools/list_changed`),params:mY.optional()});O({autoRefresh:M().default(!0),debounceMs:P().int().nonnegative().default(300)});const rZ=wa([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),iZ=uY.extend({level:rZ}),aZ=pY.extend({method:D(`logging/setLevel`),params:iZ}),oZ=mY.extend({level:rZ,logger:A().optional(),data:E()}),sZ=hY.extend({method:D(`notifications/message`),params:oZ}),cZ=O({hints:N(O({name:A().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),lZ=O({mode:wa([`auto`,`required`,`none`]).optional()}),uZ=O({type:D(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(WX).default([]),structuredContent:O({}).loose().optional(),isError:M().optional(),_meta:j(A(),E()).optional()}),dZ=za(`type`,[zX,BX,VX]),fZ=za(`type`,[zX,BX,VX,HX,uZ]),pZ=O({role:mX,content:k([fZ,N(fZ)]),_meta:j(A(),E()).optional()}),mZ=dY.extend({messages:N(pZ),modelPreferences:cZ.optional(),systemPrompt:A().optional(),includeContext:wa([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(A()).optional(),metadata:iY.optional(),tools:N(XX).optional(),toolChoice:lZ.optional()}),hZ=pY.extend({method:D(`sampling/createMessage`),params:mZ}),gZ=gY.extend({model:A(),stopReason:Fa(wa([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:mX,content:dZ}),_Z=gY.extend({model:A(),stopReason:Fa(wa([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:mX,content:k([fZ,N(fZ)])}),vZ=O({type:D(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),yZ=O({type:D(`string`),title:A().optional(),description:A().optional(),minLength:P().optional(),maxLength:P().optional(),format:wa([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),bZ=O({type:wa([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),xZ=O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),SZ=O({type:D(`string`),title:A().optional(),description:A().optional(),oneOf:N(O({const:A(),title:A()})),default:A().optional()}),CZ=k([k([O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),k([xZ,SZ]),k([O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({type:D(`string`),enum:N(A())}),default:N(A()).optional()}),O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({anyOf:N(O({const:A(),title:A()}))}),default:N(A()).optional()})])]),vZ,yZ,bZ]),wZ=k([dY.extend({mode:D(`form`).optional(),message:A(),requestedSchema:O({type:D(`object`),properties:j(A(),CZ),required:N(A()).optional()})}),dY.extend({mode:D(`url`),message:A(),elicitationId:A(),url:A().url()})]),TZ=pY.extend({method:D(`elicitation/create`),params:wZ}),EZ=mY.extend({elicitationId:A()}),DZ=hY.extend({method:D(`notifications/elicitation/complete`),params:EZ}),OZ=gY.extend({action:wa([`accept`,`decline`,`cancel`]),content:qa(e=>e===null?void 0:e,j(A(),k([A(),P(),M(),N(A())])).optional())}),kZ=O({type:D(`ref/resource`),uri:A()}),AZ=O({type:D(`ref/prompt`),name:A()}),jZ=uY.extend({ref:k([AZ,kZ]),argument:O({name:A(),value:A()}),context:O({arguments:j(A(),A()).optional()}).optional()}),MZ=pY.extend({method:D(`completion/complete`),params:jZ});function NZ(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function PZ(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const FZ=gY.extend({completion:Ua({values:N(A()).max(100),total:Fa(P().int()),hasMore:Fa(M())})}),IZ=O({uri:A().startsWith(`file://`),name:A().optional(),_meta:j(A(),E()).optional()}),LZ=pY.extend({method:D(`roots/list`),params:uY.optional()}),RZ=gY.extend({roots:N(IZ)}),zZ=hY.extend({method:D(`notifications/roots/list_changed`),params:mY.optional()});k([GY,zY,MZ,aZ,RX,FX,vX,bX,wX,OX,AX,tZ,ZX,rX,aX,oX,cX]),k([AY,JY,UY,zZ,nX]),k([OY,gZ,_Z,OZ,RZ,iX,sX,eX]),k([GY,hZ,TZ,LZ,rX,aX,oX,cX]),k([AY,JY,sZ,MX,EX,nZ,qX,nX,DZ]),k([OY,HY,FZ,KX,IX,yX,xX,TX,$X,QX,iX,sX,eX]);var BZ=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===wY.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new VZ(e.elicitations,n)}return new e(t,n,r)}},VZ=class extends BZ{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(wY.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function HZ(e){return e===`completed`||e===`failed`||e===`cancelled`}const UZ=Symbol(`Let zodToJsonSchema decide on which parser to use`),WZ={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`},GZ=e=>typeof e==`string`?{...WZ,name:e}:{...WZ,...e},KZ=e=>{let t=GZ(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 qZ(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function JZ(e,t,n,r,i){e[t]=n,qZ(e,t,r,i)}const YZ=(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 XZ(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?YZ(t,e.currentPath):t.join(`/`)}}function ZZ(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=VQ(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&JZ(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&JZ(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(JZ(n,`minItems`,e.exactLength.value,e.exactLength.message,t),JZ(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function QZ(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?JZ(n,`minimum`,r.value,r.message,t):JZ(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),JZ(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?JZ(n,`maximum`,r.value,r.message,t):JZ(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),JZ(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:JZ(n,`multipleOf`,r.value,r.message,t);break}return n}function $Z(){return{type:`boolean`}}function eQ(e,t){return VQ(e.type._def,t)}const tQ=(e,t)=>VQ(e.innerType._def,t);function nQ(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>nQ(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 rQ(e,t)}}const rQ=(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`:JZ(n,`minimum`,r.value,r.message,t);break;case`max`:JZ(n,`maximum`,r.value,r.message,t);break}return n};function iQ(e,t){return{...VQ(e.innerType._def,t),default:e.defaultValue()}}function aQ(e,t){return t.effectStrategy===`input`?VQ(e.schema._def,t):XZ(t)}function oQ(e){return{type:`string`,enum:Array.from(e.values)}}const sQ=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function cQ(e,t){let n=[VQ(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),VQ(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(sQ(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 lQ(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 uQ;const dQ={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:()=>(uQ===void 0&&(uQ=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),uQ),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 fQ(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:JZ(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:JZ(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`:gQ(n,`email`,r.message,t);break;case`format:idn-email`:gQ(n,`idn-email`,r.message,t);break;case`pattern:zod`:_Q(n,dQ.email,r.message,t);break}break;case`url`:gQ(n,`uri`,r.message,t);break;case`uuid`:gQ(n,`uuid`,r.message,t);break;case`regex`:_Q(n,r.regex,r.message,t);break;case`cuid`:_Q(n,dQ.cuid,r.message,t);break;case`cuid2`:_Q(n,dQ.cuid2,r.message,t);break;case`startsWith`:_Q(n,RegExp(`^${pQ(r.value,t)}`),r.message,t);break;case`endsWith`:_Q(n,RegExp(`${pQ(r.value,t)}$`),r.message,t);break;case`datetime`:gQ(n,`date-time`,r.message,t);break;case`date`:gQ(n,`date`,r.message,t);break;case`time`:gQ(n,`time`,r.message,t);break;case`duration`:gQ(n,`duration`,r.message,t);break;case`length`:JZ(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),JZ(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:_Q(n,RegExp(pQ(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&gQ(n,`ipv4`,r.message,t),r.version!==`v4`&&gQ(n,`ipv6`,r.message,t);break;case`base64url`:_Q(n,dQ.base64url,r.message,t);break;case`jwt`:_Q(n,dQ.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&_Q(n,dQ.ipv4Cidr,r.message,t),r.version!==`v4`&&_Q(n,dQ.ipv6Cidr,r.message,t);break;case`emoji`:_Q(n,dQ.emoji(),r.message,t);break;case`ulid`:_Q(n,dQ.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:gQ(n,`binary`,r.message,t);break;case`contentEncoding:base64`:JZ(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:_Q(n,dQ.base64,r.message,t);break}break;case`nanoid`:_Q(n,dQ.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function pQ(e,t){return t.patternStrategy===`escape`?hQ(e):e}const mQ=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function hQ(e){let t=``;for(let n=0;n<e.length;n++)mQ.has(e[n])||(t+=`\\`),t+=e[n];return t}function gQ(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}}})):JZ(e,`format`,t,n,r)}function _Q(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:vQ(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):JZ(e,`pattern`,vQ(t,r),n,r)}function vQ(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
1225
|
+
`);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(),ln.release(uo))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),ln.release(uo))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),ln.release(uo))})}let Jo=`local-op-auth-signout`,Yo=J(ni,async(e,t,n)=>{let r=n.host??vo();if(!ln.tryAcquire(fo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Jo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=st,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=tl(e,i,uj({...Xa,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,On,{},{handler:Jo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Jo,cause:e})}finally{ln.release(fo)}},{handler:Jo,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Jo})}),Zo=`/api/local-op/auth/set-identity`,es=`local-op-auth-set-identity`,ts=J(Rr,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!T){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:es});return}if(!ln.tryAcquire(Zo)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:es,extraHeaders:{"Retry-After":`5`}});return}try{nB(T,r,i),ot?.()?.refreshIdentity().catch(()=>{}),q(t,200,On,{},{handler:es})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:es,cause:e})}finally{ln.release(Zo)}},{handler:es,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:es})});async function ns(e,t){if(TV(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=ot?.();if(!e){q(t,200,Ft,{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,Ft,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 rs=J(le,async(e,t,n)=>{let r=ot?.();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,re,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:`sync-trigger`})?ot?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function is(e,t){if(TV(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=ot?.();q(t,200,eee,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let as=J(S,async(e,t,n)=>{let r=ot?.();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,zi,{},{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)=>TV(e,t,{handler:`sync-resolve-conflict`})?ot?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function os(e,t){if(!TV(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!T){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let 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=DS(i),o=n.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=ot?.(),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=Qo({baseDir:T,timeout:{block:15e3}}),d=s?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(d){try{let e=async e=>{if(!e)return``;try{return await u.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},r=await e(d.theirsSha),a=await e(d.baseSha),o=DS(i),s=n.documents.get(o),c=``,l=!1,f=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);f=typeof e==`string`&&e.length>0?e:null;let t=zt?zt(o):null;t!==null&&(c=t,l=!0)}else{WI(L(T,i),T);try{c=V(L(T,i),`utf-8`),l=!0}catch{l=!1}}let p=l?r.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,Gi,{file:i,base:a,ours:c,theirs:r,kind:p,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})}return}async function f(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([f(1),f(2),f(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:``,d=null;if(l===`ytext`){let e=DS(i),t=n.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=zt?zt(e):null;t!==null&&!DG(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,Gi,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function ss(e,t){if(!TV(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=RU(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,Mn,{plan:await eW({projectDir:o,rootDir:r,packId:a})},{handler:`seed-plan`})}catch(e){if(e instanceof EU){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof DU){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 cs=J(bn,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,s=RU(a);if(typeof a==`string`&&a.length>0&&s===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,gee,{result:await YU(i,{projectDir:o,packId:s})},{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)=>TV(e,t,{handler:`seed-apply`})});async function ls(e,t){if(TV(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,Zi,{packs:BU()},{handler:`seed-packs`})}}let us=J(fr,async(e,t,n)=>{if(n.out!==void 0&&!SV(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,sr,await XF({...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)=>TV(e,t,{handler:`install-skill`})});async function ds(e,t){if(TV(e,t,{handler:`installed-agents`}))try{await vj(e,t,In.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:LS(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let fs=J(ke,async(e,t)=>{if(!Je){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,Jn,{tags:Je.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 ms(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(!Je){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=Je.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:Vn(e),matchingTags:t,snippet:null}));q(t,200,c,{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 hs(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(o),s=i===``?a:z(a,i);return s!==a&&!s.startsWith(`${a}${ul}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let gs=/^[A-Za-z0-9_-]+$/;function _s(e,t,n=`template`){return!e||!gs.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 vs(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}${ul}`))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 bs(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 xs=iB({GET:J(ke,async(e,t)=>{try{let n=hs(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await XO(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,eD.parse)(await Gl(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,qi,{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(jt,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=JR(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=hs(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=tk({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`&&(Si(e,bi(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Ci(`folder-config-put`))}q(t,200,w,{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 Ss(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&&US(o)?(KS(i,new GS({file:`${a}.md`}),r),!0):!1}function Cs(e,t,r){let i=n.documents.get(e);return i&&US(i)?(KS(r,new GS({file:`${e}.md`}),t),!0):!1}let ws=J(ke,rB(async(e,t)=>{let n=OO(z(o));q(t,200,Ir,{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}),Ts=e=>{let{body:t}=Fi(e);return{frontmatter:et(e)??{},body:t}},Es=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!_s(r,t,`template-get`))return;let i=hs(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=vs(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=_n(await Gl(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,qr,{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}),Ds=J(yi,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=JR(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 i=n.name;if(!_s(i,t,`template-put`))return;let a=hs(n.folder,t,`folder`,`template-put`);if(!a||Ss(a.folderRel,i,`template-put`,t))return;let o=jk({name:i,body:typeof n.body==`string`?n.body:``,frontmatter:bs(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(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`),c=!B(s),l=R(a.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=zs(a.folderRel,i),{agentId:d,agentName:f,colorSeed:p,clientName:m}=fi(n),h=await r.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Xx(h.dc.document,o.content,`agent`)},h.origin);let g=await ur(u);if(g?.kind===`failure`){pr(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){hr(t,`template-put`);return}Si(e,bi(`template`,a.folderRel,i),`${c?`template-create`:`template-edit`}: ${l}`),await Ci(`template-put`),q(t,200,aee,{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`}),Os=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!_s(r,t,`template-delete`))return;let i=hs(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=JR({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(Ss(i.folderRel,r,`template-delete`,t))return;await Fr([zs(i.folderRel,r)],`deleted-upstream`);let s=Nk({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&&(Si(o,bi(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Ci(`template-delete`)),q(t,200,mee,{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}),ks=iB({GET:Es,PUT:Ds,POST:J(En,async(e,t,n)=>{try{let e=JR(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(!_s(n.fromName,t,`template-move`)||!_s(n.toName,t,`template-move`))return;let r=hs(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=hs(n.toFolder,t,`folder`,`template-move`);if(!i||Ss(r.folderRel,n.fromName,`template-move`,t))return;await Fr([zs(r.folderRel,n.fromName)],`renamed`);let a=await Fk({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await kK(T,e,t);return n||OK(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=vs(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=ir(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=Mk({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:bs(n.frontmatter)});t.ok||(o=t.error)}}if(Si(e,bi(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Ci(`template-move`),Ye?.(`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,ei,{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:Os},{handler:`template`}),As=J(dee,async(e,t,i)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=JR(i,ht);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let a=i.sourcePath;if(!MK(a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let s=Qn(a);if(_S(s)||vS(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`template-import`});return}let c=aK(o,`file`,s);if(!B(c)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${s}.`,{handler:`template-import`});return}let l=n.documents.get(s);if(i.deleteSource){let e=ot?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),r=l!==void 0&&US(l),i=n.has(a);if(r||i){KS(t,new GS({file:a}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await n.openDirectConnection(s);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=i.name;if(!d){let{basename:e}=oK(a);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!_s(d,t,`template-import`))return;let f=hs(i.targetFolder,t,`folder`,`template-import`);if(!f||Ss(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=Fi(u),h=Yi(p),g={};try{h.trim()&&(g=(0,eD.parse)(h))}catch{}let v=i.title||g?.title||eF(u,d),y=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,eD.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=jk({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),ee=!B(w),te=R(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),ne=zs(f.folderRel,d),{agentId:re,agentName:ie,colorSeed:ae,clientName:oe}=fi(i),se=await r.getSession(ne,re,{displayName:ie,colorSeed:ae,clientName:oe});se.dc.document.transact(()=>{Xx(se.dc.document,C.content,`agent`)},se.origin);let ce=await ur(ne);if(ce?.kind===`failure`){pr(t,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){hr(t,`template-import`);return}Si(e,bi(`template`,f.folderRel,d),`template-import: ${te}`),i.deleteSource&&(await Fr([s],`deleted-upstream`),Rt&&Rt.setDeleted(s),Eo(c),_?.({kind:`delete`,path:c,docName:s})),await Ci(`template-import`),Ye?.(`files`),q(t,200,yr,{path:te,created:ee,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 js(e,t,n){return!e||e.length>64||!Vi.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 Ms(e,t,n){let r=Ut.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 Ns=yt??Ll();function Ps(e){return z(e===`global`?Ns:o,`.ok`,`skills`)}let Fs=SF.project;function Is(){if(!T)return null;let e=[],t=null;for(let n of g){let r=St[n];if(!r)continue;let i=z(T,...r.split(`/`),Fs);B(z(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=z(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:R(T,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Ls(){let e=Is();if(!e)return null;let t;try{let{frontmatter:n}=Ts(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Fs,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Rs(e,t,n){return wF(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 zs(e,t){return`${i}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Bs(e){return e===`navigation`||e===`relevance`?e:void 0}function Vs(e,t){return R(t===`global`?Ns:o,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Hs(e){return e===`global`?Ns:T}async function Us(e,t){let n=await lM(e,t);return wI(t,e,g),n!==null}function Ws(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=Tl(e,{withFileTypes:!0})}catch(r){return F(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!Vi.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}=Ts(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:Vs(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Gs=J(ke,rB(async(e,t)=>{let n=Ws(Ps(`project`),`project`),r=Ws(Ps(`global`),`global`),i=T?oM(T).skills:{},a=oM(Ns).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=zoe(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Fs)?null:Ls();q(t,200,gn,{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}),Ks=O({managed:M().nullable(),importable:P().int().nonnegative()}),qs=()=>({managed:T?$F(T)?.manageEditorSkills??null:null,importable:T?Woe({projectDir:T,skillsRoot:Ps(`project`)}):0}),Js=iB({GET:J(ke,async(e,t)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Ks,qs(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:J(O({manageEditorSkills:M()}),async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await eI(T,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await BI({projectDir:T,skillsRoot:Ps(`project`)});e.adopted.length+e.collided.length>0&&Ye?.(`files`)}q(t,200,Ks,qs(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),Ys=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!js(r,t,`skill-get`))return;let i=Ms(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Fs&&i===`project`){let e=Is();if(e){let{frontmatter:n,body:a}=Ts(await Gl(e.skillMd,`utf-8`));q(t,200,it,{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:EI(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Ps(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}=Ts(await Gl(o,`utf-8`));q(t,200,it,{skill:{name:r,scope:i,path:Vs(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:EI(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}),Xs=J(aa,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-put`)||Rs(n.name,t,`skill-put`))return;let i=ck({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!i.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:i.error.code,cause:Error(i.error.message)});return}let a=Ps(n.scope),o=z(a,n.name,`SKILL.md`),s=!B(o),c=R(a,o).split(/[\\/]/).filter(Boolean).join(`/`),l=ji(n.scope,n.name);if(Cs(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=fi(n),m=await r.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Xx(m.dc.document,i.content,`agent`)},m.origin);let h=await ur(l);if(h?.kind===`failure`){pr(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){hr(t,`skill-put`);return}n.scope===`project`&&(Si(e,bi(`skill`,``,n.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Ci(`skill-put`)),Ye?.(`files`),q(t,200,b,{path:c,created:s,warnings:i.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`}),Zs=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!js(r,t,`skill-delete`)||Rs(r,t,`skill-delete`))return;let i=Ms(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Ps(i),o=n.searchParams,s=JR({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 Fr([ji(i,r)],`deleted-upstream`);let c=mk({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`&&(Si(s,bi(`skill`,``,r),`skill-delete: ${c.path}`),await Ci(`skill-delete`)),Ye?.(`files`));let l=Hs(i);l&&await Us(l,r),q(t,200,ut,{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}),Qs=iB({GET:Ys,PUT:Xs,POST:J(qe,async(e,t,n)=>{try{let e=JR(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(!js(n.fromName,t,`skill-move`)||!js(n.toName,t,`skill-move`)||Rs(n.fromName,t,`skill-move`)||Rs(n.toName,t,`skill-move`))return;let r=Ps(n.scope);await Fr([ji(n.scope,n.fromName)],`renamed`);let i=await hk({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await kK(T,e,t);return n||OK(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=Ts(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=lk({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{rc(r,n.fromName,n.toName)}catch(e){F(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let f=Vs(z(r,n.fromName),n.scope),p=Vs(z(r,n.toName),n.scope);n.scope===`project`&&(Si(e,bi(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Ci(`skill-move`));let m=Hs(n.scope);if(m){let e=await lM(m,n.fromName);if(e){let t=gI(e.hosts);wI(n.fromName,m,t);let i=CI(z(r,n.toName),n.toName,m,t);await cM(m,n.toName,{...e,hosts:i})}}if(Ye?.(`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,Et,{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:Zs},{handler:`skill`});function $s(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 ec(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function tc(e,t){let n=t.replace(/\.md$/i,``);return`${Rn(e).replace(/\/SKILL$/,``)}/${n}`}function nc(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of Tl(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 rc(e,t,n){if(!We)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{We.deleteDocument(e),Je?.deleteDocument(e);return}We.renameDocument(e,t,r),Je?.renameDocument(e,t,r)};r(Rn(t),Rn(n),z(e,n,`SKILL.md`));for(let i of nc(e,n))r(tc(t,i),tc(n,i),z(e,n,i));Ye?.(`backlinks`),Ye?.(`graph`)}let ic=iB({GET:J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!js(r,t,`skill-file-get`))return;let i=Ms(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Fs&&i===`project`?Is():null,s=o&&a===`SKILL.md`?`reference`:$s(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(Ps(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${ul}`)){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?ve.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 Gl(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,m,{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(Dr,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-file-put`)||Rs(n.name,t,`skill-file-put`))return;let i=$s(n.path);if(i===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 a=Ps(n.scope);if(!B(z(a,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=ec(n.scope,i,o),c;if(s){let e=tc(n.name,o);if(Cs(e,`skill-file-put`,t))return;if(c=!B(z(a,n.name,o)),c&&dk(z(a,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:i,agentName:s,colorSeed:l,clientName:u}=fi(n),d=await r.getSession(e,i,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{Xx(d.dc.document,n.content,`agent`)},d.origin);let f=await ur(e);if(f?.kind===`failure`){pr(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){hr(t,`skill-file-put`);return}}else{let e=fk({skillsRoot:a,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`&&(Si(e,bi(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${o}`),await Ci(`skill-file-put`)),Ye?.(`files`),q(t,200,$e,{path:o,created:c,kind:i,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(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!js(r,t,`skill-file-delete`)||Rs(r,t,`skill-file-delete`))return;let i=Ms(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=$s(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=JR({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=Ps(i);ec(i,o,a)&&await Fr([tc(r,a)],`deleted-upstream`);let l=pk({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`&&(Si(s,bi(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Ci(`skill-file-delete`)),l.existed&&Ye?.(`files`),q(t,200,Nr,{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`}),ac=J(mt,async(e,t,n)=>{try{let e=Ps(n.scope);if(!js(n.name,t,`skill-install`)||Rs(n.name,t,`skill-install`))return;if(n.scope===`project`&&!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Hs(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=yI(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?g.filter(e=>n.targets?.some(t=>t===e)):[...g]:n.targets===void 0?bI(r,UI(r)??void 0):g.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=gI(oM(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&wI(n.name,r,l);let u=CI(i,n.name,r,o);u.length===0?await lM(r,n.name):await cM(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),Ye?.(`files`),q(t,200,je,{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`}),oc=J(lee,async(e,t,n)=>{try{if(!js(n.name,t,`skill-uninstall`)||Rs(n.name,t,`skill-uninstall`))return;let e=Hs(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 Us(e,n.name);Ye?.(`files`),q(t,200,Le,{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`}),sc=iB({GET:J(ke,rB(async(e,t)=>{let n=T?UI(T):null;q(t,200,Zt,{targets:bI(T??``,n??void 0),configured:n!==null},{handler:`skill-targets-get`})},{handler:`skill-targets-get`,title:`Failed to read skill targets.`}),{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(Se,rB(async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let r=n.targets,i=new Set(r),a=bI(T,UI(T)??void 0),o=Ps(`project`);await Joe(T,r);let{reprojected:s,bundleHosts:c}=await Koe({projectDir:T,skillsRoot:o,targets:r});Ye?.(`files`),q(t,200,He,{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`}),cc=J(iee,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-restore`)||Rs(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=Ce?.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 sW({shadow:r,contentDir:o,contentRoot:Ue??`.`,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=[],s=yI(z(o,`.ok`,`skills`,n.name),n.name);s.ok||a.push(`Restored, but the skill no longer validates: ${s.errors.join(` `)}`),a.push("Run `install` to push the restored version to your editors."),Si(e,bi(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Ci(`skill-restore`),Ye?.(`files`),q(t,200,Oe,{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`}),lc=J(un,async(e,t,n)=>{try{let e=JR(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(!js(n.name,t,`skill-update`)||Rs(n.name,t,`skill-update`))return;if(!DI(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 i=Loe(n.name);if(i===null||i.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 a=z(Ps(`project`),n.name,`SKILL.md`);if(!B(a)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let o;try{o=OI(V(a,`utf-8`))}catch{}let s,c=Ce?.current;if(c)try{let e=Re?.()??`main`;s=(await BR(c,Ue??`.`,[TR],e,`Before updating ${n.name} (${o??`unversioned`} → ${i.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=ji(`project`,n.name);if(Cs(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=fi(n),m=await r.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Xx(m.dc.document,i.content,`agent`)},m.origin);let h=await ur(l);if(h?.kind===`failure`){pr(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){hr(t,`skill-update`);return}Si(e,bi(`skill`,``,n.name),`skill-pack-update: ${n.name} (${o??`unversioned`} → ${i.version})`),await Ci(`skill-update`),Ye?.(`files`),q(t,200,rn,{name:n.name,version:i.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 uc(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])=>Mt({kind:`folder`,path:e,modifiedTs:t}))}function dc(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 fc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function pc(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 mc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function hc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function gc(e,t,n,r){let i=r.documents.filter(e=>!Bn(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Gt?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Gt.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Gt.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Kt?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Gt.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function _c(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`?dc(e.document.content,t):void 0}}async function vc(e){let t=performance.now();if(Dc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await Oc(),i=await gc(e.query,e.intent,e.semanticParam,n),a=oe(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>_c(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},xA({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 yc(){let e=Ps(`project`);if(!B(e))return[];let t;try{t=Tl(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!Vi.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=jl(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function bc(){let e=[];for(let t of yc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=Ts(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(Mt({kind:`page`,path:ji(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function xc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Sc=new Map;async function Cc(){let e=[],t=[],n=new Set;for(let[r,i]of h()){if(_S(r)||vS(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(Mt({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=xc(i),o=Sc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await Gl(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=eF(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=Mt({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Sc.set(r,{key:a,doc:u}),e.push(u)}for(let e of Sc.keys())n.has(e)||Sc.delete(e);let r=WG(),i=t,a=!1;return t.length>r&&(a=!0,i=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,r),F(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),yG().add(1)),{documents:[...e,...bc(),...i,...uc([...e,...i])],truncated:a}}function wc(){return yc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Tc(){return te?`gen:${te()}|skills${wc()}`:`${[...h()].filter(([e])=>!_S(e)&&!vS(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${xc(t)}`).join(``)}|skills${wc()}`}let Ec=Nt===void 0;Nt?.then(()=>{Ec=!0},e=>{Ec=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Dc(){return!Ec}async function Oc(){let e=`${o}${T??``}`,t=Tc(),n=AK.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 Cc();if(!e)return xG().add(1,{mode:`cold`}),{corpus:vee(t),truncated:n};let a=ee(e,t);if(a.rebuilt){xG().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;F(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else xG().add(1,{mode:`incremental`}),F(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();AK.set(e,{fingerprint:t,pending:a});try{let n=await a;return AK.get(e)?.pending===a&&AK.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw AK.get(e)?.pending===a&&AK.delete(e),t}}function kc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Oc().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}kc();let Ac=iB({GET:J(ke,rB(async(e,t)=>{let n=See(e),r=n.get(`limit`),i=n.get(`query`)??``,a=fc(n.get(`intent`)),o=Bs(n.get(`ranking`)),s=pc(n.get(`scope`)??n.get(`scopes`)),c=mc(n.get(`semantic`)),l=hc(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,de,await vc({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(Lt,rB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=fc(n.intent),a=Bs(n.ranking),o=pc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=mc(n.semantic),l=hc(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,de,await vc({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`}),jc=J(ke,rB(async(e,t)=>{q(t,200,ge,{...await GF(Ll())},{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)=>TV(e,t,{handler:`skill-install-state`})});async function Mc(e,t){if(TV(e,t,{handler:`handoff`}))try{await Wj(e,t,{contentDir:o,platform:process.platform,isSchemeRegistered:In.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:LS(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Nc(e,t){if(TV(e,t,{handler:`spawn-cursor`}))try{await Pj(e,t,{contentDir:o,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:LS(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Pc=J(a,async(e,t,n)=>{try{if(!T){rF(`no-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`no-remote`},{handler:nF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!kae(e,n.kind)){rF(`invalid-path`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`invalid-path`},{handler:nF});return}let r=Pae(T);if(r===null){if(sF(T).kind===`no-remote`){rF(`no-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`no-remote`},{handler:nF});return}rF(`detached-head`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`detached-head`},{handler:nF});return}let i=sF(T);if(i.kind===`no-remote`){rF(`no-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`no-remote`},{handler:nF});return}if(i.kind===`non-github`){rF(`non-github-remote`,{kind:n.kind}),q(t,200,Kn,{ok:!1,error:`non-github-remote`},{handler:nF});return}if(!zae(T,r)){rF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,Kn,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:nF});return}let a=SK(T,o);if(a===null)throw Error(`content dir is not contained within the project dir`);let s=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&s&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=Aae(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=jae(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Nh(c)}`,u=await Mae(T,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);rF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,Kn,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:nF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:nF,cause:e})}},{handler:nF,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:nF})}),Fc=J(ke,async(e,t)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Uz});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(!Oi(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:Uz});return}if(!Vz(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:Uz});return}q(t,200,en,await Hz(T,r,i,a),{handler:Uz})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Uz,cause:e})}},{handler:Uz,method:`GET`,skipBodyParse:!0}),Ic=J(wn,async(e,t,n)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:xF});return}if(!Vz(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:xF});return}let e=SK(T,o);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,Qr,await eoe(T,n.branch,r,n.kind),{handler:xF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xF,cause:e})}},{handler:xF,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:xF})}),Lc=J(pn,async(e,t,n)=>{if(JR(n,ht).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:Jz});return}if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Jz});return}try{q(t,200,_t,await $o(()=>Xz(T,n.branch,{fastForward:n.fastForward===!0})),{handler:Jz})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Jz,cause:e})}},{handler:Jz,method:`POST`});async function Rc(e){let[t,...n]=st,r=[...n,...e];return await new Promise((e,n)=>{let i=tl(t,r,uj({...Ya,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},fF),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 ${fF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=vF(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 zc=J(ke,async(e,t)=>{if(!ln.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:lF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Rc([`share`,`owners`,`--json`]),n=Bae(hF(e));_F(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,Gr,n,{handler:lF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lF,cause:e})}finally{ln.release(`/api/share/publish/owners`)}},{handler:lF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>TV(e,t,{handler:lF})}),Bc=J(ke,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!mF(r)||!pF(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:uF});return}if(!ln.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:uF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Rc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Vae(hF(e));_F(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,pee,n,{handler:uF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:uF,cause:e})}finally{ln.release(`/api/share/publish/name-check`)}},{handler:uF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>TV(e,t,{handler:uF})}),Vc=J(uee,async(e,t,n)=>{if(!T){_F(`publish-create`,`no-project`),q(t,200,_r,{ok:!1,error:`no-project`},{handler:dF});return}if(!mF(n.owner)||!pF(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:dF});return}if(!ln.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:dF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,T,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Rc(e),i=Wae(hF(r));_F(`publish-create`,i.ok?`ok`:i.error),i.ok&&ot?.()?.refreshRemote().catch(()=>{}),q(t,200,_r,i,{handler:dF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:dF,cause:e})}finally{ln.release(`/api/share/publish`)}},{handler:dF,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:dF})}),Hc=J(Ae,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,Ke,{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)=>TV(e,t,{handler:`client-logs`})}),Uc=T?AD(T):null;async function Wc(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:Uc?ps(Uc)?.port??0:0,singleFile:an};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,tee,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 Gc=`local-op-embeddings-set-key`,Kc=`local-op-embeddings-clear-key`,qc=`/api/local-op/embeddings`;function Jc(){let e=Jt?.();return{projectDir:T??o,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Yc=J(nr,async(e,t,n)=>{if(!ln.tryAcquire(qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Gc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Jc();await new qA(qt).setForProject(e,r,n.key),Gt?.reloadCredential(),q(t,200,Wn,{keyPresent:!0},{handler:Gc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Gc,cause:e})}finally{ln.release(qc)}},{handler:Gc,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Gc})}),Xc=J(ke,async(e,t)=>{if(!ln.tryAcquire(qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Kc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Jc();await new qA(qt).clearForProject(e,n),Gt?.reloadCredential(),q(t,200,Wn,{keyPresent:!1},{handler:Kc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Kc,cause:e})}finally{ln.release(qc)}},{handler:Kc,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Kc})}),Zc=`local-op-embeddings-test`,Qc=`/api/local-op/embeddings/test`,$c=J(ke,async(e,t)=>{if(!ln.tryAcquire(Qc)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Zc,extraHeaders:{"Retry-After":`5`}});return}try{let e=Jt?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await IA(new qA(qt),T??o,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await RA({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,oi,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Zc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Zc,cause:e})}finally{ln.release(Qc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>TV(e,t,{handler:Zc})}),el=J(ke,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Gt){let t=Gt.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Jt?.()?.baseUrl??`https://api.openai.com/v1`,s=await IA(new qA(qt),T??o,a),c=s.apiKey!==null,u=!c&&s.keyless,d=c?s.source:null,f=s.apiKey&&s.apiKey.length>=8?s.apiKey.slice(-4):null,p=0;for(let[e]of l())!_S(e)&&!vS(e)&&!Bn(e)&&(p+=1);q(t,200,ae,{enabled:e,keyPresent:c,keyNotRequired:u,keySource:d,keyHint:f,ready:n,capable:r,embedded:i,total:p},{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 nl(e,t){let n=Qt?.()??Pt;try{let r=await $r(e,MP(o,n,{docName:t,projectDir:T??o,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=$t?.()??`warning`;if(We&&a!==`off`&&!SS(t)){We.updateDocumentFromMarkdown(t,e);let r=GP({projectDir:T??o,contentDir:o,baseConfig:n,backlinkIndex:We,linksValidation:a,admittedDocNames:br,docFilePathFor:e=>pK(o,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:pK(o,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function rl(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=FP({projectDir:T??o,contentDir:o});return RN(t.schemas,n)}let al=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!MK(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Qt?.()??Pt,i=[],a=kP(o,n??void 0,e=>i.push(e)),s=jP(T??o,AP(r,a),e=>i.push(e));n===null&&i.push(...rl(s)),q(t,200,Ii,{effective:s,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}),cl=J(kt,async(e,t,n)=>{let r;try{r=WP(z(o),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}Ye?.(`lint-config`);try{let e=Qt?.()??Pt,n=[],r=kP(o,void 0,e=>n.push(e)),i=jP(T??o,AP(e,r),e=>n.push(e));n.push(...rl(i)),q(t,200,Ii,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),ll=J(dr,async(e,t,n)=>{let r;try{let e=z(T??o),t=n.parentPath??[];r=n.delete?pae(e,n.file):n.field!==void 0&&n.removeField?dae(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?fae(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?lae(e,n.file,n.field,n.constraint,t):uae(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Ye?.(`files`),Ye?.(`lint-config`);try{let e=Qt?.()??Pt,n=[],r=kP(o,void 0,e=>n.push(e)),i=jP(T??o,AP(e,r),e=>n.push(e));n.push(...rl(i)),q(t,200,Ii,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),dl=J(ke,async(e,t)=>{try{let e=z(T??o),{schemas:n,truncated:r}=IN(e),i=new Set(n),a=!1;if(Tt!==void 0){let t=XG({contentDir:o,contentFilter:Tt,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&$n(a)){let t=R(e,z(o,a));!t.startsWith(`..`)&&!sl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let s=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,or,{schemas:s.slice(0,500),truncated:r||a||s.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),fl=e=>{let t=e.replace(/\.(md|mdx)$/i,``),r=n.documents.get(t);return r===void 0?null:r.getText(`source`).toString()},pl=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!MK(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=pK(o,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Qt?.()??Pt,a=[],s=await NP({projectDir:T??o,contentDir:o,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:fl});q(t,200,Xi,a.length>0?{...s,warnings:a}:s,{handler:`lint`})}catch(e){if(e instanceof KM){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}),ml=J(ke,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&&!QG(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Qt?.()??Pt;q(t,200,yn,await IP({projectDir:T??o,contentDir:o,baseConfig:i,targetPath:r,liveSourceFor:fl}),{handler:`lint-audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),hl=J(ke,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!QG(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),s=a===null||a===``?void 0:a;if(s!==void 0){if(i!==void 0||!QG(s)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=pK(o,s)??`${s}.md`}let c=Qt?.()??Pt;q(t,200,x,await gae(GP({projectDir:T??o,contentDir:o,baseConfig:c,liveSourceFor:fl,backlinkIndex:We??null,linksValidation:$t?.(),admittedDocNames:br,docFilePathFor:e=>pK(o,e)}),{targetPath:i}),{handler:`audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),gl=J(jn,async(t,n,i)=>{try{let t=rK(i.docName,n,`lint-fix`);if(t===null)return;let a=Qn(t),s=JR(i,ht);if(s.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=s.kind===`anonymous`?`principal-anonymous`:s.writerId,l=s.kind===`anonymous`?`Anonymous`:s.displayName,u=s.kind===`anonymous`?c:s.colorSeed,d=s.kind===`agent`?s.clientName:void 0;if(_S(a)||vS(a)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`lint-fix`});return}let f=pK(o,a);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}iK(z(o,f),o);let p=Qt?.()??Pt,{stored:m}=hi(s.summary),h=await r.getSession(a,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await PP({projectDir:T??o,contentDir:o,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=zn(d),n=Fn[t]??Pr(u??c);tt?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:a,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{AC(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0)},h.origin),s.kind!==`anonymous`&&Wk(a,c,l,u,void 0,s.kind===`agent`?pi({clientName:s.clientName,clientVersion:s.clientVersion,label:s.label}):s.actor,m)}finally{tt?.touchMode(c,`idle`)}let t=await ur(a);if(t?.kind===`failure`){pr(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){hr(n,`lint-fix`);return}lr(a,`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,Wi,{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 KM){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof GS){KS(n,e,`lint-fix`);return}if(e instanceof XS){QS(n,e,`lint-fix`);return}if(e instanceof IC){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`}),vl=`link-preview`,yl=new dV({cacheDir:an?null:z(T??o,`.ok`,`local`,`link-previews`)}),xl=null,Sl=()=>(xl??=yl.init(),xl),Cl=on??nV;async function wl(e){let t=await Cl(e);return t.ok?{ok:!0,metadata:await sV({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Cl})}:{ok:!1,reason:t.reason}}let El=()=>{try{return sn?.()===!0}catch{return!1}},Ol={"/api/config":Wc,"/api/asset":Pa,"/api/asset-text":Fa,"/api/document":Ni,"/api/documents":Pi,"/api/backlinks":Li,"/api/backlink-counts":Ri,"/api/link-preview":J(Ki,async(e,t,n)=>{try{if(!El()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,At,{ok:!1,reason:`disabled`},{handler:vl});return}await Sl();let e=!1,r=await yl.load(n.url,()=>(e=!0,wl(n.url)));yl.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,At,i,{handler:vl})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vl,cause:e})}},{handler:vl,method:`POST`,preBodyGate:(e,t)=>{let n=mV({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:vl}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:vl}),!1)}}),"/api/forward-links":Hi,"/api/link-graph":Ui,"/api/dead-links":ea,"/api/orphans":Ji,"/api/hubs":$i,"/api/tags":fs,"/api/pages":Ua,"/api/folder-config":xs,"/api/template":ks,"/api/template/import":As,"/api/templates":ws,"/api/skill":Qs,"/api/skill-file":ic,"/api/skills":Gs,"/api/skills/management":Js,"/api/skill/install":ac,"/api/skill/uninstall":oc,"/api/skill/restore":cc,"/api/skill/update":lc,"/api/skill-targets":sc,"/api/search":Ac,"/api/semantic-status":el,"/api/lint/config":al,"/api/lint/markdownlint-config":cl,"/api/lint/frontmatter-schema":ll,"/api/lint/frontmatter-schemas":dl,"/api/lint":pl,"/api/lint/audit":ml,"/api/lint/fix":gl,"/api/audit":hl,"/api/suggest-links":Wa,"/api/page-headings":za,"/api/create-page":k,"/api/create-folder":La,"/api/duplicate-path":Ra,"/api/rename-path":Ba,"/api/delete-path":Va,"/api/trash/cleanup":Ha,"/api/upload":j,"/api/agent-write":wi,"/api/agent-write-md":Ti,"/api/agent-write-batch":Di,"/api/frontmatter-patch":ki,"/api/agent-patch":ta,"/api/agent-undo":oa,"/api/agent-activity":sa,"/api/agent-burst-diff":la,"/api/save-version":ga,"/api/history":_a,"/api/rollback":ya,"/api/metrics/reconciliation":xa,"/api/metrics/parse-health":Sa,"/api/metrics/agent-presence":Aa,"/api/metrics/agent-effects":ja,"/api/metrics/watcher-recent":Ma,"/api/__embed-detect":E,"/api/server-info":Ca,"/api/acp/catalog":Da,"/api/share/construct-url":Pc,"/api/share/target-status":Ic,"/api/git/branch-info":Fc,"/api/git/checkout":Lc,"/api/share/publish/owners":zc,"/api/share/publish/name-check":Bc,"/api/share/publish":Vc,"/api/principal":ka,"/api/rescue":Ia,"/api/workspace":Na,"/api/sync/status":ns,"/api/sync/trigger":rs,"/api/sync/conflicts":is,"/api/sync/conflict-content":os,"/api/sync/resolve-conflict":as,"/api/local-op/clone":Qa,"/api/local-op/ok-init":no,"/api/local-op/auth/login":To,"/api/local-op/auth/status":zo,"/api/local-op/auth/pat":Ho,"/api/local-op/auth/gh-login":ko,"/api/local-op/auth/cancel":Io,"/api/local-op/auth/repos":Go,"/api/local-op/auth/signout":Yo,"/api/local-op/auth/set-identity":ts,"/api/local-op/embeddings/set-key":Yc,"/api/local-op/embeddings/clear-key":Xc,"/api/local-op/embeddings/test":$c,"/api/installed-agents":ds,"/api/spawn-cursor":Nc,"/api/handoff":Mc,"/api/install-skill":us,"/api/skill/install-state":jc,"/api/seed/plan":ss,"/api/seed/apply":cs,"/api/seed/packs":ls,"/api/client-logs":Hc};_e&&(Ol[`/api/test-reset`]=da,Ol[`/api/test-flush-git`]=ua,Ol[`/api/test-rescan-backlinks`]=pa,Ol[`/api/test-rescan-files`]=ma);let kl=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Al=[`/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};tA({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`:Ol[n]||(a=`/api/*`);let o=n.startsWith(`/api/`)?wre(e):void 0;if(o!==void 0&&(Tre(e,o),typeof t.setHeader==`function`&&t.setHeader(FS,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&&!sD(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, ${FS}, ${tr.protocol}, ${tr.runtime}, ${tr.kind}`),t.setHeader(`Access-Control-Expose-Headers`,FS)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(kl.has(n)||Al.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!$V(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!eH(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(an&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!$V(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!eH(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=ao.extract(co.active(),e.headers),c=So(),l=Date.now();await co.with(s,()=>c.startActiveSpan(`HTTP ${i} ${a}`,{kind:oo.SERVER,attributes:{[Ko]:i,[Wo]:a,[xee]:n,[bee]:`http`,[yee]:e.headers[`user-agent`]??``,"ok.request.id":o}},async r=>{try{let a=Ol[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 va(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await ms(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(Xo,s),s>=500&&r.setStatus({code:io.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:io.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;oG().record(e,{[Ko]:i,[Wo]:a,[Xo]:t.statusCode})}}))}}}function FK(e){let t=e?.code;return typeof t==`string`?t:void 0}function IK(e){let t;try{t=Tl(e.contentDir,{withFileTypes:!0})}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&ES(n.name,ba)&&e.basenameIndex.add(n.name)}async function LK(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Kl(i,{withFileTypes:!0})}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=cD(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Wl(a)}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await ql(a)}catch(t){let n=FK(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!lD(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Jl(i)}catch(t){let n=FK(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()&&ES(a,ca)&&!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()&&ES(a,ca)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const RK=O({principalId:A().optional(),tabSessionId:A().optional(),expectedServerInstanceId:A().optional(),expectedBranch:A().optional(),expectedDocLineageEpoch:A().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:A().optional(),clientKind:A().optional()}).loose(),zK=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function BK(e){return zK.includes(e)}function VK(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function HK(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!BK(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 UK=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=VK(e,this.payload)}};function WK(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=RK.safeParse(t);return n.success?n.data:void 0}var GK=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const KK=F(`conflict-storage`);var qK=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(AD(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){KK.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){KK.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||bl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Nl(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return KK.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-CRnnMEIm.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!lD(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);WI(r,t),Bo(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),KK.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await bF(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){KK.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}),KK.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=z(this.projectDir),a=z(i,e.file);if(!lD(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(WI(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-CRnnMEIm.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);WI(a,i),Bo(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);Bo(a,n,`utf-8`);break;case`delete`:B(a)&&Eo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function JK(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 YK(e,t){let n=AD(e);try{bl(n,{recursive:!0}),Nl(L(n,fe),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=qo(e);bl(I(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};Nl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const XK=new Map;let ZK=!1;function QK(e,t){try{let n=JK(e,t);for(let e of XK.keys())YK(e,n)}catch{}}function $K(e){XK.set(e,(XK.get(e)??0)+1),ZK||(ZK=!0,process.on(`uncaughtExceptionMonitor`,QK));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=XK.get(e)??0;n<=1?XK.delete(e):XK.set(e,n-1)}}}function eq(e){let t=e.scheduler??h,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 tq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nq(e){if(!B(e))return{};let t;try{t=(0,eD.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(!tq(t))return{};let n=t.telemetry;if(!tq(n))return{};let r=n.localSink;return tq(r)?r:{}}function rq(e){return typeof e==`boolean`?e:void 0}function iq(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function aq(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function oq(e){if(tq(e))return iq(e.maxBytes)}function sq(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=nq(_o(`project`,e.projectDir)),n=nq(_o(`project-local`,e.projectDir));if((rq(n.enabled)??rq(t.enabled)??!0)===!1)return null;let r=oq(n.spans)??oq(t.spans)??52428800,i=oq(n.logs)??oq(t.logs)??26214400,a=aq(n.attributeDenylist)??aq(t.attributeDenylist)??Ta;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var cq;(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})(cq||={});var lq;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(lq||={});const uq=cq.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),dq=e=>{switch(typeof e){case`undefined`:return uq.undefined;case`string`:return uq.string;case`number`:return Number.isNaN(e)?uq.nan:uq.number;case`boolean`:return uq.boolean;case`function`:return uq.function;case`bigint`:return uq.bigint;case`symbol`:return uq.symbol;case`object`:return Array.isArray(e)?uq.array:e===null?uq.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?uq.promise:typeof Map<`u`&&e instanceof Map?uq.map:typeof Set<`u`&&e instanceof Set?uq.set:typeof Date<`u`&&e instanceof Date?uq.date:uq.object;default:return uq.unknown}},X=cq.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 fq=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,cq.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()}};fq.create=e=>new fq(e);const pq=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===uq.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,cq.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${cq.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${cq.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${cq.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}"`:cq.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,cq.assertNever(e)}return{message:n}};let mq=pq;function hq(){return mq}const gq=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 _q(e,t){let n=hq(),r=gq({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===pq?void 0:pq].filter(e=>!!e)});e.common.issues.push(r)}var vq=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 yq;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 yq;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 yq=Object.freeze({status:`aborted`}),bq=e=>({status:`dirty`,value:e}),xq=e=>({status:`valid`,value:e}),Sq=e=>e.status===`aborted`,Cq=e=>e.status===`dirty`,wq=e=>e.status===`valid`,Tq=e=>typeof Promise<`u`&&e instanceof Promise;var Eq;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(Eq||={});var Dq=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const Oq=(e,t)=>{if(wq(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 fq(e.common.issues);return this._error=t,this._error}}};function kq(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 Aq=class{get description(){return this._def.description}_getType(e){return dq(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:dq(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vq,ctx:{common:e.parent.common,data:e.data,parsedType:dq(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Tq(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:dq(e)};return Oq(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:dq(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return wq(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=>wq(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:dq(e)},r=this._parse({data:e,path:n.path,parent:n});return Oq(n,await(Tq(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 MJ({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 NJ.create(this,this._def)}nullable(){return PJ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pJ.create(this)}promise(){return jJ.create(this,this._def)}or(e){return gJ.create([this,e],this._def)}and(e){return bJ.create(this,e,this._def)}transform(e){return new MJ({...kq(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new FJ({...kq(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new RJ({typeName:Z.ZodBranded,type:this,...kq(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new IJ({...kq(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 zJ.create(this,e)}readonly(){return BJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const jq=/^c[^\s-]{8,}$/i,Mq=/^[0-9a-z]+$/,Nq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Pq=/^[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,Fq=/^[a-z0-9_-]{21}$/i,Iq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Lq=/^[-+]?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)?)??$/,Rq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let zq;const Bq=/^(?:(?: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])$/,Vq=/^(?:(?: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])$/,Hq=/^(([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]))$/,Uq=/^(([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])$/,Wq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kq=`((\\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])))`,qq=RegExp(`^${Kq}$`);function Jq(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 Yq(e){return RegExp(`^${Jq(e)}$`)}function Xq(e){let t=`${Kq}T${Jq(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Zq(e,t){return!!((t===`v4`||!t)&&Bq.test(e)||(t===`v6`||!t)&&Hq.test(e))}function Qq(e,t){if(!Iq.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 $q(e,t){return!!((t===`v4`||!t)&&Vq.test(e)||(t===`v6`||!t)&&Uq.test(e))}var eJ=class e extends Aq{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==uq.string){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.string,received:t.parsedType}),yq}let t=new vq,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),_q(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),_q(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?_q(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&_q(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Rq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)zq||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),zq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Pq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Fq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)jq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Mq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Nq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(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),_q(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),_q(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),_q(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),_q(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),_q(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Xq(r).test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?qq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Yq(r).test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Lq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Zq(e.data,r.version)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Qq(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?$q(e.data,r.version)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Wq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Gq.test(e.data)||(n=this._getOrReturnCtx(e,n),_q(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):cq.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,...Eq.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...Eq.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...Eq.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...Eq.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...Eq.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...Eq.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...Eq.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...Eq.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...Eq.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...Eq.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...Eq.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...Eq.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...Eq.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...Eq.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,...Eq.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,...Eq.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...Eq.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...Eq.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...Eq.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...Eq.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...Eq.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...Eq.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...Eq.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...Eq.errToObj(t)})}nonempty(e){return this.min(1,Eq.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}};eJ.create=e=>new eJ({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...kq(e)});function tJ(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 nJ=class e extends Aq{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)!==uq.number){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.number,received:t.parsedType}),yq}let t,n=new vq;for(let r of this._def.checks)r.kind===`int`?cq.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),_q(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),_q(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),_q(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?tJ(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),_q(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),_q(t,{code:X.not_finite,message:r.message}),n.dirty()):cq.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,Eq.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Eq.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Eq.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Eq.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Eq.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:Eq.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:Eq.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:Eq.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:Eq.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:Eq.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Eq.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:Eq.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:Eq.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:Eq.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`&&cq.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)}};nJ.create=e=>new nJ({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...kq(e)});var rJ=class e extends Aq{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)!==uq.bigint)return this._getInvalidInput(e);let t,n=new vq;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),_q(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),_q(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),_q(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):cq.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.bigint,received:t.parsedType}),yq}gte(e,t){return this.setLimit(`min`,e,!0,Eq.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,Eq.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,Eq.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,Eq.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Eq.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:Eq.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:Eq.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:Eq.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:Eq.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:Eq.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}};rJ.create=e=>new rJ({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...kq(e)});var iJ=class extends Aq{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==uq.boolean){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.boolean,received:t.parsedType}),yq}return xq(e.data)}};iJ.create=e=>new iJ({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...kq(e)});var aJ=class e extends Aq{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==uq.date){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.date,received:t.parsedType}),yq}if(Number.isNaN(e.data.getTime()))return _q(this._getOrReturnCtx(e),{code:X.invalid_date}),yq;let t=new vq,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),_q(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),_q(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):cq.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:Eq.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:Eq.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)}};aJ.create=e=>new aJ({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...kq(e)});var oJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.symbol){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.symbol,received:t.parsedType}),yq}return xq(e.data)}};oJ.create=e=>new oJ({typeName:Z.ZodSymbol,...kq(e)});var sJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.undefined){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.undefined,received:t.parsedType}),yq}return xq(e.data)}};sJ.create=e=>new sJ({typeName:Z.ZodUndefined,...kq(e)});var cJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.null){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.null,received:t.parsedType}),yq}return xq(e.data)}};cJ.create=e=>new cJ({typeName:Z.ZodNull,...kq(e)});var lJ=class extends Aq{constructor(){super(...arguments),this._any=!0}_parse(e){return xq(e.data)}};lJ.create=e=>new lJ({typeName:Z.ZodAny,...kq(e)});var uJ=class extends Aq{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xq(e.data)}};uJ.create=e=>new uJ({typeName:Z.ZodUnknown,...kq(e)});var dJ=class extends Aq{_parse(e){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.never,received:t.parsedType}),yq}};dJ.create=e=>new dJ({typeName:Z.ZodNever,...kq(e)});var fJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.undefined){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.void,received:t.parsedType}),yq}return xq(e.data)}};fJ.create=e=>new fJ({typeName:Z.ZodVoid,...kq(e)});var pJ=class e extends Aq{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==uq.array)return _q(t,{code:X.invalid_type,expected:uq.array,received:t.parsedType}),yq;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(_q(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&&(_q(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&&(_q(t,{code:X.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new Dq(t,e,t.path,n)))).then(e=>vq.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new Dq(t,e,t.path,n)));return vq.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:Eq.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:Eq.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:Eq.toString(n)}})}nonempty(e){return this.min(1,e)}};pJ.create=(e,t)=>new pJ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...kq(t)});function mJ(e){if(e instanceof hJ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=NJ.create(mJ(r))}return new hJ({...e._def,shape:()=>t})}else if(e instanceof pJ)return new pJ({...e._def,type:mJ(e.element)});else if(e instanceof NJ)return NJ.create(mJ(e.unwrap()));else if(e instanceof PJ)return PJ.create(mJ(e.unwrap()));else if(e instanceof xJ)return xJ.create(e.items.map(e=>mJ(e)));else return e}var hJ=class e extends Aq{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=cq.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==uq.object){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.object,received:t.parsedType}),yq}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof dJ&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new Dq(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof dJ){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&&(_q(n,{code:X.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new Dq(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>vq.mergeObjectSync(t,e)):vq.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return Eq.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:Eq.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 cq.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 cq.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return mJ(this)}partial(t){let n={};for(let e of cq.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 cq.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof NJ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return OJ(cq.objectKeys(this.shape))}};hJ.create=(e,t)=>new hJ({shape:()=>e,unknownKeys:`strip`,catchall:dJ.create(),typeName:Z.ZodObject,...kq(t)}),hJ.strictCreate=(e,t)=>new hJ({shape:()=>e,unknownKeys:`strict`,catchall:dJ.create(),typeName:Z.ZodObject,...kq(t)}),hJ.lazycreate=(e,t)=>new hJ({shape:e,unknownKeys:`strip`,catchall:dJ.create(),typeName:Z.ZodObject,...kq(t)});var gJ=class extends Aq{_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 fq(e.ctx.common.issues));return _q(t,{code:X.invalid_union,unionErrors:n}),yq}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 fq(e));return _q(t,{code:X.invalid_union,unionErrors:i}),yq}}get options(){return this._def.options}};gJ.create=(e,t)=>new gJ({options:e,typeName:Z.ZodUnion,...kq(t)});const _J=e=>e instanceof EJ?_J(e.schema):e instanceof MJ?_J(e.innerType()):e instanceof DJ?[e.value]:e instanceof kJ?e.options:e instanceof AJ?cq.objectValues(e.enum):e instanceof FJ?_J(e._def.innerType):e instanceof sJ?[void 0]:e instanceof cJ?[null]:e instanceof NJ?[void 0,..._J(e.unwrap())]:e instanceof PJ?[null,..._J(e.unwrap())]:e instanceof RJ||e instanceof BJ?_J(e.unwrap()):e instanceof IJ?_J(e._def.innerType):[];var vJ=class e extends Aq{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==uq.object)return _q(t,{code:X.invalid_type,expected:uq.object,received:t.parsedType}),yq;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}):(_q(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),yq)}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=_J(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,...kq(r)})}};function yJ(e,t){let n=dq(e),r=dq(t);if(e===t)return{valid:!0,data:e};if(n===uq.object&&r===uq.object){let n=cq.objectKeys(t),r=cq.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=yJ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===uq.array&&r===uq.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=yJ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===uq.date&&r===uq.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var bJ=class extends Aq{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Sq(e)||Sq(r))return yq;let i=yJ(e.value,r.value);return i.valid?((Cq(e)||Cq(r))&&t.dirty(),{status:t.value,value:i.data}):(_q(n,{code:X.invalid_intersection_types}),yq)};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}))}};bJ.create=(e,t,n)=>new bJ({left:e,right:t,typeName:Z.ZodIntersection,...kq(n)});var xJ=class e extends Aq{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==uq.array)return _q(n,{code:X.invalid_type,expected:uq.array,received:n.parsedType}),yq;if(n.data.length<this._def.items.length)return _q(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),yq;!this._def.rest&&n.data.length>this._def.items.length&&(_q(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new Dq(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>vq.mergeArray(t,e)):vq.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};xJ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new xJ({items:e,typeName:Z.ZodTuple,rest:null,...kq(t)})};var SJ=class e extends Aq{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!==uq.object)return _q(n,{code:X.invalid_type,expected:uq.object,received:n.parsedType}),yq;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new Dq(n,e,n.path,e)),value:a._parse(new Dq(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?vq.mergeObjectAsync(t,r):vq.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Aq?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...kq(r)}):new e({keyType:eJ.create(),valueType:t,typeName:Z.ZodRecord,...kq(n)})}},CJ=class extends Aq{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!==uq.map)return _q(n,{code:X.invalid_type,expected:uq.map,received:n.parsedType}),yq;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new Dq(n,e,n.path,[a,`key`])),value:i._parse(new Dq(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return yq;(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 yq;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};CJ.create=(e,t,n)=>new CJ({valueType:t,keyType:e,typeName:Z.ZodMap,...kq(n)});var wJ=class e extends Aq{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==uq.set)return _q(n,{code:X.invalid_type,expected:uq.set,received:n.parsedType}),yq;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(_q(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&&(_q(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 yq;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new Dq(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:Eq.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:Eq.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};wJ.create=(e,t)=>new wJ({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...kq(t)});var TJ=class e extends Aq{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==uq.function)return _q(t,{code:X.invalid_type,expected:uq.function,received:t.parsedType}),yq;function n(e,n){return gq({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,hq(),pq].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return gq({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,hq(),pq].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 jJ){let e=this;return xq(async function(...t){let o=new fq([]),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 xq(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new fq([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new fq([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:xJ.create(t).rest(uJ.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||xJ.create([]).rest(uJ.create()),returns:n||uJ.create(),typeName:Z.ZodFunction,...kq(r)})}},EJ=class extends Aq{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})}};EJ.create=(e,t)=>new EJ({getter:e,typeName:Z.ZodLazy,...kq(t)});var DJ=class extends Aq{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return _q(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),yq}return{status:`valid`,value:e.data}}get value(){return this._def.value}};DJ.create=(e,t)=>new DJ({value:e,typeName:Z.ZodLiteral,...kq(t)});function OJ(e,t){return new kJ({values:e,typeName:Z.ZodEnum,...kq(t)})}var kJ=class e extends Aq{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return _q(t,{expected:cq.joinValues(n),received:t.parsedType,code:X.invalid_type}),yq}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return _q(t,{received:t.data,code:X.invalid_enum_value,options:n}),yq}return xq(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})}};kJ.create=OJ;var AJ=class extends Aq{_parse(e){let t=cq.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==uq.string&&n.parsedType!==uq.number){let e=cq.objectValues(t);return _q(n,{expected:cq.joinValues(e),received:n.parsedType,code:X.invalid_type}),yq}if(this._cache||=new Set(cq.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=cq.objectValues(t);return _q(n,{received:n.data,code:X.invalid_enum_value,options:e}),yq}return xq(e.data)}get enum(){return this._def.values}};AJ.create=(e,t)=>new AJ({values:e,typeName:Z.ZodNativeEnum,...kq(t)});var jJ=class extends Aq{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==uq.promise&&t.common.async===!1?(_q(t,{code:X.invalid_type,expected:uq.promise,received:t.parsedType}),yq):xq((t.parsedType===uq.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};jJ.create=(e,t)=>new jJ({type:e,typeName:Z.ZodPromise,...kq(t)});var MJ=class extends Aq{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=>{_q(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 yq;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?yq:r.status===`dirty`||t.value===`dirty`?bq(r.value):r});{if(t.value===`aborted`)return yq;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?yq:r.status===`dirty`||t.value===`dirty`?bq(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`?yq:(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`?yq:(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(!wq(e))return yq;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=>wq(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):yq);cq.assertNever(r)}};MJ.create=(e,t,n)=>new MJ({schema:e,typeName:Z.ZodEffects,effect:t,...kq(n)}),MJ.createWithPreprocess=(e,t,n)=>new MJ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...kq(n)});var NJ=class extends Aq{_parse(e){return this._getType(e)===uq.undefined?xq(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};NJ.create=(e,t)=>new NJ({innerType:e,typeName:Z.ZodOptional,...kq(t)});var PJ=class extends Aq{_parse(e){return this._getType(e)===uq.null?xq(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};PJ.create=(e,t)=>new PJ({innerType:e,typeName:Z.ZodNullable,...kq(t)});var FJ=class extends Aq{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===uq.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};FJ.create=(e,t)=>new FJ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...kq(t)});var IJ=class extends Aq{_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 Tq(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new fq(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new fq(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};IJ.create=(e,t)=>new IJ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...kq(t)});var LJ=class extends Aq{_parse(e){if(this._getType(e)!==uq.nan){let t=this._getOrReturnCtx(e);return _q(t,{code:X.invalid_type,expected:uq.nan,received:t.parsedType}),yq}return{status:`valid`,value:e.data}}};LJ.create=e=>new LJ({typeName:Z.ZodNaN,...kq(e)});var RJ=class extends Aq{_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}},zJ=class e extends Aq{_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`?yq:e.status===`dirty`?(t.dirty(),bq(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`?yq: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})}},BJ=class extends Aq{_parse(e){let t=this._def.innerType._parse(e),n=e=>(wq(e)&&(e.value=Object.freeze(e.value)),e);return Tq(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};BJ.create=(e,t)=>new BJ({innerType:e,typeName:Z.ZodReadonly,...kq(t)}),hJ.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||={}),eJ.create,nJ.create,LJ.create,rJ.create,iJ.create,aJ.create,oJ.create,sJ.create,cJ.create,lJ.create,uJ.create,dJ.create,fJ.create,pJ.create;const VJ=hJ.create;hJ.strictCreate,gJ.create,vJ.create,bJ.create,xJ.create,SJ.create,CJ.create,wJ.create,TJ.create,EJ.create,DJ.create,kJ.create,AJ.create,jJ.create,MJ.create,NJ.create,PJ.create,MJ.createWithPreprocess,zJ.create;const HJ=xa(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);to.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Da(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>da(e,t,n),e.parseAsync=async(t,n)=>pa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Sa(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)=>sa(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),UJ=xa(`ZodMiniObject`,(e,t)=>{ua.init(e,t),HJ.init(e,t),Ba(e,`shape`,()=>t.shape)});function WJ(e,t){return new UJ({type:`object`,shape:e??{},...ya(t)})}function GJ(e){return!!e._zod}function KJ(e){let t=Object.values(e);if(t.length===0)return WJ({});let n=t.every(GJ),r=t.every(e=>!GJ(e));if(n)return WJ(e);if(r)return VJ(e);throw Error(`Mixed Zod versions detected in object shape.`)}function qJ(e,t){return GJ(e)?da(e,t):e.safeParse(t)}async function JJ(e,t){return GJ(e)?await Sa(e,t):await e.safeParseAsync(t)}function YJ(e){if(!e)return;let t;if(t=GJ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function XJ(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 KJ(e)}}if(GJ(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 ZJ(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 QJ(e){return e.description}function $J(e){if(GJ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function eY(e){if(GJ(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 tY=`2025-11-25`,nY=[tY,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],rY=`io.modelcontextprotocol/related-task`,iY=Ya(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),aY=k([A(),P().int()]),oY=A();Ua({ttl:P().optional(),pollInterval:P().optional()});const sY=O({ttl:P().optional()}),cY=O({taskId:A()}),lY=Ua({progressToken:aY.optional(),[rY]:cY.optional()}),uY=O({_meta:lY.optional()}),dY=uY.extend({task:sY.optional()}),fY=e=>dY.safeParse(e).success,pY=O({method:A(),params:uY.loose().optional()}),mY=O({_meta:lY.optional()}),hY=O({method:A(),params:mY.loose().optional()}),gY=Ua({_meta:lY.optional()}),_Y=k([A(),P().int()]),vY=O({jsonrpc:D(`2.0`),id:_Y,...pY.shape}).strict(),yY=e=>vY.safeParse(e).success,bY=O({jsonrpc:D(`2.0`),...hY.shape}).strict(),xY=e=>bY.safeParse(e).success,SY=O({jsonrpc:D(`2.0`),id:_Y,result:gY}).strict(),CY=e=>SY.safeParse(e).success;var wY;(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`})(wY||={});const TY=O({jsonrpc:D(`2.0`),id:_Y.optional(),error:O({code:P().int(),message:A(),data:E().optional()})}).strict(),EY=e=>TY.safeParse(e).success,DY=k([vY,bY,SY,TY]);k([SY,TY]);const OY=gY.strict(),kY=mY.extend({requestId:_Y.optional(),reason:A().optional()}),AY=hY.extend({method:D(`notifications/cancelled`),params:kY}),jY=O({icons:N(O({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:wa([`light`,`dark`]).optional()})).optional()}),MY=O({name:A(),title:A().optional()}),NY=MY.extend({...MY.shape,...jY.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),PY=qa(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ka(O({form:Ka(O({applyDefaults:M().optional()}),j(A(),E())).optional(),url:iY.optional()}),j(A(),E()).optional())),FY=Ua({list:iY.optional(),cancel:iY.optional(),requests:Ua({sampling:Ua({createMessage:iY.optional()}).optional(),elicitation:Ua({create:iY.optional()}).optional()}).optional()}),IY=Ua({list:iY.optional(),cancel:iY.optional(),requests:Ua({tools:Ua({call:iY.optional()}).optional()}).optional()}),LY=O({experimental:j(A(),iY).optional(),sampling:O({context:iY.optional(),tools:iY.optional()}).optional(),elicitation:PY.optional(),roots:O({listChanged:M().optional()}).optional(),tasks:FY.optional(),extensions:j(A(),iY).optional()}),RY=uY.extend({protocolVersion:A(),capabilities:LY,clientInfo:NY}),zY=pY.extend({method:D(`initialize`),params:RY}),BY=e=>zY.safeParse(e).success,VY=O({experimental:j(A(),iY).optional(),logging:iY.optional(),completions:iY.optional(),prompts:O({listChanged:M().optional()}).optional(),resources:O({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:O({listChanged:M().optional()}).optional(),tasks:IY.optional(),extensions:j(A(),iY).optional()}),HY=gY.extend({protocolVersion:A(),capabilities:VY,serverInfo:NY,instructions:A().optional()}),UY=hY.extend({method:D(`notifications/initialized`),params:mY.optional()}),WY=e=>UY.safeParse(e).success,GY=pY.extend({method:D(`ping`),params:uY.optional()}),KY=O({progress:P(),total:Fa(P()),message:Fa(A())}),qY=O({...mY.shape,...KY.shape,progressToken:aY}),JY=hY.extend({method:D(`notifications/progress`),params:qY}),YY=uY.extend({cursor:oY.optional()}),XY=pY.extend({params:YY.optional()}),ZY=gY.extend({nextCursor:oY.optional()}),QY=wa([`working`,`input_required`,`completed`,`failed`,`cancelled`]),$Y=O({taskId:A(),status:QY,ttl:k([P(),oa()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Fa(P()),statusMessage:Fa(A())}),eX=gY.extend({task:$Y}),tX=mY.merge($Y),nX=hY.extend({method:D(`notifications/tasks/status`),params:tX}),rX=pY.extend({method:D(`tasks/get`),params:uY.extend({taskId:A()})}),iX=gY.merge($Y),aX=pY.extend({method:D(`tasks/result`),params:uY.extend({taskId:A()})});gY.loose();const oX=XY.extend({method:D(`tasks/list`)}),sX=ZY.extend({tasks:N($Y)}),cX=pY.extend({method:D(`tasks/cancel`),params:uY.extend({taskId:A()})}),lX=gY.merge($Y),uX=O({uri:A(),mimeType:Fa(A()),_meta:j(A(),E()).optional()}),dX=uX.extend({text:A()}),fX=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),pX=uX.extend({blob:fX}),mX=wa([`user`,`assistant`]),hX=O({audience:N(mX).optional(),priority:P().min(0).max(1).optional(),lastModified:no({offset:!0}).optional()}),gX=O({...MY.shape,...jY.shape,uri:A(),description:Fa(A()),mimeType:Fa(A()),size:Fa(P()),annotations:hX.optional(),_meta:Fa(Ua({}))}),_X=O({...MY.shape,...jY.shape,uriTemplate:A(),description:Fa(A()),mimeType:Fa(A()),annotations:hX.optional(),_meta:Fa(Ua({}))}),vX=XY.extend({method:D(`resources/list`)}),yX=ZY.extend({resources:N(gX)}),bX=XY.extend({method:D(`resources/templates/list`)}),xX=ZY.extend({resourceTemplates:N(_X)}),SX=uY.extend({uri:A()}),CX=SX,wX=pY.extend({method:D(`resources/read`),params:CX}),TX=gY.extend({contents:N(k([dX,pX]))}),EX=hY.extend({method:D(`notifications/resources/list_changed`),params:mY.optional()}),DX=SX,OX=pY.extend({method:D(`resources/subscribe`),params:DX}),kX=SX,AX=pY.extend({method:D(`resources/unsubscribe`),params:kX}),jX=mY.extend({uri:A()}),MX=hY.extend({method:D(`notifications/resources/updated`),params:jX}),NX=O({name:A(),description:Fa(A()),required:Fa(M())}),PX=O({...MY.shape,...jY.shape,description:Fa(A()),arguments:Fa(N(NX)),_meta:Fa(Ua({}))}),FX=XY.extend({method:D(`prompts/list`)}),IX=ZY.extend({prompts:N(PX)}),LX=uY.extend({name:A(),arguments:j(A(),A()).optional()}),RX=pY.extend({method:D(`prompts/get`),params:LX}),zX=O({type:D(`text`),text:A(),annotations:hX.optional(),_meta:j(A(),E()).optional()}),BX=O({type:D(`image`),data:fX,mimeType:A(),annotations:hX.optional(),_meta:j(A(),E()).optional()}),VX=O({type:D(`audio`),data:fX,mimeType:A(),annotations:hX.optional(),_meta:j(A(),E()).optional()}),HX=O({type:D(`tool_use`),name:A(),id:A(),input:j(A(),E()),_meta:j(A(),E()).optional()}),UX=O({type:D(`resource`),resource:k([dX,pX]),annotations:hX.optional(),_meta:j(A(),E()).optional()}),WX=k([zX,BX,VX,gX.extend({type:D(`resource_link`)}),UX]),GX=O({role:mX,content:WX}),KX=gY.extend({description:A().optional(),messages:N(GX)}),qX=hY.extend({method:D(`notifications/prompts/list_changed`),params:mY.optional()}),JX=O({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),YX=O({taskSupport:wa([`required`,`optional`,`forbidden`]).optional()}),XX=O({...MY.shape,...jY.shape,description:A().optional(),inputSchema:O({type:D(`object`),properties:j(A(),iY).optional(),required:N(A()).optional()}).catchall(E()),outputSchema:O({type:D(`object`),properties:j(A(),iY).optional(),required:N(A()).optional()}).catchall(E()).optional(),annotations:JX.optional(),execution:YX.optional(),_meta:j(A(),E()).optional()}),ZX=XY.extend({method:D(`tools/list`)}),QX=ZY.extend({tools:N(XX)}),$X=gY.extend({content:N(WX).default([]),structuredContent:j(A(),E()).optional(),isError:M().optional()});$X.or(gY.extend({toolResult:E()}));const eZ=dY.extend({name:A(),arguments:j(A(),E()).optional()}),tZ=pY.extend({method:D(`tools/call`),params:eZ}),nZ=hY.extend({method:D(`notifications/tools/list_changed`),params:mY.optional()});O({autoRefresh:M().default(!0),debounceMs:P().int().nonnegative().default(300)});const rZ=wa([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),iZ=uY.extend({level:rZ}),aZ=pY.extend({method:D(`logging/setLevel`),params:iZ}),oZ=mY.extend({level:rZ,logger:A().optional(),data:E()}),sZ=hY.extend({method:D(`notifications/message`),params:oZ}),cZ=O({hints:N(O({name:A().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),lZ=O({mode:wa([`auto`,`required`,`none`]).optional()}),uZ=O({type:D(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(WX).default([]),structuredContent:O({}).loose().optional(),isError:M().optional(),_meta:j(A(),E()).optional()}),dZ=za(`type`,[zX,BX,VX]),fZ=za(`type`,[zX,BX,VX,HX,uZ]),pZ=O({role:mX,content:k([fZ,N(fZ)]),_meta:j(A(),E()).optional()}),mZ=dY.extend({messages:N(pZ),modelPreferences:cZ.optional(),systemPrompt:A().optional(),includeContext:wa([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(A()).optional(),metadata:iY.optional(),tools:N(XX).optional(),toolChoice:lZ.optional()}),hZ=pY.extend({method:D(`sampling/createMessage`),params:mZ}),gZ=gY.extend({model:A(),stopReason:Fa(wa([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:mX,content:dZ}),_Z=gY.extend({model:A(),stopReason:Fa(wa([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:mX,content:k([fZ,N(fZ)])}),vZ=O({type:D(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),yZ=O({type:D(`string`),title:A().optional(),description:A().optional(),minLength:P().optional(),maxLength:P().optional(),format:wa([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),bZ=O({type:wa([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),xZ=O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),SZ=O({type:D(`string`),title:A().optional(),description:A().optional(),oneOf:N(O({const:A(),title:A()})),default:A().optional()}),CZ=k([k([O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),k([xZ,SZ]),k([O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({type:D(`string`),enum:N(A())}),default:N(A()).optional()}),O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({anyOf:N(O({const:A(),title:A()}))}),default:N(A()).optional()})])]),vZ,yZ,bZ]),wZ=k([dY.extend({mode:D(`form`).optional(),message:A(),requestedSchema:O({type:D(`object`),properties:j(A(),CZ),required:N(A()).optional()})}),dY.extend({mode:D(`url`),message:A(),elicitationId:A(),url:A().url()})]),TZ=pY.extend({method:D(`elicitation/create`),params:wZ}),EZ=mY.extend({elicitationId:A()}),DZ=hY.extend({method:D(`notifications/elicitation/complete`),params:EZ}),OZ=gY.extend({action:wa([`accept`,`decline`,`cancel`]),content:qa(e=>e===null?void 0:e,j(A(),k([A(),P(),M(),N(A())])).optional())}),kZ=O({type:D(`ref/resource`),uri:A()}),AZ=O({type:D(`ref/prompt`),name:A()}),jZ=uY.extend({ref:k([AZ,kZ]),argument:O({name:A(),value:A()}),context:O({arguments:j(A(),A()).optional()}).optional()}),MZ=pY.extend({method:D(`completion/complete`),params:jZ});function NZ(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function PZ(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const FZ=gY.extend({completion:Ua({values:N(A()).max(100),total:Fa(P().int()),hasMore:Fa(M())})}),IZ=O({uri:A().startsWith(`file://`),name:A().optional(),_meta:j(A(),E()).optional()}),LZ=pY.extend({method:D(`roots/list`),params:uY.optional()}),RZ=gY.extend({roots:N(IZ)}),zZ=hY.extend({method:D(`notifications/roots/list_changed`),params:mY.optional()});k([GY,zY,MZ,aZ,RX,FX,vX,bX,wX,OX,AX,tZ,ZX,rX,aX,oX,cX]),k([AY,JY,UY,zZ,nX]),k([OY,gZ,_Z,OZ,RZ,iX,sX,eX]),k([GY,hZ,TZ,LZ,rX,aX,oX,cX]),k([AY,JY,sZ,MX,EX,nZ,qX,nX,DZ]),k([OY,HY,FZ,KX,IX,yX,xX,TX,$X,QX,iX,sX,eX]);var BZ=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===wY.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new VZ(e.elicitations,n)}return new e(t,n,r)}},VZ=class extends BZ{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(wY.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function HZ(e){return e===`completed`||e===`failed`||e===`cancelled`}const UZ=Symbol(`Let zodToJsonSchema decide on which parser to use`),WZ={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`},GZ=e=>typeof e==`string`?{...WZ,name:e}:{...WZ,...e},KZ=e=>{let t=GZ(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 qZ(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function JZ(e,t,n,r,i){e[t]=n,qZ(e,t,r,i)}const YZ=(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 XZ(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?YZ(t,e.currentPath):t.join(`/`)}}function ZZ(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=VQ(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&JZ(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&JZ(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(JZ(n,`minItems`,e.exactLength.value,e.exactLength.message,t),JZ(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function QZ(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?JZ(n,`minimum`,r.value,r.message,t):JZ(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),JZ(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?JZ(n,`maximum`,r.value,r.message,t):JZ(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),JZ(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:JZ(n,`multipleOf`,r.value,r.message,t);break}return n}function $Z(){return{type:`boolean`}}function eQ(e,t){return VQ(e.type._def,t)}const tQ=(e,t)=>VQ(e.innerType._def,t);function nQ(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>nQ(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 rQ(e,t)}}const rQ=(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`:JZ(n,`minimum`,r.value,r.message,t);break;case`max`:JZ(n,`maximum`,r.value,r.message,t);break}return n};function iQ(e,t){return{...VQ(e.innerType._def,t),default:e.defaultValue()}}function aQ(e,t){return t.effectStrategy===`input`?VQ(e.schema._def,t):XZ(t)}function oQ(e){return{type:`string`,enum:Array.from(e.values)}}const sQ=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function cQ(e,t){let n=[VQ(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),VQ(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(sQ(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 lQ(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 uQ;const dQ={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:()=>(uQ===void 0&&(uQ=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),uQ),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 fQ(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:JZ(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:JZ(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`:gQ(n,`email`,r.message,t);break;case`format:idn-email`:gQ(n,`idn-email`,r.message,t);break;case`pattern:zod`:_Q(n,dQ.email,r.message,t);break}break;case`url`:gQ(n,`uri`,r.message,t);break;case`uuid`:gQ(n,`uuid`,r.message,t);break;case`regex`:_Q(n,r.regex,r.message,t);break;case`cuid`:_Q(n,dQ.cuid,r.message,t);break;case`cuid2`:_Q(n,dQ.cuid2,r.message,t);break;case`startsWith`:_Q(n,RegExp(`^${pQ(r.value,t)}`),r.message,t);break;case`endsWith`:_Q(n,RegExp(`${pQ(r.value,t)}$`),r.message,t);break;case`datetime`:gQ(n,`date-time`,r.message,t);break;case`date`:gQ(n,`date`,r.message,t);break;case`time`:gQ(n,`time`,r.message,t);break;case`duration`:gQ(n,`duration`,r.message,t);break;case`length`:JZ(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),JZ(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:_Q(n,RegExp(pQ(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&gQ(n,`ipv4`,r.message,t),r.version!==`v4`&&gQ(n,`ipv6`,r.message,t);break;case`base64url`:_Q(n,dQ.base64url,r.message,t);break;case`jwt`:_Q(n,dQ.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&_Q(n,dQ.ipv4Cidr,r.message,t),r.version!==`v4`&&_Q(n,dQ.ipv6Cidr,r.message,t);break;case`emoji`:_Q(n,dQ.emoji(),r.message,t);break;case`ulid`:_Q(n,dQ.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:gQ(n,`binary`,r.message,t);break;case`contentEncoding:base64`:JZ(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:_Q(n,dQ.base64,r.message,t);break}break;case`nanoid`:_Q(n,dQ.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function pQ(e,t){return t.patternStrategy===`escape`?hQ(e):e}const mQ=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function hQ(e){let t=``;for(let n=0;n<e.length;n++)mQ.has(e[n])||(t+=`\\`),t+=e[n];return t}function gQ(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}}})):JZ(e,`format`,t,n,r)}function _Q(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:vQ(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):JZ(e,`pattern`,vQ(t,r),n,r)}function vQ(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
|
|
1226
1226
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
1227
1227
|
]))`;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 yQ(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]:VQ(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??XZ(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:VQ(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}=fQ(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}=eQ(e.keyType._def,t);return{...n,propertyNames:i}}return n}function bQ(e,t){return t.mapStrategy===`record`?yQ(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[VQ(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||XZ(t),VQ(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||XZ(t)],minItems:2,maxItems:2}}}function xQ(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 SQ(e){return e.target===`openAi`?void 0:{not:XZ({...e,currentPath:[...e.currentPath,`not`]})}}function CQ(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const wQ={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function TQ(e,t){if(t.target===`openApi3`)return EQ(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in wQ&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=wQ[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 EQ(e,t)}const EQ=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>VQ(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 DQ(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:wQ[e.innerType._def.typeName],nullable:!0}:{type:[wQ[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=VQ(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=VQ(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function OQ(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`,qZ(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?JZ(n,`minimum`,r.value,r.message,t):JZ(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),JZ(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?JZ(n,`maximum`,r.value,r.message,t):JZ(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),JZ(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:JZ(n,`multipleOf`,r.value,r.message,t);break}return n}function kQ(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=jQ(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=VQ(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=AQ(e,t);return o!==void 0&&(r.additionalProperties=o),r}function AQ(e,t){if(e.catchall._def.typeName!==`ZodNever`)return VQ(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 jQ(e){try{return e.isOptional()}catch{return!0}}const MQ=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return VQ(e.innerType._def,t);let n=VQ(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:XZ(t)},n]}:XZ(t)},NQ=(e,t)=>{if(t.pipeStrategy===`input`)return VQ(e.in._def,t);if(t.pipeStrategy===`output`)return VQ(e.out._def,t);let n=VQ(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,VQ(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function PQ(e,t){return VQ(e.type._def,t)}function FQ(e,t){let n={type:`array`,uniqueItems:!0,items:VQ(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&JZ(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&JZ(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function IQ(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>VQ(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:VQ(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>VQ(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function LQ(e){return{not:XZ(e)}}function RQ(e){return XZ(e)}const zQ=(e,t)=>VQ(e.innerType._def,t),BQ=(e,t,n)=>{switch(t){case Z.ZodString:return fQ(e,n);case Z.ZodNumber:return OQ(e,n);case Z.ZodObject:return kQ(e,n);case Z.ZodBigInt:return QZ(e,n);case Z.ZodBoolean:return $Z();case Z.ZodDate:return nQ(e,n);case Z.ZodUndefined:return LQ(n);case Z.ZodNull:return CQ(n);case Z.ZodArray:return ZZ(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return TQ(e,n);case Z.ZodIntersection:return cQ(e,n);case Z.ZodTuple:return IQ(e,n);case Z.ZodRecord:return yQ(e,n);case Z.ZodLiteral:return lQ(e,n);case Z.ZodEnum:return oQ(e);case Z.ZodNativeEnum:return xQ(e);case Z.ZodNullable:return DQ(e,n);case Z.ZodOptional:return MQ(e,n);case Z.ZodMap:return bQ(e,n);case Z.ZodSet:return FQ(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return PQ(e,n);case Z.ZodNaN:case Z.ZodNever:return SQ(n);case Z.ZodEffects:return aQ(e,n);case Z.ZodAny:return XZ(n);case Z.ZodUnknown:return RQ(n);case Z.ZodDefault:return iQ(e,n);case Z.ZodBranded:return eQ(e,n);case Z.ZodReadonly:return zQ(e,n);case Z.ZodCatch:return tQ(e,n);case Z.ZodPipeline:return NQ(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>void 0)(t)}};function VQ(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==UZ)return i}if(r&&!n){let e=HQ(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=BQ(e,e.typeName,t),o=typeof a==`function`?VQ(a(),t):a;if(o&&UQ(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const HQ=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:YZ(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`),XZ(t)):t.$refStrategy===`seen`?XZ(t):void 0}},UQ=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),WQ=(e,t)=>{let n=KZ(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:VQ(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??XZ(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=VQ(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??XZ(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 GQ(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function KQ(e,t){return GJ(e)?Pa(e,{target:GQ(t?.target),io:t?.pipeStrategy??`input`}):WQ(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function qQ(e){let t=YJ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=eY(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function JQ(e,t){let n=qJ(e,t);if(!n.success)throw n.error;return n.data}var YQ=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(AY,e=>{this._oncancel(e)}),this.setNotificationHandler(JY,e=>{this._onprogress(e)}),this.setRequestHandler(GY,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(rX,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new BZ(wY.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(aX,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 BZ(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 BZ(wY.InvalidParams,`Task not found: ${r}`);if(!HZ(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(HZ(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[rY]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(oX,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 BZ(wY.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(cX,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new BZ(wY.InvalidParams,`Task not found: ${e.params.taskId}`);if(HZ(n.status))throw new BZ(wY.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 BZ(wY.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof BZ?e:new BZ(wY.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),BZ.fromError(wY.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),CY(e)||EY(e)?this._onresponse(e):yY(e)?this._onrequest(e,t):xY(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=BZ.fromError(wY.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?.[rY]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:wY.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=fY(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 BZ(wY.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:wY.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),CY(e)?n(e):n(new BZ(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(CY(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),CY(e)?r(e):r(BZ.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 BZ?e:new BZ(wY.InternalError,String(e))}}return}let i;try{let r=await this.request(e,eX,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new BZ(wY.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},HZ(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new BZ(wY.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new BZ(wY.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 BZ?e:new BZ(wY.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||{},[rY]: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 BZ?e:new BZ(wY.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=qJ(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(BZ.fromError(wY.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},iX,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},sX,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},lX,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||{},[rY]: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||{},[rY]: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||{},[rY]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=qQ(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=JQ(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=qQ(e);this._notificationHandlers.set(n,n=>{let r=JQ(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`&&yY(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new BZ(wY.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 BZ(wY.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new BZ(wY.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 BZ(wY.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=nX.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),HZ(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 BZ(wY.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(HZ(a.status))throw new BZ(wY.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=nX.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),HZ(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function XQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ZQ(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];XQ(a)&&XQ(i)?n[r]={...a,...i}:n[r]=i}return n}var QQ=t(T(),1),$Q=t(tt(),1);function e$(){let e=new QQ.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$Q.default)(e),e}var t$=class{constructor(e){this._ajv=e??e$()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},n$=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},gZ,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},OZ,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function r$(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function i$(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var a$=class extends YQ{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(rZ.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new t$,this.setRequestHandler(zY,e=>this._oninitialize(e)),this.setNotificationHandler(UY,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(aZ,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=rZ.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new n$(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=ZQ(this._capabilities,e)}setRequestHandler(e,t){let n=YJ(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(GJ(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=qJ(tZ,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new BZ(wY.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=qJ(eX,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new BZ(wY.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=qJ($X,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new BZ(wY.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){i$(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&r$(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nY.includes(t)?t:tY,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},OY)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},_Z,t):this.request({method:`sampling/createMessage`,params:e},gZ,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},OZ,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},OZ,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new BZ(wY.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof BZ?e:new BZ(wY.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},RZ,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const o$=Symbol.for(`mcp.completable`);function s$(e){return!!e&&typeof e==`object`&&o$ in e}function c$(e){return e[o$]?.complete}var l$;(function(e){e.Completable=`McpCompletable`})(l$||={});const u$=/^[A-Za-z0-9._-]{1,128}$/;function d$(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!u$.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function f$(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function p$(e){let t=d$(e);return f$(e,t.warnings),t.isValid}var m$=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},h$=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new a$(e,t)}get experimental(){return this._experimental||={tasks:new m$(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(S$(ZX)),this.server.assertCanSetRequestHandler(S$(tZ)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ZX,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=XJ(t.inputSchema);return e?KQ(e,{strictUnions:!0,pipeStrategy:`input`}):g$})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=XJ(t.outputSchema);e&&(n.outputSchema=KQ(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(tZ,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new BZ(wY.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new BZ(wY.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new BZ(wY.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new BZ(wY.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof BZ&&e.code===wY.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await JJ(XJ(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=ZJ(`error`in r?r.error:`Unknown error`);throw new BZ(wY.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new BZ(wY.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await JJ(XJ(e.outputSchema),t.structuredContent);if(!r.success){let e=ZJ(`error`in r?r.error:`Unknown error`);throw new BZ(wY.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new BZ(wY.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(S$(MZ)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(MZ,async e=>{switch(e.params.ref.type){case`ref/prompt`:return NZ(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return PZ(e),this.handleResourceCompletion(e,e.params.ref);default:throw new BZ(wY.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new BZ(wY.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new BZ(wY.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return w$;let r=YJ(n.argsSchema)?.[e.params.argument.name];if(!s$(r))return w$;let i=c$(r);return i?C$(await i(e.params.argument.value,e.params.context)):w$}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return w$;throw new BZ(wY.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?C$(await r(e.params.argument.value,e.params.context)):w$}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(S$(vX)),this.server.assertCanSetRequestHandler(S$(bX)),this.server.assertCanSetRequestHandler(S$(wX)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(vX,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(bX,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(wX,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new BZ(wY.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new BZ(wY.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(S$(FX)),this.server.assertCanSetRequestHandler(S$(RX)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(FX,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?x$(t.argsSchema):void 0}))})),this.server.setRequestHandler(RX,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new BZ(wY.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new BZ(wY.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await JJ(XJ(n.argsSchema),e.params.arguments);if(!r.success){let t=ZJ(`error`in r?r.error:`Unknown error`);throw new BZ(wY.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:KJ(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=KJ(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>s$(e instanceof ja?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){p$(e);let l={title:t,description:n,inputSchema:b$(r),outputSchema:b$(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&p$(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=KJ(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=KJ(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(y$(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!y$(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const g$={type:`object`,properties:{}};function _$(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function v$(e){return`_def`in e||`_zod`in e||_$(e)}function y$(e){return typeof e!=`object`||!e||v$(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(_$)}function b$(e){if(e){if(y$(e))return KJ(e);if(!v$(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function x$(e){let t=YJ(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:QJ(t),required:!$J(t)})):[]}function S$(e){let t=YJ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=eY(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function C$(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const w$={completion:{values:[],hasMore:!1}};var T$=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},E$=e=>e instanceof T$?e:new T$(e.message,{cause:e}),D$=global.Request,O$=class extends D${constructor(e,t){typeof e==`object`&&M$ in e&&(e=e[M$]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},k$=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},A$=Symbol(`wrapBodyStream`),j$=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new O$(t,a);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[A$]){let e;a.body=new ReadableStream({async pull(t){try{e||=tu.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=tu.toWeb(r);return new O$(t,a)},M$=Symbol(`getRequestCache`),N$=Symbol(`requestCache`),P$=Symbol(`incomingKey`),F$=Symbol(`urlKey`),I$=Symbol(`headersKey`),L$=Symbol(`abortControllerKey`),R$={get method(){return this[P$].method||`GET`},get url(){return this[F$]},get headers(){return this[I$]||=k$(this[P$])},[Symbol(`getAbortController`)](){return this[M$](),this[L$]},[M$](){return this[L$]||=new AbortController,this[N$]||=j$(this.method,this[F$],this.headers,this[P$],this[L$])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(R$,e,{get(){return this[M$]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(R$,e,{value:function(){return this[M$]()[e]()}})}),Object.defineProperty(R$,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[N$]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(R$,O$.prototype);var z$=(e,t)=>{let n=Object.create(R$);n[P$]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof ou)throw new T$(`Absolute URL for :path is not allowed in HTTP/2`);try{n[F$]=new URL(r).href}catch(e){throw new T$(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof ou?e.authority:e.headers.host)||t;if(!i)throw new T$(`Missing host header`);let a;if(e instanceof ou){if(a=e.scheme,!(a===`http`||a===`https`))throw new T$(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;let o=new URL(`${a}://${i}${r}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,``))throw new T$(`Invalid host header`);return n[F$]=o.href,n},B$=Symbol(`responseCache`),V$=Symbol(`getResponseCache`),H$=Symbol(`cache`),U$=global.Response,W$=class e{#e;#t;[V$](){return delete this[H$],this[B$]||=new U$(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[B$];if(e){this.#t=e,this[V$]();return}else this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[H$]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[H$];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[V$]().headers}get status(){return this[H$]?.[0]??this[V$]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(W$.prototype,e,{get(){return this[V$]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(W$.prototype,e,{value:function(){return this[V$]()[e]()}})}),Object.defineProperty(W$.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[B$]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(W$,U$),Object.setPrototypeOf(W$.prototype,U$.prototype);async function G$(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function K$(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function q$(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:K$(e.getReader(),t)}var J$=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Y$=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Oee);var X$=Symbol(`outgoingEnded`),Z$=Symbol(`incomingDraining`),Q$=500,$$=64*1024*1024,e1=e=>{let t=e;if(e.destroyed||t[Z$])return;if(t[Z$]=!0,e instanceof ou){try{e.stream?.close?.(Ree.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(a),e.off(`data`,o),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},a=setTimeout(i,Q$);a.unref?.();let o=e=>{n+=e.length,n>$$&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},t1=()=>new Response(null,{status:400}),n1=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),r1=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},i1=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},a1=async(e,t)=>{let[n,r,i]=e[H$],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=J$(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=J$(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(i1(t),await q$(r,t)?.catch(e=>r1(e,t))),t[X$]?.()},o1=e=>typeof e.then==`function`,s1=async(e,t,n={})=>{if(o1(e))if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(n1);if(H$ in e)return a1(e,t);let r=J$(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await G$(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&i1(t),await K$(n,t,o))}else r[Y$]||(t.writeHead(e.status,r),t.end());t[X$]?.()},c1=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==O$&&(Object.defineProperty(global,`Request`,{value:O$}),Object.defineProperty(global,`Response`,{value:W$})),async(r,i)=>{let a,o;try{o=z$(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[A$]=!0,r.on(`end`,()=>{s=!0}),r instanceof ou&&(i[X$]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{e1(r)})})}),i.on(`finish`,()=>{s||e1(r)})),i.on(`close`,()=>{o[L$]&&(r.errored?o[L$].abort(r.errored.toString()):i.writableFinished||o[L$].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{e1(r)})})}),a=e(o,{incoming:r,outgoing:i}),H$ in a)return a1(a,i)}catch(e){if(a)return r1(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:E$(e)),!a)return}else a=o?n1(e):t1()}try{return await s1(a,i,t)}catch(e){return r1(e,i)}}},l1=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:i,id:null}),{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e)){this.onerror?.(Error(`Failed replay events`));try{i.close()}catch{}}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
|
|
1228
1228
|
`;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>DY.parse(e)):[DY.parse(a)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(BY);if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(yY)){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>BY(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)yY(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)yY(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;yY(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!nY.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${nY.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${nY.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((CY(e)||EY(e))&&(n=e.id),n===void 0){if(CY(e)||EY(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(CY(e)||EY(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},u1=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new l1(e),this._requestListener=c1(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,n){let r=e.auth;await c1(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};const d1=`x-ok-connection-id`;function f1(e,t){let n=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return n?n.slice(0,128):t}function p1(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!m1(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=Va(i.error);throw new BZ(wY.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function m1(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const h1=2e3,g1=2e3,_1=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function v1(e){return _1.some(t=>t.test(e))}function y1(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return sl(e)?e:null}catch{return null}}function b1(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&sl(a)?a:null}function x1(e){let t=[];for(let n of e.split(`
|
|
@@ -1977,7 +1977,7 @@ ${e.terminator}`}function Iue(e){return`(${P6(e.body)})${N6(e.redirections)}`}fu
|
|
|
1977
1977
|
`)}),_=f>0?[`… and ${f} more file${f===1?``:`s`} with problems`]:[];return JD([h,...g,..._,"Auto-fix a single file with `lint({ document, fix: true })` (attributed, live preview). Violations that resist auto-fix need content edits."].join(`
|
|
1978
1978
|
`),p)}const tfe=["[Requires: Hocuspocus server] Move or rename a document, folder, or asset through the managed flow at `POST /api/rename-path`. Works for all three — the tool probes the content directory to decide. Inbound wiki-links plus supported inline Markdown links are rewritten across affected docs; renamed assets are reported.",``,`**Parameters:**`,"- `from` — Current path. Doc: docName (trailing `.md`/`.mdx` stripped). Folder: relative path, no leading/trailing slash. Asset: the file path incl. extension.","- `to` — New path. Same shape as `from`.",'- `template` — Move/rename a TEMPLATE instead of a doc/folder/asset: `{ from: "<folder>/<name>", to: "<folder>/<name>" }` (nested — a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc). Mutually exclusive with flat `from`/`to`. Inherited templates are not moved (move the local copy / the owning folder); templates carry no inbound links, so nothing is rewritten.','- `skill` — Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }` (nested). Within one level (omit `toScope`, or `toScope` === `scope`): renames `.ok/skills/<from>/` → `.ok/skills/<to>/` and keeps the SKILL.md `name` in sync. ACROSS levels (`toScope` differs from `scope`, e.g. `scope: "project"` + `toScope: "global"`): moves the skill between the Project level (this KB) and the Global level (`~/.ok/skills`); history does NOT transfer (it re-creates fresh in the new level) and the moved skill lands as an un-projected Draft. Run `install` afterward to (re)project it. Mutually exclusive with flat `from`/`to`.','- `summary` — Optional one-line user-outcome (≤80 chars). If omitted, defaults to "Renamed X → Y". Avoid secrets or PII — persisted to git history.',``,"**Errors:** 400 — invalid path / excluded by `.gitignore`/`.okignore`; 404 — source does not exist; 409 — destination already exists (`colliding[]` returned)."].join(`
|
|
1979
1979
|
`);function nfe(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromDocName:t,toDocName:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromDocName:t,toDocName:n}]:[]}):[]}function rfe(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{docName:t,rewrites:n}=e;return typeof t==`string`&&typeof n==`number`?[{docName:t,rewrites:n}]:[]}):[]}function ife(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let{fromPath:t,toPath:n}=e;return typeof t==`string`&&typeof n==`string`?[{fromPath:t,toPath:n}]:[]}):[]}function e8(e){return!(typeof e!=`string`||e.length===0||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`..`))}function t8(e,t,n=`${t}s`){return e===1?t:n}function afe(e,t){let n=PD(e,t);if(!n.ok)return null;let r=n.abs;if(B(r))try{let e=jl(r);if(e.isDirectory())return`folder`;if(e.isFile())return r.endsWith(`.md`)||r.endsWith(`.mdx`)?`file`:`asset`}catch(e){let t=e.code;if(t===`EACCES`||t===`EPERM`)return`file`}for(let e of ve)if(B(`${r}${e}`))return`file`;return null}function ofe(e,t){e.registerTool(`move`,{description:tfe,inputSchema:{from:A().optional().describe(`Current path of a document, folder, or asset (auto-detected).`),to:A().optional().describe(`New path. All inbound wiki-links + inline links are rewritten automatically.`),template:O({from:A(),to:A()}).optional().describe('Move/rename a TEMPLATE instead: `{ from: "<folder>/<name>", to: "<folder>/<name>" }`. Nested because a flat path cannot disambiguate a template under `.ok/templates/` from a same-named doc. Mutually exclusive with flat `from`/`to`.'),skill:O({from:A(),to:A(),scope:wa(Yn).optional().describe('Source level (default "project"). "project" = this KB\'s `.ok/skills/`; "global" = the Global `~/.ok/skills/`.'),toScope:wa(Yn).optional().describe("Destination level. Omit (or set equal to `scope`) for a within-level rename. Set to the OTHER level to move the skill across levels (project↔global) — history does not transfer and it lands as a Draft.")}).optional().describe('Move/rename a SKILL: `{ from: "<name>", to: "<name>", scope?, toScope? }`. Within one level: renames `.ok/skills/<name>/` and keeps SKILL.md `name` in sync. Across levels (`toScope` differs from `scope`): moves between Project and Global, resetting history. Mutually exclusive with flat `from`/`to`.'),summary:LD.describe(`Optional one-line user-outcome (≤80 chars). Defaults to "Renamed X → Y". Persisted to git history.`),cwd:A().optional().describe(ID)},outputSchema:qD({ok:M().describe(`Whether the move succeeded.`),kind:wa([`file`,`folder`,`asset`,`template`,`skill`]).optional().describe("What was moved (`file`/`folder`/`asset` auto-detected from `from`; `template`/`skill` when that nested target was used)."),committed:M().optional().describe("Template move only: `true` = tracked `git mv` (history preserved), `false` = plain disk rename (untracked / local-only `.ok/`)."),renamed:N(O({fromDocName:A(),toDocName:A()})).optional().describe(`docName remappings performed.`),rewrittenDocs:UD.optional().describe(`Docs whose inbound links were rewritten.`),renamedAssets:UD.optional().describe(`Referenced assets that were moved alongside.`),previewUrls:j(A(),A()).optional().describe(`Route-only preview URL per new docName.`),previewUrlSource:BD,previousPreviewUrl:VD,summary:HD.optional(),error:A().optional().describe("Present when `ok` is false."),colliding:UD.optional().describe(`On a 409 collision: the conflicting from→to pairs.`),crossScope:M().optional().describe("Skill cross-level move only: `true` when the skill was moved between the Project and Global levels (history reset; lands as a Draft — re-run `install`)."),bothScopes:M().optional().describe("Skill cross-level move only: `true` when the destination write succeeded but deleting the source failed, so the skill now exists in BOTH levels and the source copy must be removed manually.")})},async e=>{let n=await $D(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return K(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n;if(!a)return K(YD,!0);if(e.template!==void 0){if(e.from!==void 0||e.to!==void 0)return K("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `template: { from, to }` — not both.",!0);let n=q0(e.template.from);if(!n.ok)return K(`Error: ${n.error}`,!0);let r=q0(e.template.to);if(!r.ok)return K(`Error: ${r.error}`,!0);let i=await aO(a,`/api/template`,{fromFolder:n.folder,fromName:n.name,toFolder:r.folder,toName:r.name,...e.summary===void 0?{}:{summary:e.summary},...FD(t.identityRef?.current)});if(!i.ok){let e=typeof i.error==`string`?i.error:`Template move failed`;return JD(`Error: ${e}`,{ok:!1,kind:`template`,error:e},!0)}let o=i.committed===!0,s=typeof i.from==`string`?i.from:e.template.from,c=typeof i.to==`string`?i.to:e.template.to;return JD(`${o?`Renamed`:`Moved`} template ${s} → ${c}.${o?``:" (Untracked `.ok/` — moved on disk without git history.)"}`,{ok:!0,kind:`template`,committed:o})}if(e.skill!==void 0){if(e.from!==void 0||e.to!==void 0)return K("Error: pass EITHER flat `from`/`to` (document/folder/asset) OR `skill: { from, to }` — not both.",!0);let n=e.skill.scope??`project`;return e.skill.toScope!==void 0&&e.skill.toScope!==n?c2(a,{fromScope:n,toScope:e.skill.toScope,fromName:e.skill.from,toName:e.skill.to,summary:e.summary,identity:t.identityRef?.current}):s2(a,{fromName:e.skill.from,toName:e.skill.to,scope:e.skill.scope,summary:e.summary,identity:t.identityRef?.current})}if(e.from===void 0||e.to===void 0)return K("Error: provide both `from` and `to` (or use `template: { from, to }` to move a template, or `skill: { from, to }` to move/rename a skill).",!0);let o=L(r,i.content.dir),s=afe(o,e.from);if(s===null){let t=q0(e.from);return t.ok&&B(L(o,t.folder,`.ok`,`templates`,`${t.name}.md`))?K(`Error: \`${e.from}\` is a template, not a doc/folder/asset. Move it with \`move({ template: { from: "${e.from}", to: "<folder>/<newName>" } })\`.`,!0):K(`Error: \`${e.from}\` does not exist as a doc, folder, or asset under the content directory.`,!0)}let c=e.from,l=e.to;if(s===`file`){let t=tO(e.from);if(!t.ok)return K(t.error,!0);let n=tO(e.to);if(!n.ok)return K(n.error,!0);c=t.docName,l=n.docName}else if(s===`folder`&&(!e8(e.from)||!e8(e.to)))return K("Error: folder `from`/`to` must be relative paths with no leading/trailing slash.",!0);let u=await aO(a,`/api/rename-path`,{kind:s,fromPath:c,toPath:l,...e.summary===void 0?{}:{summary:e.summary},...FD(t.identityRef?.current)});if(!u.ok){let e=u.error,t=cO(u.colliding),n={ok:!1,error:e,...t.length>0?{colliding:t}:{}};return JD(`Error: ${e}`,n,!0)}let d=nfe(u.renamed),f=rfe(u.rewrittenDocs),p=ife(u.renamedAssets),m={config:t.config,resolveCwd:t.resolveCwd},h={},g,_;if(s===`file`){let e=await M0(l,m,r),t=await M0(c,m,r);e&&(h[l]=e.url,g=e.source),t&&(_=t.url)}else if(s===`folder`)for(let{toDocName:e}of d){let t=await M0(e,m,r);t&&(h[e]=t.url,g??=t.source)}let v=u.summary&&typeof u.summary==`object`?u.summary:void 0,y=typeof v?.hint==`string`?v.hint:void 0,b=[];if(s===`asset`)b.push(`Moved asset ${c} → ${l}.`);else if(s===`folder`)b.push(d.length===0?`No managed docs under ${e.from}/ — nothing to rename. Empty folders are not tracked.`:`Renamed folder ${e.from}/ → ${e.to}/ (${d.length} doc${d.length===1?``:`s`}, ${f.length} rewrite${f.length===1?``:`s`}).`);else{let e=d.map(({fromDocName:e,toDocName:t})=>`${e} -> ${t}`).join(`, `)||`${c} -> ${l}`,t=f.length===0?`No inbound links required updates.`:`Rewrote ${f.length} ${t8(f.length,`document`)}.`;b.push(`Renamed ${e}. ${t}`)}return p.length>0&&b.push(`Moved ${p.length} referenced ${t8(p.length,`asset`)}.`),y&&b.push(y),JD(b.join(`
|
|
1980
|
-
`),{ok:!0,kind:s,renamed:d,rewrittenDocs:f,...p.length>0?{renamedAssets:p}:{},...Object.keys(h).length>0?{previewUrls:h}:{},...g?{previewUrlSource:g}:{},..._?{previousPreviewUrl:_}:{},...v?{summary:v}:{}})})}const sfe=[`[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.`,``,`Three sections:`,"- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.","- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.",'- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed. **Inside SVG, route theme tokens through `style="..."` rather than presentation attributes** — `<circle style="fill: var(--chart-1)">` works; `<circle fill="var(--chart-1)">` silently falls back to black in Safari / older Chromium because CSS `var()` is not a valid SVG `<paint>` value per the W3C spec.',``,"External resources load directly: the preview iframe has open network access, so an embed can load external stylesheets, `fetch` live data, or pull map tiles / remote images / web fonts over `https:`. The iframe is a sandboxed null-origin frame — an embed can reach the network but never the knowledge base, cookies, or auth.",``,'Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',``,`**Parameters:**`,"- `components` (optional) — Canonical ids to expand to full JSX-form detail (max 32). Case-sensitive (`Callout` not `callout`). Returns `componentDetails` + `notFound`.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
1980
|
+
`),{ok:!0,kind:s,renamed:d,rewrittenDocs:f,...p.length>0?{renamedAssets:p}:{},...Object.keys(h).length>0?{previewUrls:h}:{},...g?{previewUrlSource:g}:{},..._?{previousPreviewUrl:_}:{},...v?{summary:v}:{}})})}const sfe=[`[Operates on registry data; no running OK server required] Return the OK authoring palette so a generated document reads as one coherent, themed artifact.`,``,`Three sections:`,"- `components` — the **markdown-native forms** OK auto-promotes into themed canonical components at parse time. Write `> [!NOTE]` (not `<Callout>`), `<details>` (not `<Accordion>`), ` ```mermaid `, `$x$`. Each entry carries a copy-ready `example` + `guidance`.","- `embedPatterns` — copy-ready ` ```html preview ` starters (chart, stat cards, custom SVG, interactive control) already wired to the theme tokens, so an embed tracks light/dark with no hand-picked colors.",'- `tokens` — the CSS custom properties injected into every preview iframe; reference them as `var(--chart-1)`, `var(--foreground)`, … inside an `html preview` embed. **Inside SVG, route theme tokens through `style="..."` rather than presentation attributes** — `<circle style="fill: var(--chart-1)">` works; `<circle fill="var(--chart-1)">` silently falls back to black in Safari / older Chromium because CSS `var()` is not a valid SVG `<paint>` value per the W3C spec.',``,"**These delimiters are live syntax in ordinary prose, not just inside the constructs above:** `==highlight==`, `$inline math$` / `$$block math$$`, `%%comment%%` and `<!-- comment -->` (both hidden from readers), `~~strikethrough~~`. An accidental pair silently formats — or, for the comment forms, HIDES — the text between it. To keep a pair literal, either wrap it in an inline code span (`` `==x==` ``, `` `$5` ``), which always works and reads as code, or backslash-escape either delimiter (`\\==x\\==`, `\\$5`, `\\%\\%note\\%\\%`, `\\<!-- note -->`) to keep it as running prose. `~~` is the exception: escape both tildes (`\\~\\~x\\~\\~`), because a one-sided `\\~~x~~` renders right but gets rewritten to the two-sided form on save.",``,"External resources load directly: the preview iframe has open network access, so an embed can load external stylesheets, `fetch` live data, or pull map tiles / remote images / web fonts over `https:`. The iframe is a sandboxed null-origin frame — an embed can reach the network but never the knowledge base, cookies, or auth.",``,'Pass `components: [ids]` to ALSO get the full JSX-form prop schema for specific canonicals (e.g. `palette({ components: ["Callout", "Tabs"] })`) — merged from the former `get_components`.',``,`**Parameters:**`,"- `components` (optional) — Canonical ids to expand to full JSX-form detail (max 32). Case-sensitive (`Callout` not `callout`). Returns `componentDetails` + `notFound`.","- `cwd` (optional) — Project root (see `cwd` description below)."].join(`
|
|
1981
1981
|
`),cfe={components:N(A().min(1)).max(32).optional().describe("Canonical ids to expand to full JSX-form detail (max 32, case-sensitive). Returns `componentDetails` + `notFound`."),cwd:A().optional().describe(ID)},lfe=qD({version:D(1).describe(`Schema version stamp — bump for breaking shape changes.`),components:N(O({id:A(),displayName:A(),description:A(),authoring:wa([`markdown`,`jsx`]).describe("`markdown` — write the markdown-native form OK auto-promotes; `jsx` — write the JSX tag directly (no markdown-native form exists)."),example:A().describe(`Copy-ready source for the authoring form.`),guidance:A().describe(`One line on when / how to use this construct.`)})).describe(`Canonical authoring constructs, keyed by the form an agent should write.`),embedPatterns:N(O({id:A(),title:A(),description:A(),snippet:A().describe("A complete, theme-wired ```html preview fenced block.")})).describe("Copy-ready themed `html preview` starters."),tokens:N(O({name:A().describe("CSS custom-property name, e.g. `--chart-1`."),light:A(),dark:A()})).describe("Theme tokens injected into every preview iframe — reference with `var(--name)`."),componentDetails:N(j(A(),E())).optional().describe("Full JSX-form prop schema for the requested `components` ids (when provided)."),notFound:N(A()).optional().describe("Requested `components` ids that did not match any canonical.")}),ufe=[{id:`Callout`,registryName:`Callout`,fallbackDisplayName:`Callout`,description:`Alert / admonition box in one of 15 themed type variants.`,authoring:`markdown`,example:`> [!NOTE]
|
|
1982
1982
|
> Body text. Swap NOTE for TIP, IMPORTANT, WARNING, CAUTION, …`,guidance:"Write the GFM alert form — OK auto-promotes it to a themed Callout. 15 types; append `+` / `-` (e.g. `> [!NOTE]+`) to make it foldable."},{id:`Accordion`,registryName:`Accordion`,fallbackDisplayName:`Accordion`,description:`Collapsible section with a clickable summary.`,authoring:`markdown`,example:`<details>
|
|
1983
1983
|
<summary>Section title</summary>
|
|
@@ -1990,7 +1990,9 @@ Block:
|
|
|
1990
1990
|
|
|
1991
1991
|
$$
|
|
1992
1992
|
\\int_0^1 x^2 \\, dx
|
|
1993
|
-
$$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-promotes it to Math."},{id:`
|
|
1993
|
+
$$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-promotes it to Math. `$` is live in ordinary prose too, so a currency pair like `Cost $5$ each` parses as math; write `` `$5` `` or `\\$5` to keep a literal dollar sign."},{id:`Highlight`,fallbackDisplayName:`Highlight`,description:`Marked / highlighted inline text.`,authoring:`markdown`,example:`The ==key phrase== stands out.`,guidance:"Write `==text==` — OK auto-promotes it to a highlight. `==` is live anywhere in prose, so to show a literal pair use an inline code span (`` `==x==` ``) or escape either side (`\\==x\\==`)."},{id:`Comment`,fallbackDisplayName:`Comment`,description:`Author-only note, hidden from the rendered document.`,authoring:`markdown`,example:`%%Not shown to readers.%%
|
|
1994
|
+
|
|
1995
|
+
<!-- Also not shown to readers. -->`,guidance:"Write `%%text%%` or `<!-- text -->` — both render hidden and are dropped from the clipboard. Because they are live in prose, an accidental pair HIDES the text between it; to show a literal pair use an inline code span (`` `%%x%%` ``) or escape either side (`\\%\\%x\\%\\%`)."},{id:`wiki-embed`,fallbackDisplayName:`Wiki embed`,description:`Inline another document or an asset by name.`,authoring:`markdown`,example:`![[document-name]]
|
|
1994
1996
|
|
|
1995
1997
|
![[diagram.png]]`,guidance:"Write a `![[file]]` wiki-embed to inline another doc or an uploaded asset."},{id:`Tabs`,registryName:`Tabs`,fallbackDisplayName:`Tabs`,description:`Tabbed panels — a pill strip with one panel visible at a time.`,authoring:`jsx`,example:`<Tabs>
|
|
1996
1998
|
<Tab label="First">First panel content.</Tab>
|
|
@@ -3260,6 +3262,6 @@ native-divergence-injected
|
|
|
3260
3262
|
`).split(`
|
|
3261
3263
|
`),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=Oge(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(AD(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(!SS(e))try{let{frontmatter:n,body:r}=Fi(t),i=Je(n?Yi(n):``),a=kge(r),o=new Set([...i,...a]),s=new Set;for(let e of o)for(let t of Ci(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(SS(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=Wr(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(()=>iL(`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([Jl(t),Gl(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 Gl(e,`utf-8`))}catch(e){return v9.warn({err:e},`Failed to load tag snapshot; falling back to full rebuild`),!1}if(!Dge(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(SS(e))continue;let t=new Set(n),r=new Set;for(let e of t)for(let t of Ci(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 Co(I(e),{recursive:!0}),await bo(e,JSON.stringify(t,null,2),`utf-8`)}reconcileWithDisk(){return this.enqueue(()=>iL(`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 Jl(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 Gl(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 Kl(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=cD(R(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!TS(r.name))continue;let i=cD(R(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:DS(i),filePath:n})}}};let S9=!1;function C9(){if(S9)return;let e=Vee;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){S9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),S9=!0}catch(e){F(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const Age=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function jge(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(z6).join(` `)} auth git-credential`]}function Mge(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=nl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],uj({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return F(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return F(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
|
|
3262
3264
|
`)){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(!dD(a,t))continue;let s=mz(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:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=F(`server`),b=new D5,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 re(){let e=mo({absPath:_o(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=Za(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 ie(){let e=mo({absPath:_o(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=Aa(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let r=mo({absPath:_o(`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`),{mode:_a(r.value.autoSync?.default)??`off`,source:`committed-default`}}function ae(){let e=mo({absPath:_o(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Ri(e):Pt}function oe(){return mo({absPath:_o(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function se(){return QA(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function ce(){let e=mo({absPath:_o(`project-local`,n,l),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 le(e){return`${jA(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function ue(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=ie();t=n.mode,mt?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=se();Me.applyConfig({enabled:n.enabled,providerFingerprint:le(n)}),e===`__config__/project`&&Ee?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}Ho();let de=$l(),fe=AD(n),pe=new Ju({localDir:fe,log:F(`acp-registry`)}),me=new Vu(fe,F(`acp-permissions`));if(gs(fe,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{i9({lockDir:fe,shadowRepoDir:gu(n)})}catch(e){throw ss(fe),e}let he=fi(),ge=(e,t)=>he.resolveEmbed(e,t),_e=(e,n)=>{let r=he.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=z(t,r);if(!lD(i,z(t)))return null;try{let e=jl(i);return e.isFile()?e.size:null}catch{return null}},ve,ye,be,xe,Se,Ce,we,Te,Ee=null,De=null,Oe=null,ke=null,Ae=null,je=se(),Me=new lj({loadEmbedder:e.embedderLoader??(()=>{let t=se();return LA({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:L(AD(n),`embeddings`),enabled:je.enabled,providerFingerprint:le(je)}),Pe=null,Fe=new Set,Ie=!1,Le=[],Re,ze,Be,Ve=new Promise((e,t)=>{ze=e,Be=t});function He(e){Ee?.signal(e)}let Ue=null;function We(){Ue!==null&&clearTimeout(Ue),Ue=setTimeout(()=>{Ue=null,ye.saveToDisk().catch(e=>{F(`backlinks`).warn({err:e},`Failed to persist debounced cache`)}),be.saveToDisk().catch(e=>{F(`tag-index`).warn({err:e},`Failed to persist debounced tag snapshot`)})},2e3)}let Ge=null,Ke=!1,qe=()=>{try{Y7(n,Je.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Je=new zhe(void 0,{onEviction:()=>pre(),onSizeChange:e=>mre(e),onMutate:()=>{!Ke||Ge!==null||(Ge=setTimeout(()=>{Ge=null,qe()},2e3))}});for(let[e,r]of Hhe(n))xS(e)||MK(e)&&([`.md`,`.mdx`].some(n=>{let r=z(t,`${e}${n}`);return lD(r,z(t))&&B(r)})||Je.restore(e,r));Ke=!0;let Ye=(e,t)=>{xS(e)||Je.setRenamed(e,t)},Xe=e=>{if(!xS(e)){if(Je.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Je.setDeleted(e)}},Ze=e=>{xS(e)||Je.delete(e)};try{ve=DN({projectDir:n,contentDir:t,singleDocRelPath:_,onAfterRebuild:()=>{ye.rebuildFromDisk(x()).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),be.init().catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),Lz(ft).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?F(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):F(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ye=new PL({projectDir:n,contentDir:t,contentFilter:ve}),be=new x9({projectDir:n,contentDir:t,contentFilter:ve}),(async()=>{await be.loadFromDisk()?await be.reconcileWithDisk():await be.init()})().catch(e=>{F(`server-factory`).warn({err:e},`[server-factory] tag-index warm boot failed; continuing with empty index`)}),xe={current:d},Se=o?Jme({getShadow:()=>xe.current??null,getCurrentBranch:()=>pt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:hu(n)??void 0,isWriterLive:e=>{if(!Oe&&!Te)return F(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Oe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Te?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,Ce=H7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:xe,ephemeral:v,contentRoot:f,backlinkIndex:ye,configHomedirOverride:l,getCurrentBranch:()=>pt?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e,getPrincipal:()=>Pe,onAgentCommit:()=>Ee?.signal(`session-activity`),onFlushCommit:()=>Se?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Ee?.emitDiskAck(e,t),!xS(e)&&Hie(r,n)&&(ke?.(),He(`files`))},onConfigRejected:(e,t)=>Ee?.emitConfigValidationRejected(e,t),onConfigPersisted:ue,isRecentlyRemoved:e=>Je.has(e),mdManager:e.mdManager,durabilityState:b}),we=new lme({quiet:r,debounce:i,maxDebounce:a,extensions:[Ce.extension]});let p=we;Le.push(vhe(()=>p.documents.size),yhe(()=>Ce.getQueueDepths()),xhe(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),Che(),v||(Ae=Lhe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>Ce.forceStore(e,t),getBase:e=>b.getReconciledBase(e),isBatchActive:()=>b.isBatchInProgress(),peekInFlight:e=>b.peekInFlightFlush(e),readDiskBytes:e=>{let n=uD(e,t),r,i;try{r=Dl(n),i=jl(r).size}catch(t){let n=ys(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new W7(`symlink cycle at content path: ${e}`):t}if(!dD(r,t))throw new W7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new W7(`document exceeds the open byte limit: ${e}`);try{return V(r,`utf-8`)}catch(e){if(ys(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=we.shouldUnloadDocument.bind(we);we.shouldUnloadDocument=e=>{if(Fe.has(e)||Ie&&g(e))return!0;let t=e.name;return xS(t)||S(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Re=async e=>{Fe.add(e);try{await we.unloadDocument(e)}finally{Fe.delete(e)}},Ee=new wS(we),De=new Yw(we),Oe=new Xw(we),Te=new zC(we);let y=Te;Le.push(She(()=>({active:y.liveSessionCount,limit:y.sessionLimit})));let C=j5({backlinkIndex:ye,tagIndex:be,signalChannel:He});we.configuration.extensions.push(C),we.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=WK(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==de)throw new UK(`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 UK(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(Pe&&n.principalId===Pe.id?o.principalId=Pe.id:Pe?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Pe.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),we.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!vS(e.documentName)&&!yS(e.documentName))return;let t=e.request,n=t.socket?.remoteAddress;if(n!==void 0&&!$V(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(!eH(i))throw Error(`config-doc admission requires loopback Host header (host=${i??`<absent>`}, doc=${e.documentName})`)}});let w=z(t);function ee(e){if(!MK(e))return null;let t=z(w,NS(e));return lD(t,w)?t:null}we.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await Bhe(e.documentName,{recentlyRemovedDocs:Je,resolveFilePath:ee,fileExists:B})}}),we.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=WK(e.token);Eme(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>we.documents.get(e)})}}),we.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new K8(e.update);if(t.readVarString(),t.readVarUint()===r5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Jr} rejected — server-only channel`)}});let te=PK({hocuspocus:we,durabilityState:b,sessionManager:Te,contentDir:t,contentFilter:ve,serverInstanceId:de,getFileIndex:()=>ft?ft.getFileIndex():new Map,getAttachmentFolderPath:re,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:u,shadowRef:xe,flushGitCommit:()=>Ce.flushPendingGitCommit(),flushContributors:()=>Ce.flushContributors(),getCurrentBranch:()=>pt?.getLastKnownBranch()??null,getDiskAckSVs:()=>Ee?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,backlinkIndex:ye,tagIndex:be,signalChannel:He,agentFocusBroadcaster:De,agentPresenceBroadcaster:Oe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>mt,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:ge,getPrincipal:()=>Pe,acpRegistry:pe,loadAcpCustomAgents:()=>Yu(fe,F(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Re,ready:Ve,recentlyRemovedDocs:Je,serializeDoc:nt,evictManagedArtifactLkg:e=>{Ce.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Me,getSemanticSimilarityFloor:()=>se().similarityFloor,getLinterBaseConfig:()=>ae(),getLinksValidationSetting:()=>oe(),getLinkPreviewsEnabled:ce,embeddingsSecretsFile:WA(l),readSemanticProviderConfig:se,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{ke=e}});we.configuration.extensions.push(te),we.configuration.extensions.push(Z7({mdManager:uo,schema:lo,shadowRef:xe,contentRoot:f,getCurrentBranch:()=>pt?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e})),we.configuration.extensions.push(Ege()),we.configuration.extensions.push(Tme({getSyncEngine:()=>mt,projectDir:n,contentDir:t}))}catch(e){for(let e of Le.splice(0))e();throw Ae?.dispose(),Ae=null,ss(fe),e}let Qe=null,$e=new Map,et=[];function tt(e,t){let n=z(e,`rescue`),r=z(n,NS(t));return lD(r,n)?r:null}function nt(e){let t=we.documents.get(e);return t?KR(t):null}let rt=(e,t)=>UR(b,we,e,t,ge,_e);function it(e){if(!US(e)||mt?.getConflicts().some(r=>E5(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let at=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of we.documents){if(xS(n))continue;let r=we.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{UL(r,i,ge,n)},HL)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},ot=null,st=e=>{e&&(ot===null&&(ot=new Set,setImmediate(()=>{let e=ot;if(ot=null,e)try{for(let t of e)at(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),ot.add(e))};function ct(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 XR(e)}}async function lt(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),ye.updateDocumentFromMarkdown(e.docName,e.content),We(),be.updateDocumentFromMarkdown(e.docName,e.content),He(`files`),He(`backlinks`),He(`graph`),He(`tags`),Ze(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=we.documents.get(t);if(!r){ye.updateDocumentFromMarkdown(t,n),We(),be.updateDocumentFromMarkdown(t,n),He(`backlinks`),He(`graph`),He(`tags`);return}let i=S(t)??``,a=nt(t)??i,o=qL({docName:t,base:i,ours:a,theirs:n}),s=rz(i).slice(0,6),c=rz(a).slice(0,6),l=rz(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`:it(r),ye.updateDocumentFromMarkdown(t,n),We(),be.updateDocumentFromMarkdown(t,n),He(`backlinks`),He(`graph`),He(`tags`);break;case`clean`:try{rt(t,o.newContent),C(t,o.newContent),Qx(),it(r),ye.updateDocumentFromMarkdown(t,n),We(),be.updateDocumentFromMarkdown(t,n),He(`backlinks`),He(`graph`),He(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),C(t,n),it(r)}break;case`merged`:try{rt(t,o.newContent),C(t,n),Qx(),it(r),ye.updateDocumentFromMarkdown(t,n),We(),be.updateDocumentFromMarkdown(t,n),He(`backlinks`),He(`graph`),He(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),C(t,n),it(r)}break;case`conflicts`:try{rt(t,o.newContent),C(t,o.newContent),Qx(),$x(),ye.updateDocumentFromMarkdown(t,n),We(),be.updateDocumentFromMarkdown(t,n),He(`backlinks`),He(`graph`),He(`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`:{$x();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=we.documents.get(t);if(!n){ye.deleteDocument(t),We(),be.deleteDocument(t),He(`files`),He(`backlinks`),He(`graph`),He(`tags`),Xe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=S(t)??``,i=nt(t)??``,a=i!==r;if(a&&xe.current){let e=xe.current,n=pt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{jR(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{tS(),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),ye.deleteDocument(t),We(),be.deleteDocument(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),we.closeConnections(t),await Re(n),He(`files`),He(`backlinks`),He(`graph`),He(`tags`),Xe(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=we.documents.get(t);if(w(t),C(n,r),ye.renameDocument(t,n,r),We(),be.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}`),He(`files`),He(`backlinks`),He(`graph`),He(`tags`),Ye(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=we.documents.get(t);if(!n)return;let r=nt(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`:he.add(e.relativePath),He(`files`),st(il(e.relativePath));break;case`asset-delete`:he.remove(e.relativePath),He(`files`),st(il(e.relativePath));break;case`folder-create`:case`folder-delete`:He(`files`);break;case`file-create`:case`file-update`:case`file-delete`:He(`files`);break;default:XR(e)}}catch(t){let n=ct(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let ut=[];async function dt(e){if(ne()){ut.push(e);return}await lt(e)}async function T(){let e=ut.splice(0,ut.length);for(let t of e)await lt(t)}let ft=null,pt=null,mt=null,ht=null;async function gt(e){if(we.documents.size===0)return;let t=!1,n=new Promise(e=>{we.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(we.documents.keys());we.closeConnections(),we.flushPendingStores();for(let e of we.documents.values())e.getConnectionsCount()===0&&we.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(we.documents.keys()),i=[],o=[];if(xe.current){for(let e of n)if(!xS(e))try{let t=nt(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=tt(xe.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:xe.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}bl(I(n),{recursive:!0}),Nl(n,t,`utf-8`),tS(),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=[];Ie=!0;for(let e of Le.splice(0))e();try{await Ae?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Ae=null;try{_s(fe)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Ue!==null&&(clearTimeout(Ue),Ue=null),be.close(),Ge!==null&&(clearTimeout(Ge),Ge=null),Ke)try{Y7(n,Je.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([Ve.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=we.documents.size;Se?.destroy();try{try{try{pt&&=(await pt.unsubscribe(),null),ft&&=(await ft.unsubscribe(),null);for(let{docName:e,cleanup:t}of et)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}et.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{Ee?.destroy(),Oe?.destroy(),Qe&&=(await Qe.disconnect(),null);for(let[e,t]of $e)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}$e.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 Te.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 SC()}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(p)}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 Ce.flushPendingGitCommit(),await Ce.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}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(xe.current){try{let e=(await Qo({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Nl(z(xe.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{fR(xe.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{ss(fe,{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 yt(){try{Pe=await G7(n),y.info({principalId:Pe.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!xe.current)try{xe.current=await dR(n),y.info({gitDir:xe.current.gitDir},`[server] history repo initialized at ${xe.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),vt.push(`shadow-repo`)}if(xe.current){let e=null;try{e=KH(xe.current.gitDir),hU(xe.current.gitDir,e),ZH(xe.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([gU(xe.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 Se?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(xe.current)try{await cR(xe.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{xe.current=await dR(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),xe.current=void 0,vt.includes(`shadow-repo`)||vt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(xe.current)try{let e=z(xe.current.gitDir,`last-known-head`),t=null;try{t=V(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Qo({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Qo({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 DR(xe.current,f??``,t,r,e),eS()}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{Nl(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=MH(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=ese(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{Qe=await we.openDirectConnection(Jr),Ee?.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?[]:li;for(let e of r)try{let t=await we.openDirectConnection(e);$e.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([[on,_o(`project`,n)],[$t,_o(`project-local`,n)],[fn,_o(`user`,n,l)]]);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 hme(t,t=>{let n=we.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=T5(n??null,e,t,Ce.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),ue(e)});et.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=lH(e,Ce.managedArtifactCtx);if(!n)return;let r=fH(we.documents.get(n)??null,n,t,Ce.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Dn(n)&&ye.ingestGlobalSkillBundles(aH(Ce.managedArtifactCtx),x()).then(()=>{He(`backlinks`),He(`graph`)}).catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=aH(Ce.managedArtifactCtx),n=await U5(t,e);et.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 OO(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 U5(r,e,Xme);et.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=nl(`git`,[`rev-parse`,`--git-common-dir`],uj({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=L(z(n,e.stdout.trim()),`info`,`exclude`);B(I(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=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 gme(a,(t,r)=>{(async()=>{if(t===e)try{let e=T5(we.documents.get(`__config__/okignore`)??null,Ne,r,Ce.configPersistenceCtx);o.info({docName:Ne,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 ve.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`),Ee?.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`),Ee?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:R(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(et.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=A5(n).branch??`main`;ee(a),ye.switchBranch(a);let o=performance.now();try{await yo(`ok.boot.indexes`,void 0,async()=>{let e=x();try{if(await ye.loadFromDisk(e)){let t=await ye.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)xS(e)||Je.peek(e)?.kind!==`renamed`&&(Je.setDeleted(e),n++);n>0&&y.info({count:n},`[removal-guard] tombstoned docs deleted while the server was down`)}else await ye.rebuildFromDisk(e);try{await ye.ingestGlobalSkillBundles(aH(Ce.managedArtifactCtx),e)}catch(t){y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}ye.saveToDisk().catch(t=>{F(`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 yo(`ok.boot.seed-walk`,void 0,async()=>Iz(t,dt,ve)),zL(`seedWalkMs`,Math.round(performance.now()-n));{let e=z(t),n=0;for(let[t]of Je.entries()){if(!MK(t))continue;let r=z(e,`${t}${MS(t)}`);lD(r,e)&&B(r)&&(Je.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 be.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&y.info(e,`[tag-index] startup reconcile: offline changes applied`),be.saveToDisk().catch(e=>{F(`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 LK({contentDir:t,contentFilter:ve,basenameIndex:he,onSkip:(e,t,n)=>{r++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):IK({contentDir:t,basenameIndex:he,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{zL(`indexesMs`,Math.round(performance.now()-o)),ft&&BL(`fileCount`,ft.getFileIndex().size)}try{pt=await jme(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),One(),we.flushPendingStores(),await Ce.flushPendingGitCommit(),te(!0),xe.current){let e=x(),t=A5(n).branch??e,r=[];for(let[e,t]of we.documents){if(xS(e))continue;let n=null;if(t.transact(()=>{n=nt(e)},Age),n===null)continue;let i=S(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await LR(xe.current,e,TR.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=ut.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 T(),e.headMoved&&e.newHead){let r=Mge(n,z(t),e.oldHead,e.newHead);if(r.size>0){Gk(r.keys());for(let[e,t]of r)Wk(e,Kee(t.email),t.name,t.email,Au(e));await Ce.flushContributors()}}if(await Ce.flushDeferredStores(`within-branch`),mt!==null)try{await mt.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Ane(),ut.splice(0,ut.length),ee(i),Ue!==null&&(clearTimeout(Ue),Ue=null),ye.switchBranch(i),ve.rebuildDirCount();try{let e=0;he.clear(),await LK({contentDir:t,contentFilter:ve,basenameIndex:he,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 we.documents)if(!xS(e))try{let r=uD(e,t);if(!B(r)){let t=S(e)??``,r=nt(e)??``;if(r!==t&&xe.current){let t=xe.current;queueMicrotask(()=>{jR(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{tS(),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`);rt(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:we.documents.size},`[branch-switch] loaded branch ${i} (${we.documents.size} docs)`);try{if(await ye.loadFromDisk(i)){let e=await ye.reconcileWithDisk(i);(e.added>0||e.updated>0||e.deleted>0)&&y.info(e,`[backlinks] branch-switch reconcile for ${i}`)}else await ye.rebuildFromDisk(i);try{await ye.ingestGlobalSkillBundles(aH(Ce.managedArtifactCtx),i)}catch(e){y.warn({err:e,branch:i},`[backlinks] branch-switch global skill bundle ingest failed`)}ye.saveToDisk(i).catch(e=>{F(`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 be.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 be.init()}if(be.saveToDisk().catch(e=>{F(`tag-index`).warn({branch:i,err:e},`Failed to persist tag snapshot after branch switch`)}),xe.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of we.documents)if(!xS(t))try{let n=await zR(xe.current,i,TR.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=S(t);if(!r)continue;let a=qL({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:rt(t,a.newContent),C(t,a.newContent),e++;break;case`conflicts`:rt(t,a.newContent),C(t,a.newContent),$x(),e++;{let e=we.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-`)&&xe.current)try{let t=cR(xe.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await rR(xe.current).withMutator(async()=>{for(let e of n.split(`
|
|
3263
|
-
`))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 Ce.flushDeferredStores(`discard-stale`),Ee?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&xe.current&&r>0){let t=f??`.`;try{let n=await DR(xe.current,t,e.oldHead,e.newHead,i);eS(),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=cD(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=DS(e),a=we.documents.get(i);if(!a)continue;let o=nt(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`)}}function c(e){for(let r of e)try{let e=cD(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=we.documents.get(DS(e));i&&it(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let u=jge(m),d=ie();d.mode!==`off`&&y.info({mode:d.mode,source:d.source},`[sync] mode active at boot`);try{mt=new wge({projectDir:n,contentDir:t,contentFilter:ve,contentRoot:f,mode:d.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:u,cc1Broadcaster:Ee,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||Ce.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,onContentConflictsResolved:c,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=xe.current;n&&await AR(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=xe.current;n&&await AR(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Ao({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:Ha(t.error),configPath:_o(`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}He(`files`),He(`backlinks`),He(`graph`),He(`tags`);let p=RL();p!==void 0&&zL(`readyMs`,p)}return yt().then(ze,Be),{hocuspocus:we,durabilityState:b,sessionManager:Te,cc1Broadcaster:Ee,agentFocusBroadcaster:De,agentPresenceBroadcaster:Oe,maintenanceCoordinator:Se,contentFilter:ve,basenameIndex:he,serverInstanceId:de,destroy:_t,ready:Ve,degraded:vt,lockDir:fe,get syncEngine(){return mt},resolveEmbed:ge,acpRegistry:pe,acpPermissions:me}}function T9(e){return e/1048576}function Nge(){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;vo(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function Pge(){if(E9)return;let e=Uo().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}=Nge();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 Fge(){if(!D9){let e=Uo().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=Aee({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=Uo().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=AD(e);M9=new Yo({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ea(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){ea(null),await M9?.drain(),M9=null,N9=!1}so();const Ige=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],Lge=[`cache`,`tmp`];function Rge(e){let t=z(e,Ga);if(!(()=>{if(!B(t))return!0;try{return Tl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of Ige)B(z(e,t))&&n.push(t);for(let t of Lge){let r=z(e,t);try{B(r)&&jl(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function zge(e){let t=mu(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 Bge(e){LL();let t=e.projectDir??e.contentDir,n=sq({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}`)}Go.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Ho({localSink:n?.telemetry}),F9(t),Pge(),Fge();let{kind:r,gitdir:i}=zge(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=No(i));let o=$K(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>yo(`ok.boot`,{attributes:a},async()=>Vge(e)),l=()=>{if(s)try{let e=ao.extract(co.active(),{traceparent:s});return co.with(e,c)}catch(e){F(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function Vge(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??F(`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-DUfHjP3M.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 h8(B(p)?`config`:`okdir`,f);let m=z(p,`.gitignore`);B(m)||F(`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??sI;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof iI||e instanceof aI){let t=e instanceof aI?e.detected:``,n=e instanceof aI?`too_old`:`not_available`;LV(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=Rge(p);g.length>0&&F(`boot`).warn({files:g},`Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${Ga}/.`);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,authStreamHeartbeatMs:e.authStreamHeartbeatMs,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:ee,maintenanceCoordinator:te}=_,ne=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),re=e.port??0,ie=e.ephemeral?void 0:l8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ne}:${re}`,log:i}),ae=s();ae.headersTimeout=3e4,ae.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:OD({contentFilter:_.contentFilter,contentSirv:os(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ro,assetExtensions:ba,blocklistExtensions:ga}),se=!1;if(e.reactShellDistDir)try{KI(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof GI)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 ce=e.reactShellDistDir?os(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,le=e.ephemeral?null:new Kw({contentDir:e.contentDir,localDir:S,registry:_.acpRegistry,permissions:_.acpPermissions,sessionManager:C,agentPresenceBroadcaster:ee,resolveEmbed:_.resolveEmbed,isExcludedPath:e=>_.contentFilter.isExcluded(e),isIgnoredPath:e=>_.contentFilter.isPathIgnored(e),getLoadedDocText:e=>v.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${ne}:${re}`,getMcpStdioCommand:()=>Gw(e.localOpCliArgs,re),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:i});le!==null&&await le.init();let ue=d8({httpServer:ae,hocuspocus:v,mcpHttpHandler:ie,log:i,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:ce,ephemeral:e.ephemeral,acpThreadManager:le}),de=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},fe=null;r!==null&&(fe=eq({httpServer:ae,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await de()})})),await R9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);ae.once(`error`,r),ae.listen(e.port,e.host,()=>{ae.removeListener(`error`,r),t()})})}catch(e){if(se)try{YI(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),l(S),e}let pe=RL();pe!==void 0&&zL(`httpListenMs`,pe);let me=ae.address(),he=typeof me==`object`&&me?me.port:e.port??0;if(re=he,u(S,he),se&&qI(S,he),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let ge=!1,_e=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)}};de=async()=>{if(ge)return;ge=!0;let e=[],t=async(t,n)=>{try{await _e(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{c(S),se&&Xoe(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{fe?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(le!==null&&await t(`acpThreads.destroy`,()=>le.destroy()),await t(`mount.shutdown`,()=>ue.shutdown()),ie!==void 0&&await t(`mcpHttpHandler.close`,()=>ie.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ue.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{ae.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ae.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),se&&await t(`releaseUiLock`,async()=>YI(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>Vo()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Go.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await BI({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:ae,destroy:de,lockDir:S,contentDir:e.contentDir,port:he,ready:b,degraded:x,didAutoInit:d,serverInstance:_,acpThreadManager:le}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new qK(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=hu(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!B(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=es({baseDir:n,timeout:{block:5e3}});s=new Set(await bF(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=DS(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 Hge=Ma;function Uge(e={}){let t=e.home??Ll(),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(Jo(),1);const B9=L(Ll(),`.ok`,`logs`),Wge=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function Gge(){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 Kge(e){bl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function qge(e){try{if(jl(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{Ol(n,r)}catch{}}try{Ml(`${e}.3`)}catch{}}function Jge(e){try{let t=Date.now(),n=10080*60*1e3,r=Tl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=jl(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{Ml(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{Ml(L(e,t.name)),a-=t.size}catch{}}}catch{}}function Yge(e){Kge(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);qge(n),(e._setTimeout??setTimeout)(()=>Jge(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:Gge(),name:e.name,redact:{paths:Wge,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 Xge(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 Zge(e){return L(B9,`${e}.${V9()}.log`)}function Qge(){return B9}function $ge(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=B(z(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}const H9=au(el),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function e_e(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],uj({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function t_e(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!jl(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=sI()}catch(e){throw e instanceof iI||e instanceof aI?(LV(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof aI?`too_old`:`not_available`,detectedVersion:e instanceof aI?e.detected:``},e instanceof aI?`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 e_e(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],uj({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!B(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,n_e=Gt.map(e=>e.replace(/\/$/,``));async function r_e(e){let t=hu(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(s_e(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ts(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await $o(async()=>{let t=await i_e(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await a_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=ts(e,{gitIndexFile:L(Bl(),`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 o_e(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await tB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;rs(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${we}\` 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 n_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 i_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 a_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 o_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 s_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 c_e(e,t){let n;try{n=$c(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=I(n),r=0;r<32;r+=1){let n=L(t,`package.json`);if(B(n))try{let t=JSON.parse(await Gl(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=I(t);if(r===t)return;t=r}}const l_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 l_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 u_e(e){if(!TS(e))throw new $9(e);let t;try{t=Dl(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!jl(t).isFile())throw new Q9(e);let n=I(t),r=zz(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:DS(R(d_e(e),t).split(ul).join(`/`)),canonicalFilePath:t}}let i=il(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:DS(i)}}function d_e(e){return z(e,mo({absPath:_o(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function f_e(e){let t=xl(z(Bl(),`ok-ephemeral-`)),n=z(t,`.ok`);return bl(n,{recursive:!0}),Nl(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Nl(z(n,`.gitignore`),`local/
|
|
3265
|
+
`))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 Ce.flushDeferredStores(`discard-stale`),Ee?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&xe.current&&r>0){let t=f??`.`;try{let n=await DR(xe.current,t,e.oldHead,e.newHead,i);eS(),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=cD(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=DS(e),a=we.documents.get(i);if(!a)continue;let o=nt(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`)}}function c(e){for(let r of e)try{let e=cD(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=we.documents.get(DS(e));i&&it(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let u=jge(m),d=ie();d.mode!==`off`&&y.info({mode:d.mode,source:d.source},`[sync] mode active at boot`);try{mt=new wge({projectDir:n,contentDir:t,contentFilter:ve,contentRoot:f,mode:d.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:u,cc1Broadcaster:Ee,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||Ce.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,onContentConflictsResolved:c,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=xe.current;n&&await AR(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=xe.current;n&&await AR(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Ao({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:Ha(t.error),configPath:_o(`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}He(`files`),He(`backlinks`),He(`graph`),He(`tags`);let p=RL();p!==void 0&&zL(`readyMs`,p)}return yt().then(ze,Be),{hocuspocus:we,durabilityState:b,sessionManager:Te,cc1Broadcaster:Ee,agentFocusBroadcaster:De,agentPresenceBroadcaster:Oe,maintenanceCoordinator:Se,contentFilter:ve,basenameIndex:he,serverInstanceId:de,destroy:_t,ready:Ve,degraded:vt,lockDir:fe,get syncEngine(){return mt},resolveEmbed:ge,acpRegistry:pe,acpPermissions:me}}function T9(e){return e/1048576}function Nge(){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;vo(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function Pge(){if(E9)return;let e=Uo().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}=Nge();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 Fge(){if(!D9){let e=Uo().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=Aee({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=Uo().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=AD(e);M9=new Yo({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ea(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){ea(null),await M9?.drain(),M9=null,N9=!1}so();const Ige=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],Lge=[`cache`,`tmp`];function Rge(e){let t=z(e,Ga);if(!(()=>{if(!B(t))return!0;try{return Tl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of Ige)B(z(e,t))&&n.push(t);for(let t of Lge){let r=z(e,t);try{B(r)&&jl(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function zge(e){let t=mu(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 Bge(e){LL();let t=e.projectDir??e.contentDir,n=sq({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}`)}Go.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Ho({localSink:n?.telemetry}),F9(t),Pge(),Fge();let{kind:r,gitdir:i}=zge(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=No(i));let o=$K(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>yo(`ok.boot`,{attributes:a},async()=>Vge(e)),l=()=>{if(s)try{let e=ao.extract(co.active(),{traceparent:s});return co.with(e,c)}catch(e){F(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function Vge(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??F(`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-DKRUWCqU.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 h8(B(p)?`config`:`okdir`,f);let m=z(p,`.gitignore`);B(m)||F(`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??sI;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof iI||e instanceof aI){let t=e instanceof aI?e.detected:``,n=e instanceof aI?`too_old`:`not_available`;LV(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=Rge(p);g.length>0&&F(`boot`).warn({files:g},`Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${Ga}/.`);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,authStreamHeartbeatMs:e.authStreamHeartbeatMs,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:ee,maintenanceCoordinator:te}=_,ne=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),re=e.port??0,ie=e.ephemeral?void 0:l8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ne}:${re}`,log:i}),ae=s();ae.headersTimeout=3e4,ae.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:OD({contentFilter:_.contentFilter,contentSirv:os(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ro,assetExtensions:ba,blocklistExtensions:ga}),se=!1;if(e.reactShellDistDir)try{KI(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof GI)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 ce=e.reactShellDistDir?os(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,le=e.ephemeral?null:new Kw({contentDir:e.contentDir,localDir:S,registry:_.acpRegistry,permissions:_.acpPermissions,sessionManager:C,agentPresenceBroadcaster:ee,resolveEmbed:_.resolveEmbed,isExcludedPath:e=>_.contentFilter.isExcluded(e),isIgnoredPath:e=>_.contentFilter.isPathIgnored(e),getLoadedDocText:e=>v.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${ne}:${re}`,getMcpStdioCommand:()=>Gw(e.localOpCliArgs,re),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:i});le!==null&&await le.init();let ue=d8({httpServer:ae,hocuspocus:v,mcpHttpHandler:ie,log:i,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:ce,ephemeral:e.ephemeral,acpThreadManager:le}),de=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},fe=null;r!==null&&(fe=eq({httpServer:ae,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await de()})})),await R9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);ae.once(`error`,r),ae.listen(e.port,e.host,()=>{ae.removeListener(`error`,r),t()})})}catch(e){if(se)try{YI(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),l(S),e}let pe=RL();pe!==void 0&&zL(`httpListenMs`,pe);let me=ae.address(),he=typeof me==`object`&&me?me.port:e.port??0;if(re=he,u(S,he),se&&qI(S,he),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let ge=!1,_e=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)}};de=async()=>{if(ge)return;ge=!0;let e=[],t=async(t,n)=>{try{await _e(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{c(S),se&&Xoe(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{fe?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(le!==null&&await t(`acpThreads.destroy`,()=>le.destroy()),await t(`mount.shutdown`,()=>ue.shutdown()),ie!==void 0&&await t(`mcpHttpHandler.close`,()=>ie.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ue.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{ae.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ae.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),se&&await t(`releaseUiLock`,async()=>YI(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>Vo()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Go.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await BI({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:ae,destroy:de,lockDir:S,contentDir:e.contentDir,port:he,ready:b,degraded:x,didAutoInit:d,serverInstance:_,acpThreadManager:le}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new qK(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=hu(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!B(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=es({baseDir:n,timeout:{block:5e3}});s=new Set(await bF(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=DS(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 Hge=Ma;function Uge(e={}){let t=e.home??Ll(),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(Jo(),1);const B9=L(Ll(),`.ok`,`logs`),Wge=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function Gge(){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 Kge(e){bl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function qge(e){try{if(jl(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{Ol(n,r)}catch{}}try{Ml(`${e}.3`)}catch{}}function Jge(e){try{let t=Date.now(),n=10080*60*1e3,r=Tl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=jl(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{Ml(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{Ml(L(e,t.name)),a-=t.size}catch{}}}catch{}}function Yge(e){Kge(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);qge(n),(e._setTimeout??setTimeout)(()=>Jge(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:Gge(),name:e.name,redact:{paths:Wge,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 Xge(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 Zge(e){return L(B9,`${e}.${V9()}.log`)}function Qge(){return B9}function $ge(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=B(z(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}const H9=au(el),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function e_e(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],uj({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function t_e(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!jl(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=sI()}catch(e){throw e instanceof iI||e instanceof aI?(LV(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof aI?`too_old`:`not_available`,detectedVersion:e instanceof aI?e.detected:``},e instanceof aI?`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 e_e(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],uj({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!B(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,n_e=Gt.map(e=>e.replace(/\/$/,``));async function r_e(e){let t=hu(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(s_e(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ts(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await $o(async()=>{let t=await i_e(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await a_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=ts(e,{gitIndexFile:L(Bl(),`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 o_e(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await tB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;rs(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${we}\` 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 n_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 i_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 a_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 o_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 s_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 c_e(e,t){let n;try{n=$c(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=I(n),r=0;r<32;r+=1){let n=L(t,`package.json`);if(B(n))try{let t=JSON.parse(await Gl(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=I(t);if(r===t)return;t=r}}const l_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 l_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 u_e(e){if(!TS(e))throw new $9(e);let t;try{t=Dl(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!jl(t).isFile())throw new Q9(e);let n=I(t),r=zz(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:DS(R(d_e(e),t).split(ul).join(`/`)),canonicalFilePath:t}}let i=il(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:DS(i)}}function d_e(e){return z(e,mo({absPath:_o(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function f_e(e){let t=xl(z(Bl(),`ok-ephemeral-`)),n=z(t,`.ok`);return bl(n,{recursive:!0}),Nl(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Nl(z(n,`.gitignore`),`local/
|
|
3264
3266
|
`,`utf-8`),t}export{E0 as $,xS as $i,GI as $n,NN as $r,$V as $t,n9 as A,jD as Ai,WR as An,kF as Ar,TG as At,z5 as B,EC as Bi,dR as Bn,jP as Br,HU as Bt,w9 as C,Yk as Ci,mz as Cn,HF as Cr,RK as Ct,t9 as D,Kk as Di,bz as Dn,NF as Dr,WK as Dt,Q7 as E,qk as Ei,Iz as En,UF as Er,HK as Et,D7 as F,Yw as Fi,vR as Fn,toe as Fr,rW as Ft,D5 as G,AC as Gi,cR as Gn,TP as Gr,KU as Gt,Mme as H,zC as Hi,AR as Hn,kP as Hr,PU as Ht,O7 as I,Jw as Ii,DR as In,noe as Ir,eW as It,d8 as J,VS as Ji,qL as Jn,hP as Jr,BU as Jt,m8 as K,HS as Ki,WL as Kn,wP as Kr,RU as Kt,L7 as L,Kw as Li,mR as Ln,cF as Lr,YU as Lt,Z7 as M,uD as Mi,CR as Mn,TF as Mr,JG as Mt,G7 as N,sD as Ni,wR as Nn,EF as Nr,PK as Nt,i9 as O,AD as Oi,$R as On,PF as Or,LK as Ot,H7 as P,Xw as Pi,TR as Pn,SF as Pr,zG as Pt,X6 as Q,yS as Qi,EL as Qn,DN as Qr,eH as Qt,L5 as R,tie as Ri,xR as Rn,WP as Rr,AU as Rt,I9 as S,Qk as Si,yz as Sn,GF as Sr,UK as St,x9 as T,Wk as Ti,xz as Tn,uoe as Tr,BK as Tt,j5 as U,Ire as Ui,jR as Un,CP as Ur,FU as Ut,R5 as V,IC as Vi,NR as Vn,MP as Vr,GU as Vt,A5 as W,Lre as Wi,BR as Wn,SP as Wr,UU as Wt,l8 as X,vS as Xi,HL as Xn,pP as Xr,EU as Xt,f8 as Y,wS as Yi,KL as Yn,yP as Yr,IU as Yt,o8 as Z,SS as Zi,PL as Zn,mP as Zr,DU as Zt,Hge as _,gu as _a,YA as _i,XR as _n,YF as _r,yY as _t,u_e as a,xre as aa,Ij as ai,MV as an,aI as ar,G1 as at,F9 as b,IA as bi,nz as bn,loe as br,GK as bt,r_e as c,zh as ca,fj as ci,pB as cn,hI as cr,T1 as ct,$ge as d,Hu as da,QA as di,vB as dn,lI as dr,d1 as dt,_S as ea,IM as ei,VV as en,KI as er,D0 as et,Yge as f,Yu as fa,qA as fi,hB as fn,tI as fr,f1 as ft,Uge as g,Su as ga,XA as gi,Rz as gn,XF as gr,WY as gt,Qge as h,vu as ha,JA as hi,zz as hn,eI as hr,tY as ht,f_e as i,aS as ia,Rj as ii,NV as in,iI as ir,K1 as it,r9 as j,OD as ji,PR as jn,jF as jr,qG as jt,$7 as k,kD as ki,UR as kn,MF as kr,EG as kt,W9 as l,Rh as la,yj as li,mB as ln,oI as lr,E1 as lt,Zge as m,yu as ma,ZA as mi,gB as mn,QF as mr,DY as mt,Z9 as n,mS as na,Fj as ni,IV as nn,YI as nr,N0 as nt,X9 as o,Lh as oa,Lj as oi,kV as on,nI as or,M1 as ot,Xge as p,Vu as pa,UA as pi,sB as pn,$F as pr,h$ as pt,h8 as q,G as qi,GL as qn,bP as qr,LU as qt,$9 as r,fS as ra,Pj as ri,LV as rn,qI as rr,W1 as rt,c_e as s,Ih as sa,jj as si,aB as sn,sI as sr,w1 as st,Q9 as t,gS as ta,FM as ti,zV as tn,JI as tr,O0 as tt,t_e as u,Ju as ua,uj as ui,lB as un,fI as ur,p1 as ut,Bge as v,lu as va,CA as vi,Sz as vn,hoe as vr,CY as vt,C9 as w,Jk as wi,tz as wn,VF as wr,VK as wt,P9 as x,Zk as xi,Cz as xn,WF as xr,zK as xt,R9 as y,cu as ya,wA as yi,rz as yn,KF as yr,eq as yt,Wme as z,Gw as zi,FR as zn,AP as zr,WU as zt};
|
|
3265
|
-
//# sourceMappingURL=src-
|
|
3267
|
+
//# sourceMappingURL=src-mOlBaMpr.mjs.map
|