@inkeep/open-knowledge 0.43.0-beta.11 → 0.43.0-beta.12
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-FScZV-OJ.mjs → acp-harness-probe-BgHjFLQm.mjs} +2 -2
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +7 -7
- package/dist/constants-DTOl3SVx.mjs +2 -0
- package/dist/git-handle-B6bZ5eA-.mjs +1 -0
- package/dist/{git-handle-DtR_jYUx.mjs → git-handle-DVc_e16x.mjs} +2 -2
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +1 -1
- package/dist/{init-DOMbM9QZ.mjs → init-C3NPtwsW.mjs} +3 -3
- package/dist/init-jbPJEXNL.mjs +1 -0
- package/dist/{launch-json-removal-BvzisN3q.mjs → launch-json-removal-CM6meUbZ.mjs} +2 -2
- package/dist/loader-BU3hvpWJ.mjs +1 -0
- package/dist/{loader-Bh7WABE3.mjs → loader-C04tNzUH.mjs} +2 -2
- package/dist/md-manager-BVVrP2b0.mjs +2 -0
- package/dist/{open-browser-peVrHuth.mjs → open-browser-x3hxbl2Q.mjs} +2 -2
- package/dist/parse-worker.mjs +1 -1
- package/dist/preview-BN_4v6qg.mjs +1 -0
- package/dist/{preview-DMMV4nt0.mjs → preview-ClosMsU7.mjs} +2 -2
- package/dist/public/assets/{ActivityModeContent-HvPAzuap.js → ActivityModeContent-DTyY9FXU.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-DXVF7xlv.js → AgentDiffPane-Bxxfp6qJ.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-IMQ8kqrK.js → AgentThreadClientBinder-8RE3jaN6.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-B6WcHF3z.js → CodeMirrorPropInput-l60AOLYS.js} +1 -1
- package/dist/public/assets/{DocumentContext-QO2VJVUd.js → DocumentContext-fjeyqa47.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-Br3TJSCO.js → EditorModeToggle-GDxalwgx.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-URmUoyAC.js → EnableSyncConfirmDialog-DOhZoFqn.js} +1 -1
- package/dist/public/assets/FeedbackForm-Bn8T7vX5.js +1 -0
- package/dist/public/assets/{GraphPanel-DHT3M_Xf.js → GraphPanel-CqGKHFFZ.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-D6wXCH7g.js → LintConfigEditor-BeidP0ZS.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-CvnDCIWw.js → ManagedArtifactProperties-C2qnPc_C.js} +1 -1
- package/dist/public/assets/{McpConsentDialogBody-C6b_iEsN.js → McpConsentDialogBody-DCVVVf5i.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-Ckjm-HWk.js → MermaidDocEditor-VvwQOb4B.js} +1 -1
- package/dist/public/assets/{PropertyPanel-BCDQKDSD.js → PropertyPanel-leJifucw.js} +1 -1
- package/dist/public/assets/{ReportBugDialogBody-lMg15sYD.js → ReportBugDialogBody-COMwEXMG.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-Bf9Tfipc.js → SchemaConfigEditor-BRNDxRDK.js} +1 -1
- package/dist/public/assets/{SettingsDialogBody-CV0CO7sa.js → SettingsDialogBody-CSDS-xUd.js} +1 -1
- package/dist/public/assets/{ShareBranchSwitchDialog-PmMhJ9zu.js → ShareBranchSwitchDialog-Be_ikX3U.js} +1 -1
- package/dist/public/assets/{ShareReceiveDialog-DUde-jX4.js → ShareReceiveDialog-DCirAvNX.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-CQTG5IFu.js → ShareReceiveMissDialog-CKJanT1o.js} +1 -1
- package/dist/public/assets/{SkillEditorActions-CrM2BHhi.js → SkillEditorActions-DEUAXwsS.js} +1 -1
- package/dist/public/assets/{SourceEditor-I-pbVLHm.js → SourceEditor-B3Zags19.js} +1 -1
- package/dist/public/assets/{TerminalPanel-BJuvvjn8.js → TerminalPanel-oJlqWfg_.js} +1 -1
- package/dist/public/assets/{TerminalSessionsHost-CxF-jkuS.js → TerminalSessionsHost-Dmc13JMj.js} +2 -2
- package/dist/public/assets/{TerminalWindowApp-CGrMEICf.js → TerminalWindowApp-Cvp7LIIo.js} +1 -1
- package/dist/public/assets/{ThreadView-CDeOr2kl.js → ThreadView-Dppq800p.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-DTug7oMZ.js → TimelineDiffPane-D7kfdSjy.js} +1 -1
- package/dist/public/assets/{agent-diff-store-DyEP3Km6.js → agent-diff-store-DjqU974o.js} +1 -1
- package/dist/public/assets/{agent-visibility-ik0M421s.js → agent-visibility-DwgKcief.js} +1 -1
- package/dist/public/assets/{auth-state-cache--uMim9lN.js → auth-state-cache-BiS-D1lf.js} +1 -1
- package/dist/public/assets/{client-version-C5fqEdXh.js → client-version-CiP-0dVd.js} +1 -1
- package/dist/public/assets/{config-provider-CY7XLhYT.js → config-provider-CjJvrDDE.js} +1 -1
- package/dist/public/assets/{dist-BMPs3czI.js → dist-Dy_AcDw1.js} +174 -174
- package/dist/public/assets/{doc-hash-Cx09mMdJ.js → doc-hash-BdV88vcj.js} +1 -1
- package/dist/public/assets/{documents-events-CsZSbgqD.js → documents-events-BAIUMeoV.js} +1 -1
- package/dist/public/assets/{file-tree-adapter-DUQncykJ.js → file-tree-adapter-D0NWSXoJ.js} +1 -1
- package/dist/public/assets/{file-tree-utils-CMdRs-iN.js → file-tree-utils-B8b9V0n0.js} +1 -1
- package/dist/public/assets/{index-DPtaNCi4.js → index-DbaJHLyE.js} +7 -7
- package/dist/public/assets/{lint-config-client-T5L7AekD.js → lint-config-client-CH1qsPNu.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-DFieU89D.js → markdownlint-rule-browser-AmXtD-fs.js} +1 -1
- package/dist/public/assets/{navigation-targets-BYWxwjbH.js → navigation-targets-C3sNqw3g.js} +1 -1
- package/dist/public/assets/{open-managed-artifact-tab-DHg0RpJW.js → open-managed-artifact-tab-C7wtEJar.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-DJ88nbxo.js → pending-receive-nav-store-BcQmTo2I.js} +1 -1
- package/dist/public/assets/{prop-types-CBLBXb_o.js → prop-types-CAsp_PWO.js} +1 -1
- package/dist/public/assets/{receive-store-D9WHZxmq.js → receive-store-BIIex-pm.js} +1 -1
- package/dist/public/assets/{selection-context-DUT4aHVv.js → selection-context-C8e6ddQj.js} +1 -1
- package/dist/public/assets/{skill-actions-BIWFZvwD.js → skill-actions-D7uC669s.js} +1 -1
- package/dist/public/assets/{skills-api-CzT5ZHi7.js → skills-api-vWkq9Yjo.js} +1 -1
- package/dist/public/assets/{src-BffE3bRu.js → src-a1jjnmLx.js} +1 -1
- package/dist/public/assets/{tag-pill-input-iCzfP5zx.js → tag-pill-input-j7vcpHkn.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-BJNDfVBU.js → target-navigation-intent-CCGRxmXY.js} +1 -1
- package/dist/public/assets/{terminal-launch-events-CnydHAmR.js → terminal-launch-events-CscqI70y.js} +1 -1
- package/dist/public/assets/{terminal-telemetry-CgddbfDu.js → terminal-telemetry-5Zc01ltO.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-Bq4PIaYN.js → typing-burst-detector-Dp8-M7c1.js} +1 -1
- package/dist/public/assets/{uninstall-7eKZCCHA.js → uninstall-BN1Dwiyt.js} +1 -1
- package/dist/public/assets/{use-activity-panel-BVKEKlCy.js → use-activity-panel-CX2qZrsh.js} +1 -1
- package/dist/public/assets/{use-apply-config-color-theme-VU8Nd0Xm.js → use-apply-config-color-theme-C2A3lnBb.js} +1 -1
- package/dist/public/assets/{use-collab-url-Bb6AGYgx.js → use-collab-url-Bjga3UtC.js} +1 -1
- package/dist/public/assets/{use-live-xterm-theme-C30BtcRX.js → use-live-xterm-theme-DtwirM18.js} +1 -1
- package/dist/public/assets/{use-settings-route-D3WOGF5C.js → use-settings-route-Bj2nnlZ8.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-BAUrOHbA.js → use-terminal-enabled-BPY8wWAz.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-B2Lo0NgF.js → use-timeline-entry-diff-Ck0qhFbw.js} +1 -1
- package/dist/public/assets/{use-workspace-BkbyFgS0.js → use-workspace-OvayPn9b.js} +1 -1
- package/dist/public/assets/{workspace-paths-SOIn4Gp4.js → workspace-paths-CMbhJ0Qw.js} +1 -1
- package/dist/public/index.html +35 -35
- package/dist/public/uninstall.html +2 -2
- package/dist/{repair-launch-json-A72nX3ay.mjs → repair-launch-json-nrZcDedG.mjs} +2 -2
- package/dist/{repair-mcp-configs-DDgR6Hw-.mjs → repair-mcp-configs-B-w0_Ypd.mjs} +2 -2
- package/dist/repair-skills-BCXH2Jcm.mjs +1 -0
- package/dist/{repair-skills-CbG5sTm2.mjs → repair-skills-BFa2XhCq.mjs} +2 -2
- package/dist/{server-lock-Dasu-v2i.mjs → server-lock-Bcq0DSDG.mjs} +2 -2
- package/dist/server-lock-DRXm0IHt.mjs +1 -0
- package/dist/{src-CG_sJ7fr.mjs → src-BqSmDSx1.mjs} +4 -4
- package/dist/{src-Cne-ucNX.mjs → src-CmqNHCBD.mjs} +1 -1
- package/dist/{src-NZxNysCL.mjs → src-Qy3Q9khT.mjs} +2 -2
- package/dist/{src-Dn5gGky8.mjs → src-mKEMutrR.mjs} +125 -125
- package/dist/{start-CFKsyapS.mjs → start-DnZSgRiQ.mjs} +3 -3
- package/dist/start-lTKiBdT-.mjs +1 -0
- package/dist/{write-project-skill-xElcbz-O.mjs → write-project-skill-CxSRoBP1.mjs} +2 -2
- package/package.json +4 -4
- package/dist/constants-BGUGvvvl.mjs +0 -2
- package/dist/git-handle-Df2gTERY.mjs +0 -1
- package/dist/init-BN5ycAVH.mjs +0 -1
- package/dist/loader-CzSKMzBj.mjs +0 -1
- package/dist/md-manager-YqgOJSVI.mjs +0 -2
- package/dist/preview-Doi3j_Cy.mjs +0 -1
- package/dist/public/assets/FeedbackForm-CwFVGju3.js +0 -1
- package/dist/repair-skills-BFhWJnt3.mjs +0 -1
- package/dist/server-lock-CQupI16l.mjs +0 -1
- package/dist/start-vmGNxdER.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,Ai as u,An as d,Ar as f,At as p,B as m,Ba as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Co as S,Cr as C,Ct as w,D as ee,Da as te,Di as ne,Dn as re,Do as ie,Dr as ae,Dt as oe,E as se,Ei as ce,En as le,Eo as ue,Er as de,Et as fe,F as pe,Fa as me,Fi as he,Fn as ge,Fr as _e,Ft as ve,G as ye,Ga as be,Gi as xe,Gn as Se,Gr as Ce,Gt as we,H as Te,Hi as Ee,Hn as De,Hr as Oe,Ht as ke,Ia as Ae,Ii as je,In as Me,Ir as Ne,It as Pe,J as Fe,Ja as Ie,Ji as Le,Jn as Re,Jr as ze,Jt as Be,K as Ve,Ka as He,Ki as Ue,Kn as We,Kr as Ge,Kt as Ke,Li as qe,Ln as Je,Lr as Ye,Lt as Xe,M as Ze,Ma as Qe,Mi as $e,Mn as et,Mr as tt,Mt as nt,N as rt,Na as it,Ni as at,Nn as ot,Nr as st,Nt as ct,O as T,Oa as lt,Oi as ut,On as dt,Oo as ft,Or as pt,Ot as mt,Pa as ht,Pi as gt,Pn as _t,Pr as vt,Pt as yt,Q as bt,Qi as xt,Qn as St,Qr as Ct,Qt as wt,R as Tt,Ra as Et,Ri as Dt,Rn as Ot,Rr as kt,Rt as At,S as jt,Sa as Mt,Si as Nt,Sn as Pt,Sr as eee,St as Ft,T as It,Ta as Lt,Ti as Rt,Tn as zt,To as Bt,Tr as Vt,Tt as Ht,U as Ut,Ua as Wt,Ui as tee,Un as Gt,Ur as Kt,Ut as qt,V as Jt,Vi as Yt,Vn as Xt,Vr as Zt,Vt as Qt,W as $t,Wa as en,Wi as tn,Wn as nn,Wr as rn,Wt as an,X as on,Xa as sn,Xi as cn,Xn as ln,Xr as un,Xt as dn,Y as fn,Ya as pn,Yi as nee,Yn as ree,Yr as iee,Yt as mn,Z as hn,Za as gn,Zi as _n,Zn as vn,Zr as yn,Zt as bn,_ as xn,_a as Sn,_i as Cn,_n as wn,_o as Tn,_r as En,_t as Dn,a as On,aa as kn,ai as An,an as jn,ao as Mn,ar as Nn,at as Pn,b as Fn,bi as In,bn as Ln,bo as Rn,br as zn,bt as Bn,c as Vn,ca as Hn,ci as Un,cn as Wn,co as Gn,cr as aee,ct as Kn,d as qn,da as oee,di as Jn,dn as see,do as Yn,dr as cee,dt as Xn,ea as Zn,ei as Qn,en as $n,eo as er,er as tr,et as nr,f as rr,fa as ir,fi as ar,fn as or,fo as sr,fr as cr,g as lr,ga as ur,gi as dr,gn as fr,go as pr,gr as mr,gt as hr,h as gr,ha as _r,hi as vr,hn as yr,ho as br,hr as xr,ht as Sr,i as Cr,ia as wr,ii as Tr,in as Er,io as Dr,ir as Or,it as kr,j as Ar,ja as jr,ji as Mr,jn as Nr,jr as Pr,jt as Fr,k as Ir,ki as Lr,kn as Rr,ko as zr,kr as Br,kt as lee,l as Vr,la as Hr,li as Ur,ln as uee,lo as Wr,lr as Gr,lt as Kr,m as qr,mi as Jr,mn as Yr,mo as Xr,mr as Zr,mt as Qr,n as $r,na as ei,ni as ti,nn as ni,no as ri,nr as ii,nt as ai,o as oi,oa as si,oi as ci,on as li,oo as ui,or as di,ot as fi,pa as pi,pi as mi,pn as hi,po as gi,pr as _i,q as vi,qa as yi,qi as bi,qn as xi,qr as Si,qt as Ci,r as wi,ra as Ti,ri as Ei,rn as Di,ro as Oi,rr as ki,rt as Ai,s as ji,sa as Mi,si as Ni,sn as Pi,so as Fi,sr as Ii,st as Li,t as Ri,ta as zi,ti as Bi,tn as Vi,to as Hi,tr as Ui,tt as Wi,u as Gi,ua as Ki,ui as qi,un as Ji,uo as Yi,ur as Xi,ut as Zi,v as Qi,vi as $i,vn as ea,vr as ta,vt as na,w as ra,wa as ia,wi as aa,wn as oa,wo as sa,wr as ca,wt as la,x as ua,xi as da,xn as fa,xr as pa,xt as ma,y as ha,ya as ga,yi as dee,yn as fee,yr as _a,yt as va,z as ya,zi as ba,zn as pee,zr as mee,zt as hee}from"./src-Dn5gGky8.mjs";import{$ as xa,At as Sa,B as Ca,C as wa,Ct as Ta,Dt as Ea,E as Da,Et as Oa,G as ka,H as Aa,I as ja,J as Ma,K as Na,Mt as Pa,N as Fa,Nt as Ia,Ot as La,Pt as Ra,Q as za,S as Ba,T as Va,Tt as Ha,V as Ua,W as Wa,Y as Ga,Z as Ka,_ as qa,_t as E,at as Ja,bt as Ya,ct as D,dt as O,ft as Xa,g as Za,gt as k,h as Qa,ht as A,i as $a,it as eo,jt as to,kt as no,l as ro,lt as io,m as ao,mt as j,n as oo,nt as M,ot as so,pt as co,r as lo,rt as uo,t as fo,tt as N,u as po,ut as P,v as mo,vt as ho,w as go,wt as _o,yt as vo,z as yo}from"./sleep-DDnWCWup.mjs";import{c as bo,i as xo,l as So,n as Co,s as wo}from"./esm-CItKw7Y6.mjs";import{n as To,t as Eo}from"./md-manager-YqgOJSVI.mjs";import{A as Do,C as Oo,D as ko,E as Ao,N as jo,O as Mo,S as No,T as Po,_ as Fo,a as Io,b as Lo,c as Ro,d as zo,f as Bo,g as Vo,h as Ho,i as Uo,j as Wo,k as Go,l as Ko,m as qo,n as Jo,o as Yo,p as Xo,r as Zo,s as Qo,t as $o,u as es,v as ts,w as ns,x as rs,y as is}from"./fs-traced-DDm-belY.mjs";import{D as as,E as os,S as ss,T as cs,a as ls,b as us,l as ds,p as fs,r as F,s as ps,x as ms,y as hs}from"./logger-B7Z8XO-z.mjs";import{a as gs,i as _s,o as vs,r as ys,s as bs,t as xs}from"./git-handle-DtR_jYUx.mjs";import{S as Ss,a as Cs,b as ws,c as Ts,d as Es,f as Ds,g as Os,h as ks,i as As,l as js,m as Ms,n as Ns,r as Ps,x as Fs,y as Is}from"./server-lock-Dasu-v2i.mjs";import{t as Ls}from"./libesm-DzwC_yFw.mjs";import{n as Rs,t as zs}from"./build-DYQrG4v7.mjs";import{t as Bs}from"./yazl-BafwB467.mjs";import{t as Vs}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Hs,c as Us,d as Ws,f as Gs,h as Ks,i as qs,l as Js,m as Ys,n as Xs,o as Zs,p as Qs,r as $s,s as ec,t as tc,u as nc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as rc,B as ic,C as ac,D as oc,E as sc,F as cc,H as lc,I as uc,L as dc,M as fc,N as pc,O as mc,P as hc,S as gc,T as _c,V as vc,_ as yc,a as bc,b as xc,c as Sc,d as Cc,f as wc,g as Tc,h as Ec,i as Dc,j as Oc,k as kc,l as Ac,m as jc,n as Mc,o as Nc,p as Pc,r as Fc,s as Ic,t as Lc,u as Rc,v as zc,w as Bc,x as Vc,y as Hc,z as Uc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Wc,c as Gc,d as Kc,i as qc,l as Jc,n as Yc,o as Xc,r as Zc,s as Qc,t as $c,u as el}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as tl,r as nl,t as rl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as il}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as al}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as ol,t as sl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as cl,t as ll}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as ul,r as dl,t as fl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as pl,t as ml}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as hl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as gl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as _l}from"./wrapper-BcpqREsI.mjs";import{createRequire as vl}from"node:module";import{execFile as yl,spawn as bl,spawnSync as xl}from"node:child_process";import*as Sl from"node:path";import{basename as Cl,delimiter as wl,dirname as I,extname as Tl,isAbsolute as El,join as L,normalize as Dl,posix as Ol,relative as R,resolve as z,sep as kl,win32 as Al}from"node:path";import*as jl from"node:fs";import{appendFileSync as Ml,chmodSync as Nl,closeSync as Pl,constants as Fl,createReadStream as Il,createWriteStream as Ll,existsSync as B,lstatSync as Rl,mkdirSync as zl,mkdtempSync as Bl,openSync as Vl,readFile as Hl,readFileSync as V,readSync as Ul,readdirSync as Wl,readlinkSync as Gl,realpathSync as Kl,renameSync as ql,rmSync as Jl,rmdirSync as Yl,statSync as Xl,unlinkSync as Zl,writeFileSync as Ql,writeSync as $l}from"node:fs";import{arch as eu,availableParallelism as tu,homedir as nu,hostname as ru,platform as iu,tmpdir as au}from"node:os";import{access as ou,chmod as su,constants as cu,lstat as lu,readFile as uu,readdir as du,realpath as fu,stat as pu,writeFile as mu}from"node:fs/promises";import{Readable as hu,Transform as gu,Writable as _u}from"node:stream";import{URLSearchParams as vu,fileURLToPath as yu,pathToFileURL as bu}from"node:url";import xu,{createHash as Su,randomUUID as Cu,webcrypto as wu}from"node:crypto";import Tu from"crypto";import{Readable as Eu}from"stream";import{Worker as gee}from"node:worker_threads";import{monitorEventLoopDelay as _ee,performance as Du}from"node:perf_hooks";import{createInterface as vee}from"node:readline";import{pipeline as Ou}from"node:stream/promises";import{setTimeout as ku}from"node:timers/promises";import{promisify as Au}from"node:util";import{lookup as yee}from"node:dns/promises";import{request as bee}from"node:http";import{request as xee}from"node:https";import{createBrotliDecompress as See,createGunzip as Cee,createInflate as wee}from"node:zlib";import{Http2ServerRequest as ju,constants as Tee}from"http2";import{AsyncLocalStorage as Eee}from"node:async_hooks";import{lookup as Dee}from"node:dns";import Oee from"node:tls";var Mu=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=El(t)?t:z(this.gitDir,t))}catch(e){if(!Iu(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 Iu(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]}:Ru(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 Iu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=kee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Lu(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(`..`)||El(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Mee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Iu(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return Iu(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 Ru(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Nu(e){return Fu(z(e),``)}function Pu(e){let t=z(e),n=z(nu());if(t===n)return{kind:`absent`};let r=Fu(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=Fu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Fu(e,t){let n=L(e,`.git`),r;try{r=Xl(n)}catch(e){return Iu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Mu(`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=El(o)?o:z(e,o);try{if(!Xl(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 Mu(`linked`,e,t,n,s)}}function kee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Aee(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=jee(i[1]);if(a.length>0)return a}return null}function Aee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function jee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Iu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Lu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Mee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Lu(t[1])?{kind:`symbolic`,target:t[1]}:null:Ru(e)?{kind:`oid`,oid:e}:null}function Ru(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Nee(e){return`git-author-${zr(e.trim().toLowerCase())}`}const Pee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function zu(e){let t=Pu(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 Bu(e){let t=zu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function Vu(e){let t=zu(e);switch(t.kind){case`directory`:return z(t.path,Hu(t.projectSubPath));case`linked`:if(!B(t.path))throw new Uu(t.gitPath,t.path);return z(t.path,Hu(t.projectSubPath));case`malformed-pointer`:throw new Uu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Wu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Hu(e){return e===``?`ok`:`ok-${Fee(e)}`}function Fee(e){let t=e.split(kl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Iee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Iee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var Uu=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}},Wu=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 Gu(e){let t;try{t=Vu(e)}catch(e){if(e instanceof Uu||e instanceof Wu)return null;throw e}return B(z(t,`HEAD`))?t:null}function Ku(e){return`refs/wip/${e}/`}function qu(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
1
|
+
import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$a as i,$i as a,$n as o,$r as s,$t as c,A as l,Ai as u,An as d,Ar as f,At as p,B as m,Ba as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Co as S,Cr as C,Ct as w,D as ee,Da as te,Di as ne,Dn as re,Do as ie,Dr as ae,Dt as oe,E as se,Ei as ce,En as le,Eo as ue,Er as de,Et as fe,F as pe,Fa as me,Fi as he,Fn as ge,Fr as _e,Ft as ve,G as ye,Ga as be,Gi as xe,Gn as Se,Gr as Ce,Gt as we,H as Te,Hi as Ee,Hn as De,Hr as Oe,Ht as ke,Ia as Ae,Ii as je,In as Me,Ir as Ne,It as Pe,J as Fe,Ja as Ie,Ji as Le,Jn as Re,Jr as ze,Jt as Be,K as Ve,Ka as He,Ki as Ue,Kn as We,Kr as Ge,Kt as Ke,Li as qe,Ln as Je,Lr as Ye,Lt as Xe,M as Ze,Ma as Qe,Mi as $e,Mn as et,Mr as tt,Mt as nt,N as rt,Na as it,Ni as at,Nn as ot,Nr as st,Nt as ct,O as T,Oa as lt,Oi as ut,On as dt,Oo as ft,Or as pt,Ot as mt,Pa as ht,Pi as gt,Pn as _t,Pr as vt,Pt as yt,Q as bt,Qi as xt,Qn as St,Qr as Ct,Qt as wt,R as Tt,Ra as Et,Ri as Dt,Rn as Ot,Rr as kt,Rt as At,S as jt,Sa as Mt,Si as Nt,Sn as Pt,Sr as eee,St as Ft,T as It,Ta as Lt,Ti as Rt,Tn as zt,To as Bt,Tr as Vt,Tt as Ht,U as Ut,Ua as Wt,Ui as tee,Un as Gt,Ur as Kt,Ut as qt,V as Jt,Vi as Yt,Vn as Xt,Vr as Zt,Vt as Qt,W as $t,Wa as en,Wi as tn,Wn as nn,Wr as rn,Wt as an,X as on,Xa as sn,Xi as cn,Xn as ln,Xr as un,Xt as dn,Y as fn,Ya as pn,Yi as nee,Yn as ree,Yr as iee,Yt as mn,Z as hn,Za as gn,Zi as _n,Zn as vn,Zr as yn,Zt as bn,_ as xn,_a as Sn,_i as Cn,_n as wn,_o as Tn,_r as En,_t as Dn,a as On,aa as kn,ai as An,an as jn,ao as Mn,ar as Nn,at as Pn,b as Fn,bi as In,bn as Ln,bo as Rn,br as zn,bt as Bn,c as Vn,ca as Hn,ci as Un,cn as Wn,co as Gn,cr as aee,ct as Kn,d as qn,da as oee,di as Jn,dn as see,do as Yn,dr as cee,dt as Xn,ea as Zn,ei as Qn,en as $n,eo as er,er as tr,et as nr,f as rr,fa as ir,fi as ar,fn as or,fo as sr,fr as cr,g as lr,ga as ur,gi as dr,gn as fr,go as pr,gr as mr,gt as hr,h as gr,ha as _r,hi as vr,hn as yr,ho as br,hr as xr,ht as Sr,i as Cr,ia as wr,ii as Tr,in as Er,io as Dr,ir as Or,it as kr,j as Ar,ja as jr,ji as Mr,jn as Nr,jr as Pr,jt as Fr,k as Ir,ki as Lr,kn as Rr,ko as zr,kr as Br,kt as lee,l as Vr,la as Hr,li as Ur,ln as uee,lo as Wr,lr as Gr,lt as Kr,m as qr,mi as Jr,mn as Yr,mo as Xr,mr as Zr,mt as Qr,n as $r,na as ei,ni as ti,nn as ni,no as ri,nr as ii,nt as ai,o as oi,oa as si,oi as ci,on as li,oo as ui,or as di,ot as fi,pa as pi,pi as mi,pn as hi,po as gi,pr as _i,q as vi,qa as yi,qi as bi,qn as xi,qr as Si,qt as Ci,r as wi,ra as Ti,ri as Ei,rn as Di,ro as Oi,rr as ki,rt as Ai,s as ji,sa as Mi,si as Ni,sn as Pi,so as Fi,sr as Ii,st as Li,t as Ri,ta as zi,ti as Bi,tn as Vi,to as Hi,tr as Ui,tt as Wi,u as Gi,ua as Ki,ui as qi,un as Ji,uo as Yi,ur as Xi,ut as Zi,v as Qi,vi as $i,vn as ea,vr as ta,vt as na,w as ra,wa as ia,wi as aa,wn as oa,wo as sa,wr as ca,wt as la,x as ua,xi as da,xn as fa,xr as pa,xt as ma,y as ha,ya as ga,yi as dee,yn as fee,yr as _a,yt as va,z as ya,zi as ba,zn as pee,zr as mee,zt as hee}from"./src-mKEMutrR.mjs";import{$ as xa,At as Sa,B as Ca,C as wa,Ct as Ta,Dt as Ea,E as Da,Et as Oa,G as ka,H as Aa,I as ja,J as Ma,K as Na,Mt as Pa,N as Fa,Nt as Ia,Ot as La,Pt as Ra,Q as za,S as Ba,T as Va,Tt as Ha,V as Ua,W as Wa,Y as Ga,Z as Ka,_ as qa,_t as E,at as Ja,bt as Ya,ct as D,dt as O,ft as Xa,g as Za,gt as k,h as Qa,ht as A,i as $a,it as eo,jt as to,kt as no,l as ro,lt as io,m as ao,mt as j,n as oo,nt as M,ot as so,pt as co,r as lo,rt as uo,t as fo,tt as N,u as po,ut as P,v as mo,vt as ho,w as go,wt as _o,yt as vo,z as yo}from"./sleep-DDnWCWup.mjs";import{c as bo,i as xo,l as So,n as Co,s as wo}from"./esm-CItKw7Y6.mjs";import{n as To,t as Eo}from"./md-manager-BVVrP2b0.mjs";import{A as Do,C as Oo,D as ko,E as Ao,N as jo,O as Mo,S as No,T as Po,_ as Fo,a as Io,b as Lo,c as Ro,d as zo,f as Bo,g as Vo,h as Ho,i as Uo,j as Wo,k as Go,l as Ko,m as qo,n as Jo,o as Yo,p as Xo,r as Zo,s as Qo,t as $o,u as es,v as ts,w as ns,x as rs,y as is}from"./fs-traced-DDm-belY.mjs";import{D as as,E as os,S as ss,T as cs,a as ls,b as us,l as ds,p as fs,r as F,s as ps,x as ms,y as hs}from"./logger-B7Z8XO-z.mjs";import{a as gs,i as _s,o as vs,r as ys,s as bs,t as xs}from"./git-handle-DVc_e16x.mjs";import{S as Ss,a as Cs,b as ws,c as Ts,d as Es,f as Ds,g as Os,h as ks,i as As,l as js,m as Ms,n as Ns,r as Ps,x as Fs,y as Is}from"./server-lock-Bcq0DSDG.mjs";import{t as Ls}from"./libesm-DzwC_yFw.mjs";import{n as Rs,t as zs}from"./build-DYQrG4v7.mjs";import{t as Bs}from"./yazl-BafwB467.mjs";import{t as Vs}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Hs,c as Us,d as Ws,f as Gs,h as Ks,i as qs,l as Js,m as Ys,n as Xs,o as Zs,p as Qs,r as $s,s as ec,t as tc,u as nc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as rc,B as ic,C as ac,D as oc,E as sc,F as cc,H as lc,I as uc,L as dc,M as fc,N as pc,O as mc,P as hc,S as gc,T as _c,V as vc,_ as yc,a as bc,b as xc,c as Sc,d as Cc,f as wc,g as Tc,h as Ec,i as Dc,j as Oc,k as kc,l as Ac,m as jc,n as Mc,o as Nc,p as Pc,r as Fc,s as Ic,t as Lc,u as Rc,v as zc,w as Bc,x as Vc,y as Hc,z as Uc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Wc,c as Gc,d as Kc,i as qc,l as Jc,n as Yc,o as Xc,r as Zc,s as Qc,t as $c,u as el}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as tl,r as nl,t as rl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as il}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as al}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as ol,t as sl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as cl,t as ll}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as ul,r as dl,t as fl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as pl,t as ml}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as hl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as gl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as _l}from"./wrapper-BcpqREsI.mjs";import{createRequire as vl}from"node:module";import{execFile as yl,spawn as bl,spawnSync as xl}from"node:child_process";import*as Sl from"node:path";import{basename as Cl,delimiter as wl,dirname as I,extname as Tl,isAbsolute as El,join as L,normalize as Dl,posix as Ol,relative as R,resolve as z,sep as kl,win32 as Al}from"node:path";import*as jl from"node:fs";import{appendFileSync as Ml,chmodSync as Nl,closeSync as Pl,constants as Fl,createReadStream as Il,createWriteStream as Ll,existsSync as B,lstatSync as Rl,mkdirSync as zl,mkdtempSync as Bl,openSync as Vl,readFile as Hl,readFileSync as V,readSync as Ul,readdirSync as Wl,readlinkSync as Gl,realpathSync as Kl,renameSync as ql,rmSync as Jl,rmdirSync as Yl,statSync as Xl,unlinkSync as Zl,writeFileSync as Ql,writeSync as $l}from"node:fs";import{arch as eu,availableParallelism as tu,homedir as nu,hostname as ru,platform as iu,tmpdir as au}from"node:os";import{access as ou,chmod as su,constants as cu,lstat as lu,readFile as uu,readdir as du,realpath as fu,stat as pu,writeFile as mu}from"node:fs/promises";import{Readable as hu,Transform as gu,Writable as _u}from"node:stream";import{URLSearchParams as vu,fileURLToPath as yu,pathToFileURL as bu}from"node:url";import xu,{createHash as Su,randomUUID as Cu,webcrypto as wu}from"node:crypto";import Tu from"crypto";import{Readable as Eu}from"stream";import{Worker as gee}from"node:worker_threads";import{monitorEventLoopDelay as _ee,performance as Du}from"node:perf_hooks";import{createInterface as vee}from"node:readline";import{pipeline as Ou}from"node:stream/promises";import{setTimeout as ku}from"node:timers/promises";import{promisify as Au}from"node:util";import{lookup as yee}from"node:dns/promises";import{request as bee}from"node:http";import{request as xee}from"node:https";import{createBrotliDecompress as See,createGunzip as Cee,createInflate as wee}from"node:zlib";import{Http2ServerRequest as ju,constants as Tee}from"http2";import{AsyncLocalStorage as Eee}from"node:async_hooks";import{lookup as Dee}from"node:dns";import Oee from"node:tls";var Mu=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=El(t)?t:z(this.gitDir,t))}catch(e){if(!Iu(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 Iu(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]}:Ru(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 Iu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=kee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Lu(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(`..`)||El(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Mee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Iu(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return Iu(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 Ru(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Nu(e){return Fu(z(e),``)}function Pu(e){let t=z(e),n=z(nu());if(t===n)return{kind:`absent`};let r=Fu(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=Fu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Fu(e,t){let n=L(e,`.git`),r;try{r=Xl(n)}catch(e){return Iu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Mu(`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=El(o)?o:z(e,o);try{if(!Xl(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 Mu(`linked`,e,t,n,s)}}function kee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Aee(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=jee(i[1]);if(a.length>0)return a}return null}function Aee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function jee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Iu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Lu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Mee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Lu(t[1])?{kind:`symbolic`,target:t[1]}:null:Ru(e)?{kind:`oid`,oid:e}:null}function Ru(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Nee(e){return`git-author-${zr(e.trim().toLowerCase())}`}const Pee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function zu(e){let t=Pu(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 Bu(e){let t=zu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function Vu(e){let t=zu(e);switch(t.kind){case`directory`:return z(t.path,Hu(t.projectSubPath));case`linked`:if(!B(t.path))throw new Uu(t.gitPath,t.path);return z(t.path,Hu(t.projectSubPath));case`malformed-pointer`:throw new Uu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Wu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Hu(e){return e===``?`ok`:`ok-${Fee(e)}`}function Fee(e){let t=e.split(kl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Iee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Iee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var Uu=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}},Wu=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 Gu(e){let t;try{t=Vu(e)}catch(e){if(e instanceof Uu||e instanceof Wu)return null;throw e}return B(z(t,`HEAD`))?t:null}function Ku(e){return`refs/wip/${e}/`}function qu(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 Ju=`ok-actor: `;function Yu(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),`${Ju}${JSON.stringify(i)}`}function Xu(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=Zu(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 Zu(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 Qu(e){if(!e)return null;for(let t of e.split(`
|
|
3
3
|
`)){let e=t.trim();if(!e.startsWith(Ju))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:Xu(n)}return null}function $u(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
4
4
|
`)){let e=n.trim();if(!e.startsWith(Ju))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=Xu(r);i&&t.push(i)}return t}function ed(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function td(e){let t=$u(e);return t.length>0?t.map(ed):qu(e)}function nd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function rd(e){return`reconcile: ${e}`}function id(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function ad(e,t){return`park: ${e} -> ${t}`}function od(e,t){return`rename: ${e} -> ${t}`}function sd(e){return`checkpoint: ${e}`}function cd(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const ld=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function ud(e){return e.replace(ld,` `)}function dd(e,t){let n=ud(e);if(t.length===0)return n;if(t.length>=2)return`${n} (${t.length} edits)`;let[r]=t;if(r===void 0)return n;let i=ud(r),a=`${n} — ${i}`;if(a.length<=72)return a;let o=`${n} — `,s=72-o.length-1;return s<=0?a.slice(0,72):`${o}${i.slice(0,s)}…`}function fd(e){return Pee.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function pd(e){return e.kind??`other`}function md(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var hd=class{filePath;log;grants=null;constructor(e,t){this.filePath=L(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=pd(t),i=md(n,[`allow_once`,`allow_always`]);return i===void 0?{auto:null}:r===`read`||this.hasAllowAlways(e,r)?{auto:{optionId:i.optionId}}:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n){if(n.kind!==`allow_always`)return;let r=pd(t);if(this.hasAllowAlways(e,r))return;let i=[...this.loadGrants(),{agentId:e,toolKind:r}];this.grants=i;try{let{tracedMkdir:e,tracedWriteFile:t}=await import(`./fs-traced-CeWo_16n.mjs`);await e(L(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(V(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const gd=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],_d={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},vd=`acp-agents.json`,yd=`acp-registry-cache.json`;function bd(){let e=iu(),t=eu(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`windows`:null,r=t===`arm64`?`aarch64`:t===`x64`?`x86_64`:null;return n===null||r===null?null:`${n}-${r}`}function xd(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.name==`string`&&typeof t.version==`string`&&typeof t.distribution==`object`&&t.distribution!==null}function Sd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(xd):null}var Cd=class{localDir;log;ttlMs;fetchImpl;memory=null;inflight=null;constructor(e){this.localDir=e.localDir,this.log=e.log,this.ttlMs=e.ttlMs??36e5,this.fetchImpl=e.fetchImpl??fetch}async getCatalog(){return this.memory!==null&&Date.now()-this.memory.fetchedAt<this.ttlMs&&!this.memory.stale?this.memory:(this.inflight===null&&(this.inflight=this.refresh().finally(()=>{this.inflight=null})),this.inflight)}async getAgent(e){let{agents:t}=await this.getCatalog();return t.find(t=>t.id===e)}async refresh(){try{let e=await this.fetchImpl(`https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json`,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw Error(`registry fetch failed: HTTP ${e.status}`);let t=await e.text(),n=Sd(t);if(n===null)throw Error(`registry payload did not parse as a catalog`);this.memory={agents:n,fetchedAt:Date.now(),stale:!1};try{let{tracedMkdir:e,tracedWriteFile:n}=await import(`./fs-traced-CeWo_16n.mjs`);await e(this.localDir,{recursive:!0}),await n(L(this.localDir,yd),t)}catch(e){this.log.warn({err:e},`[acp-registry] disk cache write failed`)}return this.memory}catch(e){let t=await this.readDiskCache();if(t!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving disk cache`),this.memory=t,t;if(this.memory!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving stale memory copy`),this.memory={...this.memory,stale:!0},this.memory;throw e instanceof Error?e:Error(String(e))}}async readDiskCache(){try{let e=Sd(await uu(L(this.localDir,yd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function wd(e,t){let n;try{n=await uu(L(e,vd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${vd} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return[];let i=[];for(let e of r){let n=e;typeof n?.id==`string`&&/^[a-zA-Z0-9_-]+$/.test(n.id)&&typeof n.name==`string`&&typeof n.command==`string`&&n.command.length>0&&(n.args===void 0||Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))&&(n.env===void 0||typeof n.env==`object`&&n.env!==null&&!Array.isArray(n.env)&&Object.values(n.env).every(e=>typeof e==`string`))?i.push({id:n.id,name:n.name,command:n.command,args:n.args,env:n.env??void 0}):t.warn({entry:e},`[acp-registry] dropping malformed ${vd} entry`)}return i}const H={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,nes_accept:`nes/accept`,nes_reject:`nes/reject`,nes_close:`nes/close`,document_did_open:`document/didOpen`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_save:`document/didSave`,document_did_focus:`document/didFocus`},Td={session_request_permission:`session/request_permission`,session_update:`session/update`,fs_write_text_file:`fs/write_text_file`,fs_read_text_file:`fs/read_text_file`,terminal_create:`terminal/create`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`,terminal_kill:`terminal/kill`,mcp_connect:`mcp/connect`,mcp_message:`mcp/message`,mcp_disconnect:`mcp/disconnect`,elicitation_create:`elicitation/create`,elicitation_complete:`elicitation/complete`},Ed={cancel_request:`$/cancel_request`},Dd=Symbol(`skippedItem`);function U(e,t){return e.catch(t)}function Od(e,t){let n=e.catch(t);return E().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Ra):n.parse(e))}function kd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Ad(e,t,n){return e.superRefine((e,r)=>{let i=kd(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function jd(e,t,n){return E().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Ra}let o=a.data,s=kd(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function Md(e){return N(e.catch(Dd)).transform(e=>e.filter(e=>e!==Dd))}const Nd=k([P(),A()]).nullable(),Pd=A(),Fd=O({sessionId:Pd,path:A(),content:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Id=O({sessionId:Pd,path:A(),line:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ld=A(),Rd=k([D(`read`),D(`edit`),D(`delete`),D(`move`),D(`search`),D(`execute`),D(`think`),D(`fetch`),D(`switch_mode`),D(`other`)]),zd=k([D(`pending`),D(`in_progress`),D(`completed`),D(`failed`)]),Bd=O({audience:U(Md(k([D(`assistant`),D(`user`)])).nullish(),()=>void 0),lastModified:U(A().nullish(),()=>void 0),priority:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Vd=O({annotations:U(Bd.nullish(),()=>void 0),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hd=O({annotations:U(Bd.nullish(),()=>void 0),data:A(),mimeType:A(),uri:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ud=O({annotations:U(Bd.nullish(),()=>void 0),data:A(),mimeType:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wd=O({annotations:U(Bd.nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),mimeType:U(A().nullish(),()=>void 0),name:A(),size:U(P().nullish(),()=>void 0),title:U(A().nullish(),()=>void 0),uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gd=k([O({mimeType:U(A().nullish(),()=>void 0),text:A(),uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),O({blob:A(),mimeType:U(A().nullish(),()=>void 0),uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)})]),Kd=O({annotations:U(Bd.nullish(),()=>void 0),resource:Gd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),qd=k([Vd.and(O({type:D(`text`)})),Hd.and(O({type:D(`image`)})),Ud.and(O({type:D(`audio`)})),Wd.and(O({type:D(`resource_link`)})),Kd.and(O({type:D(`resource`)}))]),Jd=O({content:qd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Yd=O({path:A(),oldText:U(A().nullish(),()=>void 0),newText:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Xd=A(),Zd=O({terminalId:Xd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qd=k([Jd.and(O({type:D(`content`)})),Yd.and(O({type:D(`diff`)})),Zd.and(O({type:D(`terminal`)}))]),$d=O({path:A(),line:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ef=O({toolCallId:Ld,kind:U(Rd.nullish(),()=>void 0),status:U(zd.nullish(),()=>void 0),title:U(A().nullish(),()=>void 0),content:U(Md(Qd).nullish(),()=>void 0),locations:U(Md($d).nullish(),()=>void 0),rawInput:U(E().optional(),()=>void 0),rawOutput:U(E().optional(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),tf=A(),nf=k([D(`allow_once`),D(`allow_always`),D(`reject_once`),D(`reject_always`)]),rf=O({sessionId:Pd,toolCall:ef,options:N(O({optionId:tf,name:A(),kind:nf,_meta:U(j(A(),E()).nullish(),()=>void 0)})),_meta:U(j(A(),E()).nullish(),()=>void 0)}),af=O({name:A(),value:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),of=O({sessionId:Pd,command:A(),args:U(Md(A()).optional(),()=>[]),env:U(Md(af).optional(),()=>[]),cwd:U(A().nullish(),()=>void 0),outputByteLimit:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),sf=O({sessionId:Pd,terminalId:Xd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),cf=O({sessionId:Pd,terminalId:Xd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),lf=O({sessionId:Pd,terminalId:Xd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),uf=O({sessionId:Pd,terminalId:Xd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),df=O({sessionId:Pd,toolCallId:U(Ld.nullish(),()=>void 0)}),ff=O({requestId:Nd}),pf=D(`object`),mf=k([D(`email`),D(`uri`),D(`date`),D(`date-time`)]),hf=O({const:A(),title:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),gf=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minLength:Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:A().nullish(),format:mf.nullish(),default:U(A().nullish(),()=>void 0),enum:N(A()).nullish(),oneOf:N(hf).nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),_f=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),vf=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),yf=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),default:U(M().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),bf=O({enum:N(A()),_meta:U(j(A(),E()).nullish(),()=>void 0)}),xf=O({anyOf:N(hf),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Sf=jd(k([bf.and(O({type:D(`string`)})),Ad(O({type:A()}),`type`,[`string`]),xf]),`type`,[`string`]),Cf=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minItems:P().nullish(),maxItems:P().nullish(),items:Sf,default:U(Md(A()).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),wf=jd(k([gf.and(O({type:D(`string`)})),_f.and(O({type:D(`number`)})),vf.and(O({type:D(`integer`)})),yf.and(O({type:D(`boolean`)})),Cf.and(O({type:D(`array`)})),Ad(O({type:A()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Tf=O({type:U(pf.optional().default(`object`),()=>`object`),title:U(A().nullish(),()=>void 0),properties:j(A(),wf).optional().default({}),required:N(A()).nullish(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ef=so(k([df,ff]),O({requestedSchema:Tf})),Df=A(),Of=so(k([df,ff]),O({elicitationId:Df,url:ho()})),kf=jd(so(k([Ef.and(O({mode:D(`form`)})),Of.and(O({mode:D(`url`)})),Ad(so(k([df,ff]),O({mode:A()})),`mode`,[`form`,`url`])]),O({message:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Af=A(),jf=O({serverId:Af,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Mf=A(),Nf=O({connectionId:Mf,method:A(),params:j(A(),E()).nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Pf=O({connectionId:Mf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ff=E();O({id:Nd,method:A(),params:k([Fd,Id,rf,of,sf,cf,lf,uf,kf,jf,Nf,Pf,Ff]).nullish()});const If=Ja().gte(0).lte(65535),Lf=O({image:U(M().optional().default(!1),()=>!1),audio:U(M().optional().default(!1),()=>!1),embeddedContext:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rf=O({http:U(M().optional().default(!1),()=>!1),sse:U(M().optional().default(!1),()=>!1),acp:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),zf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Bf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Vf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Uf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gf=O({list:U(zf.nullish(),()=>void 0),delete:U(Bf.nullish(),()=>void 0),additionalDirectories:U(Vf.nullish(),()=>void 0),fork:U(Hf.nullish(),()=>void 0),resume:U(Uf.nullish(),()=>void 0),close:U(Wf.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Kf=O({logout:U(O({_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),qf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Jf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Yf=O({syncKind:k([D(`full`),D(`incremental`)]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Xf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Zf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),$f=O({document:U(O({didOpen:U(Jf.nullish(),()=>void 0),didChange:U(Yf.nullish(),()=>void 0),didClose:U(Xf.nullish(),()=>void 0),didSave:U(Zf.nullish(),()=>void 0),didFocus:U(Qf.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ep=O({maxCount:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),tp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),np=O({maxCount:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),rp=O({maxCount:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ip=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),ap=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),op=O({recentFiles:U(ep.nullish(),()=>void 0),relatedSnippets:U(tp.nullish(),()=>void 0),editHistory:U(np.nullish(),()=>void 0),userActions:U(rp.nullish(),()=>void 0),openFiles:U(ip.nullish(),()=>void 0),diagnostics:U(ap.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),sp=O({events:U($f.nullish(),()=>void 0),context:U(op.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),cp=k([D(`utf-16`),D(`utf-32`),D(`utf-8`)]),lp=O({loadSession:U(M().optional().default(!1),()=>!1),promptCapabilities:U(Lf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:U(Rf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:U(Gf.optional().default({}),()=>({})),auth:U(Kf.optional().default({}),()=>({})),providers:U(qf.nullish(),()=>void 0),nes:U(sp.nullish(),()=>void 0),positionEncoding:U(cp.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),up=A(),dp=O({name:A(),label:U(A().nullish(),()=>void 0),secret:U(M().optional().default(!0),()=>!0),optional:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),fp=O({id:up,name:A(),description:U(A().nullish(),()=>void 0),vars:Od(Md(dp),()=>[]),link:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),pp=O({id:up,name:A(),description:U(A().nullish(),()=>void 0),args:U(Md(A()).optional(),()=>[]),env:U(j(A(),A()).optional(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),mp=O({id:up,name:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),hp=k([fp.and(O({type:D(`env_var`)})),pp.and(O({type:D(`terminal`)})),mp]),gp=O({name:A(),title:U(A().nullish(),()=>void 0),version:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),_p=O({protocolVersion:If,agentCapabilities:U(lp.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:U(Md(hp).optional().default([]),()=>[]),agentInfo:U(gp.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),vp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),yp=A(),bp=k([D(`anthropic`),D(`openai`),D(`azure`),D(`vertex`),D(`bedrock`),A()]),xp=O({apiType:bp,baseUrl:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Sp=O({providers:N(O({providerId:yp,supported:Od(Md(bp),()=>[]),required:M(),current:xp.nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)})),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Cp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),wp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Tp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ep=A(),Dp=O({currentModeId:Ep,availableModes:Od(Md(O({id:Ep,name:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Op=A(),kp=k([D(`mode`),D(`model`),D(`model_config`),D(`thought_level`),A()]),Ap=A(),jp=O({value:Ap,name:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Mp=O({group:A(),name:A(),options:Od(Md(jp),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Np=O({currentValue:Ap,options:k([N(jp),N(Mp)])}),Pp=O({currentValue:M()}),Fp=so(k([Np.and(O({type:D(`select`)})),Pp.and(O({type:D(`boolean`)}))]),O({id:Op,name:A(),description:U(A().nullish(),()=>void 0),category:U(kp.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),Ip=O({sessionId:Pd,modes:U(Dp.nullish(),()=>void 0),configOptions:U(Md(Fp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Lp=O({modes:U(Dp.nullish(),()=>void 0),configOptions:U(Md(Fp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rp=O({sessions:Od(Md(O({sessionId:Pd,cwd:A(),additionalDirectories:U(Md(A()).optional(),()=>[]),title:U(A().nullish(),()=>void 0),updatedAt:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),()=>[]),nextCursor:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),zp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Bp=O({sessionId:Pd,modes:U(Dp.nullish(),()=>void 0),configOptions:U(Md(Fp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Vp=O({modes:U(Dp.nullish(),()=>void 0),configOptions:U(Md(Fp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Up=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wp=O({configOptions:Od(Md(Fp),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gp=O({stopReason:k([D(`end_turn`),D(`max_tokens`),D(`max_turn_requests`),D(`refusal`),D(`cancelled`)]),usage:U(O({totalTokens:P(),inputTokens:P(),outputTokens:P(),thoughtTokens:U(P().nullish(),()=>void 0),cachedReadTokens:U(P().nullish(),()=>void 0),cachedWriteTokens:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Kp=O({sessionId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),qp=A(),Jp=O({line:Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Yp=O({start:Jp,end:Jp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Xp=O({range:Yp,newText:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Zp=O({id:qp,uri:A(),edits:N(Xp),cursorPosition:U(Jp.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qp=O({id:qp,uri:A(),position:Jp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),$p=O({id:qp,uri:A(),position:Jp,newName:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),em=O({id:qp,uri:A(),search:A(),replace:A(),isRegex:M().nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),tm=O({suggestions:N(k([Zp.and(O({kind:D(`edit`)})),Qp.and(O({kind:D(`jump`)})),$p.and(O({kind:D(`rename`)})),em.and(O({kind:D(`searchAndReplace`)}))])),_meta:U(j(A(),E()).nullish(),()=>void 0)}),nm=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),rm=E(),im=E(),am=O({code:k([D(-32700),D(-32600),D(-32601),D(-32602),D(-32603),D(-32800),D(-32e3),D(-32002),Ja().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:A(),data:U(E().optional(),()=>void 0)});k([O({id:Nd,result:k([_p,vp,Sp,Cp,wp,Tp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,tm,nm,rm,im])}),O({id:Nd,error:am})]);const om=O({content:qd,messageId:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),sm=O({toolCallId:Ld,title:A(),kind:U(Rd.optional(),()=>void 0),status:U(zd.optional(),()=>void 0),content:U(Md(Qd).optional(),()=>[]),locations:U(Md($d).optional(),()=>[]),rawInput:U(E().optional(),()=>void 0),rawOutput:U(E().optional(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),cm=k([D(`high`),D(`medium`),D(`low`)]),lm=k([D(`pending`),D(`in_progress`),D(`completed`)]),um=O({content:A(),priority:cm,status:lm,_meta:U(j(A(),E()).nullish(),()=>void 0)}),dm=O({entries:Od(Md(um),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),fm=A(),pm=O({planId:fm,entries:Od(Md(um),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),mm=O({planId:fm,uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),hm=O({planId:fm,content:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),gm=O({plan:k([pm.and(O({type:D(`items`)})),mm.and(O({type:D(`file`)})),hm.and(O({type:D(`markdown`)}))]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),_m=O({planId:fm,_meta:U(j(A(),E()).nullish(),()=>void 0)}),vm=O({hint:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ym=O({availableCommands:Od(Md(O({name:A(),description:A(),input:U(vm.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),bm=O({currentModeId:Ep,_meta:U(j(A(),E()).nullish(),()=>void 0)}),xm=O({configOptions:Od(Md(Fp),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Sm=O({title:U(A().nullish(),()=>void 0),updatedAt:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Cm=O({amount:P(),currency:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),wm=O({used:P(),size:P(),cost:U(Cm.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Tm=O({sessionId:Pd,update:k([om.and(O({sessionUpdate:D(`user_message_chunk`)})),om.and(O({sessionUpdate:D(`agent_message_chunk`)})),om.and(O({sessionUpdate:D(`agent_thought_chunk`)})),sm.and(O({sessionUpdate:D(`tool_call`)})),ef.and(O({sessionUpdate:D(`tool_call_update`)})),dm.and(O({sessionUpdate:D(`plan`)})),gm.and(O({sessionUpdate:D(`plan_update`)})),_m.and(O({sessionUpdate:D(`plan_removed`)})),ym.and(O({sessionUpdate:D(`available_commands_update`)})),bm.and(O({sessionUpdate:D(`current_mode_update`)})),xm.and(O({sessionUpdate:D(`config_option_update`)})),Sm.and(O({sessionUpdate:D(`session_info_update`)})),wm.and(O({sessionUpdate:D(`usage_update`)}))]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Em=O({elicitationId:Df,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Dm=O({connectionId:Mf,method:A(),params:U(j(A(),E()).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Om=E();O({method:A(),params:k([Tm,Em,Dm,Om]).nullish()});const Lee=O({readTextFile:U(M().optional().default(!1),()=>!1),writeTextFile:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ree=O({configOptions:U(O({boolean:U(O({_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),zee=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Bee=O({terminal:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Vee=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hee=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Uee=O({form:U(Vee.nullish(),()=>void 0),url:U(Hee.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wee=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gee=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Kee=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),qee=O({jump:U(Wee.nullish(),()=>void 0),rename:U(Gee.nullish(),()=>void 0),searchAndReplace:U(Kee.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),km=O({protocolVersion:If,clientCapabilities:U(O({fs:U(Lee.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:U(M().optional().default(!1),()=>!1),session:U(Ree.nullish(),()=>void 0),plan:U(zee.nullish(),()=>void 0),auth:U(Bee.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:U(Uee.nullish(),()=>void 0),nes:U(qee.nullish(),()=>void 0),positionEncodings:U(Md(cp).optional(),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:U(gp.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Am=O({methodId:up,_meta:U(j(A(),E()).nullish(),()=>void 0)}),jm=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Mm=O({providerId:yp,apiType:bp,baseUrl:A(),headers:j(A(),A()).optional(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Nm=O({providerId:yp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Pm=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Fm=O({name:A(),value:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Jee=O({name:A(),url:A(),headers:N(Fm),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Yee=O({name:A(),url:A(),headers:N(Fm),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Xee=O({name:A(),serverId:Af,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Zee=O({name:A(),command:A(),args:N(A()),env:N(af),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Im=k([Jee.and(O({type:D(`http`)})),Yee.and(O({type:D(`sse`)})),Xee.and(O({type:D(`acp`)})),Zee]),Lm=O({cwd:A(),additionalDirectories:U(Md(A()).optional(),()=>[]),mcpServers:Od(Md(Im),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rm=O({mcpServers:Od(Md(Im),()=>[]),cwd:A(),additionalDirectories:U(Md(A()).optional(),()=>[]),sessionId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),zm=O({cwd:A().nullish(),cursor:A().nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Bm=O({sessionId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Vm=O({sessionId:Pd,cwd:A(),additionalDirectories:U(Md(A()).optional(),()=>[]),mcpServers:U(Md(Im).optional(),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hm=O({sessionId:Pd,cwd:A(),additionalDirectories:U(Md(A()).optional(),()=>[]),mcpServers:U(Md(Im).optional(),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Um=O({sessionId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wm=O({sessionId:Pd,modeId:Ep,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gm=so(k([O({value:M(),type:D(`boolean`)}),O({value:Ap})]),O({sessionId:Pd,configId:Op,_meta:U(j(A(),E()).nullish(),()=>void 0)})),Km=O({sessionId:Pd,prompt:N(qd),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qee=O({uri:A(),name:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),$ee=O({name:A(),owner:A(),remoteUrl:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),qm=O({workspaceUri:U(A().nullish(),()=>void 0),workspaceFolders:N(Qee).nullish(),repository:U($ee.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ete=k([D(`automatic`),D(`diagnostic`),D(`manual`)]),tte=O({uri:A(),languageId:A(),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),nte=O({startLine:Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),rte=O({uri:A(),excerpts:N(nte),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ite=O({uri:A(),diff:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ate=O({action:A(),uri:A(),position:Jp,timestampMs:P(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ote=O({uri:A(),languageId:A(),visibleRange:U(Yp.nullish(),()=>void 0),lastFocusedMs:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ste=k([D(`error`),D(`warning`),D(`information`),D(`hint`)]),cte=O({uri:A(),range:Yp,severity:ste,message:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),lte=O({recentFiles:N(tte).nullish(),relatedSnippets:N(rte).nullish(),editHistory:N(ite).nullish(),userActions:N(ate).nullish(),openFiles:N(ote).nullish(),diagnostics:N(cte).nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Jm=O({sessionId:Pd,uri:A(),version:P(),position:Jp,selection:Yp.nullish(),triggerKind:ete,context:lte.nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ym=O({sessionId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)});O({id:Nd,method:A(),params:k([km,Am,jm,Mm,Nm,Pm,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Nf,Ff]).nullish()});const ute=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),dte=O({content:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),fte=O({optionId:tf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),pte=O({outcome:k([O({outcome:D(`cancelled`)}),fte.and(O({outcome:D(`selected`)}))]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),mte=O({terminalId:Xd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),hte=O({exitCode:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),gte=O({output:A(),truncated:M(),exitStatus:U(hte.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),_te=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),vte=O({exitCode:U(Ja().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),yte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),bte=k([A(),P(),P(),M(),N(A())]),Xm=O({content:j(A(),bte).nullish()});k([O({id:Nd,result:k([ute,dte,pte,mte,gte,_te,vte,yte,jd(so(k([Xm.and(O({action:D(`accept`)})),O({action:D(`decline`)}),O({action:D(`cancel`)}),Ad(O({action:A()}),`action`,[`accept`,`cancel`,`decline`])]),O({_meta:U(j(A(),E()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),O({connectionId:Mf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),im,rm])}),O({id:Nd,error:am})]);const Zm=O({sessionId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qm=O({sessionId:Pd,uri:A(),languageId:A(),version:P(),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),xte=O({range:Yp.nullish(),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),$m=O({sessionId:Pd,uri:A(),version:P(),contentChanges:Od(Md(xte),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),eh=O({sessionId:Pd,uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),th=O({sessionId:Pd,uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),nh=O({sessionId:Pd,uri:A(),version:P(),position:Jp,visibleRange:Yp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),rh=O({sessionId:Pd,id:qp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),ih=O({sessionId:Pd,id:qp,reason:U(k([D(`rejected`),D(`ignored`),D(`replaced`),D(`cancelled`)]).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)});O({method:A(),params:k([Zm,Qm,$m,eh,th,nh,rh,ih,Dm,Om]).nullish()}),O({requestId:Nd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ef.and(O({mode:D(`form`)})).and(O({message:A()})),Of.and(O({mode:D(`url`)})).and(O({message:A()})),k([df,ff]).and(O({message:A()})),gf.and(O({type:D(`string`)})),_f.and(O({type:D(`number`)})),vf.and(O({type:D(`integer`)})),yf.and(O({type:D(`boolean`)})),Cf.and(O({type:D(`array`)})),bf.and(O({type:D(`string`)})),Xm.and(O({action:D(`accept`)})),O({action:D(`decline`)}),O({action:D(`cancel`)});const ah=`$/cancel_request`;function oh(e){return typeof e==`object`&&!!e}function Ste(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Cte(e){if(!(!oh(e)||!Ste(e.requestId)))return e.requestId}const sh={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function ch(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function wte(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Tte(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`&&`issues`in e&&Array.isArray(e.issues)&&`format`in e&&typeof e.format==`function`}function lh(e){if(e instanceof mh)return e.toResult();if(Tte(e))return mh.invalidParams(e.format()).toResult();let t=wte(e);try{return mh.internalError(t?JSON.parse(t):{}).toResult()}catch{return mh.internalError({details:t}).toResult()}}function Ete(e){return e instanceof mh&&e.code===-32800?e:mh.requestCancelled(e)}function Dte(e,t){let n=Ote(e,t);return n?n.toResult():lh(e)}function Ote(e,t){if(!(!t.aborted||!kte(e)))return Ete(t.reason)}function kte(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Ate=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof mh?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?ch(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},uh=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},dh=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},fh=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new dh(this);receiveReader;constructor(e,t,n,r){if(typeof e==`function`){let i=e,a=t,o=n;this.initialize(o,[...r?.handlers??[],this.legacyHandler(i,a)]);return}let i=e,a=t,o=n;this.initialize(i,[...o?.handlers??[],...a])}static builder(){return new ph}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let e of this.retryQueue.splice(0))this.processIncomingMessage(e).catch(e=>this.close(e));return new uh(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return ch(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification(ah,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?ch(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return sh.yes()}}}async receive(){let e;try{let e=this.stream.readable.getReader();this.receiveReader=e;try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(this.abortController.signal.aborted||n)break;t&&this.receiveMessage(t)}}finally{this.receiveReader===e&&(this.receiveReader=void 0),e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveMessage(e){if(!this.abortController.signal.aborted){if(!oh(e)){console.error(`Invalid message`,{message:e});return}`method`in e?(`id`in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e)).catch(e=>this.close(e))):`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e})}}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let e of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let r=await e.handleMessage(t,this.context)??{handled:!0};if(r.handled)return;t=r.message??t,n||=!!r.retry}n?this.retryQueue.push(t):t.kind===`request`&&await t.responder.respondWithError(mh.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Dte(n,t.responder.signal));else{let t=lh(n);`error`in t&&console.error(`Error handling notification`,e.raw,t.error)}}}toIncomingMessage(e){if(`id`in e){let t=new AbortController;return this.incomingRequests.set(e.id,t),{kind:`request`,method:e.method,params:e.params,raw:e,signal:t.signal,responder:new Ate(e.id,t=>this.sendMessage({jsonrpc:`2.0`,id:e.id,...t}),t.signal,()=>{this.incomingRequests.get(e.id)===t&&this.incomingRequests.delete(e.id)})}}return{kind:`notification`,method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),`result`in e)t.resolve(e.result);else if(`error`in e&&oh(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new mh(n,r,i))}else t.reject(mh.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==ah)return;let t=Cte(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(mh.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?ch(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},ph=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??sh.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?sh.no(r):await n(t(r.params),r.responder,i)??sh.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?sh.no(r):await n(t(r.params),i)??sh.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new fh(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},mh=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static requestCancelled(t,n){return new e(-32800,`Request cancelled${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}},hh=class{#e=[];push(e){let t=[],n=0,r=e.indexOf(10,n);for(;r!==-1;)t.push(this.#t(e.subarray(n,r))),n=r+1,r=e.indexOf(10,n);return n<e.byteLength&&this.#e.push(n===0?e:new Uint8Array(e.subarray(n))),t}flush(){if(this.#e.length!==0)return this.#t(new Uint8Array)}#t(e){if(this.#e.length===0)return e;let t=e.byteLength;for(let e of this.#e)t+=e.byteLength;let n=new Uint8Array(t),r=0;for(let e of this.#e)n.set(e,r),r+=e.byteLength;return n.set(e,r),this.#e=[],n}};function gh(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new hh,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);oh(t)?e.enqueue(t):console.warn(`Skipping JSON line that is not an object:`,n)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}},s=t.getReader();a=s;try{for(;;){let{value:e,done:t}=await s.read();if(i)return;if(t)break;if(e){for(let t of n.push(e))if(o(t),i)return}}if(i)return;let e=n.flush();e&&o(e)}catch(t){if(i)return;e.error(t);return}finally{a===s&&(a=void 0),s.releaseLock()}i||e.close()},cancel(e){return i=!0,a?.cancel(e)}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
|
|
@@ -1225,7 +1225,7 @@ tags: [lore, history]
|
|
|
1225
1225
|
`),i=n.nextFenced+(r?`
|
|
1226
1226
|
`:``)+t;dS(b.dc.document,i,`agent`,void 0,S),Aw(`mcp-write`),te=!0}ee=!0},b.origin)})}finally{Ze?.touchMode(c,`idle`)}if(w){let e;switch(w.kind){case`invalid_value`:e={[w.key]:w.reason};break;case`reserved_key`:e={[w.key]:`'${w.key}' is reserved`};break;case`unknown_key`:e={[w.key]:`'${w.key}' is not a recognized key`};break;case`duplicate_target`:e={[w.key]:`'${w.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${w.expected.join(`, `)}; got: ${w.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${w.bytes} > ${w.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${w.reason}`};break;case`invalid_path`:e={[w.path.map(String).join(`.`)||`__path__`]:w.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(w)})`}}G(r,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(ee&&ne.length>0){if(sP(o,c,u,d,void 0,vi({clientName:f,clientVersion:p,label:m}),y),AS(),Ei(_),te){let e=await fr(o);if(e?.kind===`failure`){hr(r,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){gr(r,`frontmatter-patch`);return}}sr(o,`frontmatter-patch`)}qe?.setFocus(c,{agentName:u,currentDoc:o,writeKind:`write`,ts:Date.now()}),Qe?.();let re=rr(o),ie=ir();ie===0&&jq().add(1,{"shadow.writer":`agent`,"agent.type":fg(f)});let ae=vr(x);Cr(o,b.dc.document.getText(`source`).toString());let oe=br();oe.add(o);let se=KB(b.dc.document.getText(`source`).toString(),o,oe,Sr);q(r,200,Bi,{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 oD){G(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e,requestId:cw(n)},`[frontmatter-patch] handler failed`),G(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Hi(e){let t=e.getMap(`lifecycle`),n=t.get(`status`);if(typeof n!=`string`||n.length===0)return null;let r=t.get(`reason`);return{status:n,reason:typeof r==`string`?r:``}}let Wi=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!nY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let r=nr(n);if(LC(r)||zC(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`document-read`});return}let i=a.documents.get(r);if(i){q(t,200,Ye,{docName:r,content:i.getText(`source`).toString(),lifecycle:Hi(i)},{handler:`document-read`});return}if(!B(kJ(l,`file`,r))){G(t,404,`urn:ok:error:doc-not-found`,`Document not found: ${r}.`,{handler:`document-read`});return}let o=await a.openDirectConnection(r);try{let e=o.document;if(!e){G(t,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}q(t,200,Ye,{docName:r,content:e.getText(`source`).toString(),lifecycle:Hi(e)},{handler:`document-read`})}finally{await o.disconnect()}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Gi=J(g,async(e,t)=>{try{jt&&await jt.catch(e=>{Y.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=n.searchParams.get(`dir`),i=n.searchParams.get(`showAll`)===`true`,a=n.searchParams.get(`showOk`)===`true`,o=n.searchParams.get(`depth`)===`1`?1:1/0;if(r)try{lJ(l,r)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(i&&Tt&&yJ(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=pw(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=fJ(),n=bJ({contentDir:l,contentFilter:Tt,dirFilter:r,maxEntries:t,maxDepth:o,showOk:a,signal:e.signal}),s=0,c=await n.next();for(;!c.done;)await i(`${JSON.stringify(c.value)}\n`),s+=1,c=await n.next();let{truncated:u}=c.value;u&&Y.info({handler:`document-list`,maxEntries:t,count:s},`[document-list][showAll] stream truncated at entry cap`),await i(`${JSON.stringify({type:`complete`,truncated:u,count:s})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):Y.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(i&&Tt){let e=`showAll:${o===1?`d1:`:``}${a?`ok:`:``}${r??``}`,n=pn.get(e);if(!n){let t=new AbortController,i=(async()=>{let e=[],n=fJ(),{truncated:i}=await xJ({contentDir:l,contentFilter:Tt,dirFilter:r,documents:e,maxEntries:n,maxDepth:o,showOk:a,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),i&&Y.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:i}})();n={promise:i,controller:t,waiters:0};let s=n;pn.set(e,s),i.finally(()=>{pn.get(e)===s&&pn.delete(e)})}let i=n;i.waiters+=1;let s=!1,c=()=>{t.writableEnded||s||(s=!0,--i.waiters,i.waiters<=0&&(i.controller.abort(),pn.get(e)===i&&pn.delete(e)))};t.on(`close`,c);try{let{documents:e,truncated:n}=await i.promise;if(s)return;q(t,200,Ne,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(s)return;G(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,c)}return}let s=m(),c=S(),u=ie?.()??new Map,d=[];for(let[e,t]of u)r&&!e.startsWith(`${r}/`)&&e!==r||d.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let f=[];try{let e=kn(s);vn?.signature!==e&&(vn={signature:e,assets:_M({contentDir:l,fileIndex:s,readMarkdown:e=>{try{return V(e,`utf-8`)}catch{return null}},isExcluded:Tt?e=>Tt.isPathIgnored(e):void 0})}),f=vn?.assets??[]}catch(e){vn=null,Y.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let p=new Set;for(let e of f)r&&!e.path.startsWith(`${r}/`)&&e.path!==r||(p.add(e.path),d.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of c){if(t.kind===`markdown`){if(r&&!e.startsWith(`${r}/`)&&e!==r)continue;let n=$C(e);d.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(r&&!i.startsWith(`${r}/`)&&i!==r)continue;let a=Pj(R(l,t.canonicalPath));d.push({kind:`document`,docName:i,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}continue}if((!r||e===r||e.startsWith(`${r}/`))&&!p.has(e)){let n=uJ(e);d.push({kind:`file`,docName:e,path:e,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let n of t.aliases){if(!(!r||n===r||n.startsWith(`${r}/`))||p.has(n))continue;let i=Pj(R(l,t.canonicalPath)),a=uJ(n);d.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}}let h=me?.()??new Map;if(h.size>0){let e=e=>!r||e===r||e.startsWith(`${r}/`),t=new Map;for(let[e,n]of h){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,r]of t){let t=u.get(n),i=t?Pj(R(l,t.canonicalPath)):n;for(let a of r)e(a)&&d.push({kind:`folder`,path:a,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:i})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of u)n(e,n=>{d.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:Pj(R(l,t.canonicalPath))})});for(let[e,t]of c)n(e,n=>{let r=Pj(R(l,t.canonicalPath));if(t.kind===`markdown`)d.push({kind:`document`,docName:n,docExt:$C(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=uJ(n);d.push({kind:`file`,docName:n,path:n,docExt:`.${i}`,assetExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r})}})}d.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),q(t,200,Ne,{documents:d},{handler:`document-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Yi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!nY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}q(t,200,_e,{docName:n,backlinks:Ie.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:Un(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}),Zi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!nY(t)||(r[t]=Ie.getBacklinkCount(t))}q(t,200,vt,{counts:r},{handler:`backlink-counts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Qi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!nY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=br();q(t,200,kt,{docName:n,forwardLinks:Ie.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Gn(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}),$i=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!nY(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){G(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){G(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:a,links:o}=Ie.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=Ie.getLinkGraph());let s=br();q(t,200,mee,{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:Gn(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}),ea=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!Ae(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}q(t,200,eee,{orphans:Ie.getOrphans([...m().keys()],n).map(e=>({docName:e,title:Un(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}),na=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20,a=br();q(t,200,pa,{hubs:Ie.getHubs(i).map(e=>({docName:e.docName,title:Gn(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}),sa=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!nY(e))){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>nr(e)))]:void 0;q(t,200,zn,{deadLinks:Ie.getDeadLinks(br(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Un(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}),ca=J(Kt,async(n,r,i)=>{try{let{find:n,replace:o,offset:c}=i,u=DJ(i.docName,r,`agent-patch`);if(u===null)return;let d=nr(u),{agentId:f,agentName:p,colorSeed:m,clientName:h,clientVersion:g,label:_}=gi(i);if(Pq(n)){Nq().add(1,{result:`rejected`}),G(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(LC(d)||zC(d)){G(r,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`agent-patch`});return}let v=xj(i.summary),b=await s.getSession(d,f,{displayName:p,colorSeed:m,clientName:h}),x=vV(t,a,d,l,e.resolveEmbed,lt?.()),S=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,C;{let{frontmatter:e,body:t}=ia(b.dc.document.getText(`source`).toString()),r=y(e,t),i=c==null?r.indexOf(n):r.slice(c,c+n.length)===n?c:-1;if(i!==-1&&i>=e.length){let e=r.slice(0,i)+o+r.slice(i+n.length);C=await KE(b.dc.document,ia(e).body,`patch`,S)}}let w=new Date().toISOString(),ee=!1,te=!1,ne=!1,re,ie;try{let e=qn(h),t=Vn[e]??Vr(m??f);if(Ze?.setPresence(f,{displayName:p,icon:e,color:t,currentDoc:d,mode:`writing`,ts:Date.now()}),ie=yj(b.dc.document.getText(`source`),f,b.origin,m,h),b.dc.document.transact(()=>{let{frontmatter:e,body:t}=ia(b.dc.document.getText(`source`).toString()),r=y(e,t),i=c==null?r.indexOf(n):r.slice(c,c+n.length)===n?c:-1;if(i===-1){c==null?ee=!0:te=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":d,findLength:n.length,replaceLength:o.length,hadOffset:c!=null})),sre();return}if(i<e.length){ne=!0;return}let{body:a}=ia(r.slice(0,i)+o+r.slice(i+n.length)),s=ZE(b.dc.document);re=XE(b.dc.document,a,`patch`,S,C,JE(b));let l=Tn(s,ZE(b.dc.document))??void 0;b.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Patched (${p}): ${n.slice(0,50)}`,...l===void 0?{}:{changedBlocks:l}})},b.origin),re!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":d,position:`patch`,intendedBytes:re.intendedBytes,actualBytes:re.actualBytes,byteDelta:re.byteDelta,"agent.id":f,"agent.client_name":h})),!ee&&!te&&!ne){let{stored:e}=yi(v);sP(d,f,p,m,void 0,vi({clientName:h,clientVersion:g,label:_}),e),AS(),Ei(v),Gq(`agent-patch`,re)}}finally{ie?.(),Ze?.touchMode(f,`idle`)}if(te){G(r,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ee){G(r,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ne){Nq().add(1,{result:`rejected`}),G(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ae=await fr(d);if(ae?.kind===`failure`){hr(r,ae.failure,`agent-patch`);return}if(ae?.kind===`divergence`){gr(r,`agent-patch`);return}sr(d,`agent-patch`),qe?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`edit`,ts:Date.now()}),Qe?.();let oe=rr(d),se=ir();se===0&&jq().add(1,{"shadow.writer":`agent`,"agent.type":fg(h)});let{response:ce}=yi(v),le=b.dc.document.getText(`source`).toString();Cr(d,le);let ue=await rL(le,d),de=br();de.add(d);let fe=KB(le,d,de,Sr),pe=vr(x),me=re===void 0?void 0:ww(re),he=[...me?[me]:[],...pe?[pe]:[],...ue??[],...await fl(b.dc.document.getText(`source`).toString(),d)];q(r,200,rn,{timestamp:w,subscriberCount:oe,systemSubscriberCount:se,...ce?{summary:ce}:{},...me?{warning:me}:pe?{warning:pe}:{},...he.length>0?{warnings:he}:{},brokenLinks:fe},{handler:`agent-patch`})}catch(e){if(e instanceof yw){bw(r,e,`agent-patch`);return}if(e instanceof Tw){Dw(r,e,`agent-patch`);return}if(e instanceof oD){G(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e,requestId:cw(n)},`[agent-patch] handler failed`),G(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),la=J(Ce,async(t,n,r)=>{try{let t=DJ(r.docName,n,`agent-undo`);if(t===null)return;let i=nr(t),{agentId:a,agentName:o,colorSeed:c,clientName:l,clientVersion:u,label:d}=gi(r);if(LC(i)||zC(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=r,p,m;if(r.scope===`count`?(p=`count`,m=r.count):p=r.scope===`session`||r.scope===`file`?`session`:`last`,!s.hasSession(i,f)){G(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let h=await s.getSession(i,f),g=!1;try{let t=qn(l),n=Vn[t]??Vr(c??a);Ze?.setPresence(a,{displayName:o,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),g=eD(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,m),g&&sP(i,f,o,c,void 0,vi({clientName:l,clientVersion:u,label:d}))}finally{Ze?.touchMode(a,`idle`)}if(g){let e=await fr(i);if(e?.kind===`failure`){hr(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){gr(n,`agent-undo`);return}ar(i,`agent-undo`)}qe?.setFocus(f,{agentName:f,currentDoc:i,writeKind:`undo`,ts:Date.now()}),q(n,200,Ge,{docName:i,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof yw){bw(n,e,`agent-undo`);return}Y.error({err:e,requestId:cw(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`}),ua=J(g,async(e,t)=>{try{let n=lg(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,ree,KT(s,n),{handler:`agent-activity`})}catch(n){Y.error({err:n,requestId:cw(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}),ma=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=lg(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),a=n.searchParams.get(`keptCount`);if(r===null){G(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!nY(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let o=nr(i);if(LC(o)||zC(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!a||Number.isNaN(Number(a))){G(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(a);if(!Number.isInteger(c)||c<0){G(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=s.getLiveSession(o,r);if(!l){G(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let u=l.um;if(c>u.undoStack.length){G(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let d=l.dc.document.getText(`source`),{diff:f,before:p,after:m}=UT(u.undoStack,c,d,o);q(t,200,ln,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){Y.error({err:n,requestId:cw(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}),ha=J(g,async(e,t)=>{try{await Te?.(),q(t,200,Or,{},{handler:`test-flush-git`})}catch(n){Y.error({err:n,requestId:cw(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}),ga=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=nr(n.searchParams.get(`docName`)??`test-doc`),i;try{i=Ij(r,l)}catch(e){Y.error({err:e,docName:r},`[test-reset] safeContentPath rejected docName`),G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(r),a.closeConnections(r);let o=`onStoreDocument-${r}`;a.debouncer.isDebounced(o)&&await a.debouncer.executeNow(o);let c=a.documents.get(r);if(c&&await(Dt??a.unloadDocument.bind(a))(c),Ql(i,``,`utf-8`),Ie&&(Ie.deleteDocument(r),Ie.saveToDisk().catch(e=>{Y.warn({docName:r,err:e},`[backlinks] Failed to persist cache after test-reset for ${r}`)}),Ve?.(`backlinks`),Ve?.(`graph`)),n.searchParams.get(`reset-okignore`)!==`false`)try{let e=z(l,`.okignore`),t=a.documents.get(er);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},wM)}B(e)&&Ql(e,``,`utf-8`),Tt&&await Tt.rebuildIgnorePatterns()}catch(e){Y.warn({err:e},`[test-reset] okignore reset partial failure`)}Ve?.(`files`),q(t,200,Ii,{},{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}),va=J(g,async(e,t)=>{try{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await Ie.rebuildFromDisk(),await Ie.ingestGlobalSkillBundles([z(Ws,`.ok`,`skills`)]),Ie.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist cache after test-rescan-backlinks`)}),Ve?.(`backlinks`),Ve?.(`graph`),q(t,200,Nn,{},{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}),ya=J(g,async(e,t)=>{try{if(!he){G(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await he(),Ve?.(`files`),q(t,200,di,{},{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}),ba=J(f,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=gi(n),o=be?.current;if(!o){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let s=/^[a-zA-Z0-9_-]+$/,c=[],l=!1;if(Array.isArray(n.writers))try{c=n.writers.map(e=>{let t=e.id??`unknown`;if(!s.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){G(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=Oe?.()??`main`;if(c.length===0)if(e!==void 0)c=[{id:r,name:a?`${i} (${a})`:i,email:`${r}@openknowledge.local`}];else{let e=(await YS(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[uC],l=!0}let d=Fe??`.`,f=xj(typeof n.summary==`string`?n.summary:void 0),p=await EC(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 zG(o,xG(o.gitDir))}catch(e){Y.warn({err:e},`[rename-log] post-saveVersion GC failed`)}q(t,200,Pr,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(n){Y.error({err:n,requestId:cw(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`}),xa=J(g,async(e,t)=>{let n=be?.current;if(!n){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}try{let e=performance.now();await Te?.();let t=performance.now()-e;t>1e3&&Y.warn({durationMs:Math.round(t)},`[history] pre-read commit flush slow`)}catch(e){Y.warn({err:e},`[history] pre-read commit flush failed`)}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`folder`),o=r.searchParams.get(`branch`)??Oe?.()??`main`;if(!i&&a===null){G(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(o.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=Ts(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}=hn.run(u,()=>Dq(n,e.folderRel,Fe??`.`,{branch:o,limit:s,offset:l}));f&&cq(`folder`),q(t,200,ae,{...await d},{handler:`history`});return}let s=Fe??`.`,c=Zq(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}=hn.run(_,()=>Eq(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&cq(`doc`);let a=await e,c=Date.now()-v;F(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),q(t,200,ae,{...a},{handler:`history`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Sa(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=be?.current;if(!r){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,a=Fe??`.`,o=Zq(i,a);if(`error`in o){G(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=qS(r),c=Oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await WG(r,i,n,c,xG(r.gitDir),e=>Qq(e,a),TG());if(e===null){G(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let o=await s.raw(`show`,`${n}:${e}`),[l=``,u=``]=(await s.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);q(t,200,pt,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let wa=J(Se,async(t,n,r)=>{let i=yV(r,ut);if(i.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=a.documents.get(r.docName);if(o&&hw(o)){bw(n,new yw({file:ew(r.docName)}),`rollback`);return}let s=be?.current;if(!s){G(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=r,u=Fe??`.`,d=Zq(c,u);if(`error`in d){G(n,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=qS(s),p=Date.now();try{let t=xG(s.gitDir),r=TG(),o=await WG(s,c,l,Oe?.()??`main`,t,e=>Qq(e,u),r);if(o===null){G(n,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let d=await f.raw(`show`,`${l}:${o}`),m=new Date().toISOString();await hC(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=a.documents.get(c);if(!h){G(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let g=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:c}:void 0,_=await rT(d,g),v;h.transact(()=>{fS(h,d,g,_),v=Cw(h.getText(`source`).toString(),d,`rollback`)},Jq),v!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:v.intendedBytes,actualBytes:v.actualBytes,byteDelta:v.byteDelta,"actor.kind":i.kind,...i.kind===`agent`||i.kind===`principal`?{"actor.writer_id":i.writerId}:{}})),Gq(`rollback`,v);let y;switch(i.kind){case`agent`:{let e=l.slice(0,8),t=i.summary.kind===`value`,n=t?i.summary:xj(`Restored to ${e}`),r=yi(n);y=t||!r.response?r.response:wi(r.response),sP(c,i.writerId,i.displayName,i.colorSeed,id(c,l),i.actor,r.stored),AS(),Ei(n,!t);break}case`principal`:{let e=yi(i.summary);y=e.response,sP(c,i.writerId,i.displayName,i.colorSeed,id(c,l),i.actor,e.stored),Ei(i.summary,!1);break}case`anonymous`:Y.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(i.kind)}`)}Iq().add(1,{kind:`rollback`,attribution_kind:i.kind});let b=await fr(c);if(b?.kind===`failure`){hr(n,b.failure,`rollback`);return}if(b?.kind===`divergence`){gr(n,`rollback`);return}ar(c,`rollback`);let x=Date.now()-p;F(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),i.kind===`agent`&&qe?.setFocus(i.writerId,{agentName:i.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:ww(v);q(n,200,We,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Ta=J(g,async(e,t)=>{try{q(t,200,Ui,zS(),{handler:`metrics-reconciliation`})}catch(n){Y.error({err:n,requestId:cw(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}),Ea=J(g,async(e,t)=>{try{q(t,200,tr,tee(),{handler:`metrics-parse-health`})}catch(n){Y.error({err:n,requestId:cw(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}),Oa=J(g,async(e,n)=>{try{jt&&await jt.catch(e=>{Y.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=je?.(),i=iV();q(n,200,nee,{serverInstanceId:u,currentBranch:e,...r===void 0?{}:{currentDiskAckSVs:r},...i===void 0?{}:{boot:i}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),ka=O({agents:N(O({id:A(),name:A(),version:A(),description:A().optional(),license:A().optional(),iconUrl:A().optional(),website:A().optional(),source:za([`registry`,`custom`]),supported:M(),featured:M(),harness:O({cli:za([`claude`,`codex`,`cursor`,`opencode`,`pi`]),availability:za([`present`,`not-found`,`unknown`])}).optional()})),stale:M(),maxThreads:P()}),ja=J(g,async(e,t)=>{if(ht===void 0){G(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=bd(),{agents:n,stale:r}=await ht.getCatalog(),i=await gt?.()??[],a=await bt();q(t,200,ka,{agents:[...n.map(t=>{let n=pj[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:gd.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 Ma(e,t){if(!Sj(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=ut?.()??null;if(!n){G(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}q(t,200,bi,n,{handler:`principal`})}async function Na(e,t){if(!Sj(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=Ze?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);q(t,200,o,{presence:r},{handler:`metrics-agent-presence`})}catch(n){Y.error({err:n,requestId:cw(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 Pa(e,t){if(!Sj(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-effects`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-effects`,extraHeaders:{Allow:`GET`}});return}let n;try{let e=[];for(let[t,r]of a.documents){if(LC(t)||zC(t)||!r.share.has(`agent-effects`))continue;n=t;let i=r.getMap(`agent-effects`);if(i.size===0)continue;let a=[...i.values()].map(e=>{let t=0,n=0;for(let r of e.delta)typeof r.insert==`string`?t+=r.insert.length:r.insert!==void 0&&(t+=1),typeof r.delete==`number`&&(n+=r.delete);return{sessionId:e.sessionId,agentType:e.agent_type,ts:e.timestamp,insertedChars:t,deletedChars:n}}).sort((e,t)=>e.ts-t.ts);e.push({"doc.name":t,entries:a})}e.sort((e,t)=>e[`doc.name`].localeCompare(t[`doc.name`])),q(t,200,St,{effects:e},{handler:`metrics-agent-effects`})}catch(e){Y.error({err:e,"doc.name":n},`[metrics-agent-effects] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-effects`,cause:e})}}async function Ia(e,t){if(!Sj(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-watcher-recent`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-watcher-recent`,extraHeaders:{Allow:`GET`}});return}try{q(t,200,ii,{decisions:FV().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:cw(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 La(e,t){if(!Sj(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=fP.read();q(t,200,st,{entries:n,count:n.length,detection:qie(n[0])},{handler:`embed-detect`})}async function Ra(e,t){if(!Sj(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=z(l),r=n,a=!0;try{r=Kl(n)}catch(e){let r=Is(e);if(r===`ENOENT`)Y.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),a=!1;else{Y.warn({path:n,err:e},`[workspace] realpath failed for contentDir`),G(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}q(t,200,tt,{contentDir:r,pathSeparator:kl,symlinkResolved:a},{handler:`workspace`})}let Ba=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let r=vM(n),i=Tl(n).slice(1).toLowerCase();if(!r||!Fa.has(i)){G(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let a=Kl(l),o=z(a,n),s;try{s=Kl(o)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!Lj(s,a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let c;try{c=Xl(s)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!c.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let u=gM(a,s);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=Aa.has(i),f={"Content-Type":r,"Content-Length":String(c.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":yo.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`]=Ua),t.writeHead(200,f);try{await Ou(Il(s),t)}catch(e){Y.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:n,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Ha=1048576,Wa=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let r=Kl(l),i=z(r,n),a;try{a=Kl(i)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!Lj(a,r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let o;try{o=Xl(a)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!o.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(gM(r,a)!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(o.size>Ha){G(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ha}-byte text-viewer cap.`,{handler:`asset-text`});return}let s=(await uu(a)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(s)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Ga=J(g,async(e,t)=>{try{if(!be?.current){q(t,200,Br,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=z(be.current.gitDir,`rescue`);if(B(r))try{let t=Wl(r).filter(e=>KC(e));for(let i of t){let t=z(r,i),a=Xl(t);if(e-a.mtimeMs>864e5){try{Zl(t)}catch(e){Y.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:JC(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){Y.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=Oe?.()??`main`,t=await vC(be.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){Y.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}q(t,200,Br,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}),Ka=J(_t,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let r=n.path;if(!KC(r)){G(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(r.includes(`..`)||r.startsWith(`/`)||r.includes(`\0`)||r.includes(`\\`)){G(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let i=z(l),a=z(i,r);if(!Fj(a,i)){G(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let o=JC(r);if(LC(o)||zC(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`});return}if(CJ(r)||Wr(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let s=typeof n.template==`string`?n.template.trim():``,c=``,u;if(s.length>0){if(!/^[A-Za-z0-9_-]+$/.test(s)){G(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let n=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)):``,a=CN(i,n),o=a.find(e=>e.name===s);if(!o){let e=a.length===0?`(none)`:a.map(e=>`"${e.name}" (${e.scope})`).join(`, `);G(t,400,`urn:ok:error:invalid-request`,`Template "${s}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let l=z(i,o.path),d;try{d=V(l,`utf-8`)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=lr(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;c=XN(f,{date:QN(),user:p}),u=o.scope}zl(I(a),{recursive:!0});try{Ql(a,c,{encoding:`utf-8`,flag:`wx`})}catch(e){if(PJ(e)){G(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let d=JC(r);switch(Mt?.delete(d),Tt&&Tt.incrementMdDir(I(d)),EV(a,OV(c)),e.kind){case`agent`:case`principal`:sP(d,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}w?.({kind:`create`,path:a,docName:d,content:c}),Ie&&(Ie.updateDocumentFromMarkdown(d,c),Ie.saveToDisk().catch(e=>{Y.warn({docName:d,err:e},`[backlinks] Failed to persist create-page cache for ${d}`)}),Ve?.(`backlinks`),Ve?.(`graph`)),Ve?.(`files`),u!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:s,templateScope:u,docName:d})),q(t,200,ge,{docName:d},{handler:`create-page`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),qa=J(et,async(e,t,n)=>{try{if(yV(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!SJ(e)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(CJ(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=kJ(l,`folder`,e);if(B(r)){G(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Ko(r,{recursive:!0}),wn(e),Ve?.(`files`),q(t,200,ot,{path:e},{handler:`create-folder`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),E=J(Ot,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:r}=n,i=n.path,o=r===`file`?JC(i):i;if(!SJ(i)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(CJ(i)||r===`file`&&(LC(o)||zC(o))||r===`folder`&&wJ(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}r===`file`&&GJ(l,i);let s=kJ(l,r,i);if(!B(s)){if(r===`file`){let e=kJ(l,`folder`,i);if(B(e)&&Xl(e).isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}}G(t,404,`urn:ok:error:doc-not-found`,`${r} does not exist.`,{handler:`duplicate-path`});return}let c=Xl(s);if(r===`file`&&!c.isFile()||r===`folder`&&!c.isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}let u=r===`file`?[zJ(l,i)]:oi(kJ(l,`folder`,i)),d=$e?.(),f=new Set(d?d.getConflicts().map(e=>e.file):[]);for(let e of u){let n=e,r=a.documents.get(n),i=ew(n),o=r!==void 0&&hw(r),s=f.has(i);if(o||s){bw(t,new yw({file:i}),`duplicate-path`);return}}let p,m=[];if(r===`file`){let e=Tl(s);if(p=VJ(l,o).docName,LC(p)||zC(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=BJ(l,p,e),r=V(s,`utf-8`),i=I(n),a=B(i);try{Ko(i,{recursive:!0}),ts(n,r,{encoding:`utf-8`,flag:`wx`})}catch(e){if(PJ(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{qo(i)}catch(e){let t=Is(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&Y.warn({destinationDir:i,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let c=!1;try{QC(p,e),Mt?.delete(p),Tt&&(Tt.incrementMdDir(I(p)),c=!0),EV(n,OV(r)),w?.({kind:`create`,path:n,docName:p,content:r}),Ie?.updateDocumentFromMarkdown(p,r),m=[p]}catch(e){try{Xo(n,{force:!0})}catch(e){Y.warn({destinationPath:n,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw nw(p),Tt&&c&&Tt.decrementMdDir(I(p)),w?.({kind:`delete`,path:n,docName:p}),e}}else{if(p=HJ(l,i).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=kJ(l,`folder`,p);try{Yo(s,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(PJ(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 WJ(l,p))wn(e);let e=UJ(l,p);m=e.map(e=>e.docName);for(let t of e){let e=Tl(t.fullPath);QC(JC(t.docName),e),Mt?.delete(t.docName),Tt&&Tt.incrementMdDir(I(t.docName)),EV(t.fullPath,OV(t.content)),w?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),Ie?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{Xo(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)sP(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}Ie&&m.length>0&&(Ie.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist duplicate-path cache`)}),Ve?.(`backlinks`),Ve?.(`graph`)),Ve?.(`files`),q(t,200,pee,{kind:r,path:p,duplicatedDocNames:m},{handler:`duplicate-path`})}catch(e){if(e instanceof NJ){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=FJ(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`}),Ja=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){G(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!nY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=Bn(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,Xt,{docName:n,headings:tY(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}),Ya=J(Gt,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:r,fromPath:i,toPath:o}=n;if(!SJ(i)||!SJ(o)){G(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(r===`file`&&(LC(i)||LC(o)||zC(i)||zC(o))){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(CJ(i)||CJ(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(i===o){q(t,200,nn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let s=r===`asset`&&KC(i)&&KC(o)?`file`:r;if(s===`asset`){let n;try{n=KC(i)&&!KC(o)?await pi(i,o):await ui(i,o)}catch(e){if(e instanceof yw){bw(t,e,`rename-path`);return}let{status:n,type:r,error:i}=Mr(e);G(t,n,r,i,{handler:`rename-path`,cause:e});return}n.renamedAssets.length>0&&An();let r;if(n.renamedAssets.length>0&&n.rewrittenDocs.length>0){let t=`Renamed asset ${i} → ${o}`;r=Oi(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{Y.debug({kind:`asset`,fromPath:i,toPath:o,affectedDocs:n.rewrittenDocs.length,affectedAssets:n.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(Iq().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Ee)try{await Ee()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}q(t,200,nn,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}s===`file`&&GJ(l,i);let c=s===`file`?[zJ(l,i)]:oi(kJ(l,`folder`,i)),u=$e?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of c){let n=e,r=a.documents.get(n),i=ew(n),o=r!==void 0&&hw(r),s=d.has(i);if(o||s){bw(t,new yw({file:i}),`rename-path`);return}}if(Tt){let e=KC(i)?Tl(i):$C(i);if(s===`file`?Tt.isExcluded(KC(o)?o:`${o}${e}`):Tt.isDirExcluded(o)){G(t,400,`urn:ok:error:invalid-request`,`Destination ${s===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let f=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,p;try{p=await mi(i,o,s,f?{actor:f}:{})}catch(e){if(e instanceof MF){G(t,409,`urn:ok:error:doc-already-exists`,jr(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,nn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&An();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=Oi(e,`Renamed ${i} → ${o}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:od(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{Y.debug({kind:r,fromPath:i,toPath:o,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),Iq().add(1,{kind:`rename-${s}`,attribution_kind:e.kind}),Ee)try{await Ee()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}q(t,200,nn,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=Mr(e);G(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),D=J(Me,async(e,t,n)=>{try{gi(n);let{kind:e,path:r}=n;if(!SJ(r)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let i=e===`asset`?ai(r):{path:r,ambiguous:!1};if(i.ambiguous){G(t,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=i.path,s=e===`asset`&&KC(o)?`file`:e;if(s===`file`&&GJ(l,o),CJ(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let c=s===`asset`?kJ(l,`folder`,o):kJ(l,s,o);if(!B(c)){G(t,404,`urn:ok:error:doc-not-found`,`${s} does not exist.`,{handler:`delete-path`});return}let u=Xl(c);if(s===`file`&&!u.isFile()||s===`asset`&&!u.isFile()||s===`folder`&&!u.isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${s}.`,{handler:`delete-path`});return}let d=s===`asset`?[]:s===`file`?[zJ(l,o)]:oi(kJ(l,`folder`,o)),f=$e?.(),p=new Set(f?f.getConflicts().map(e=>e.file):[]);for(let e of d){let n=e,r=a.documents.get(n),i=ew(n),o=r!==void 0&&hw(r),s=p.has(i);if(o||s){bw(t,new yw({file:i}),`delete-path`);return}}if(await Ir(d,`deleted-upstream`),Mt)for(let e of d)LC(e)||zC(e)||(Mt.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));s===`file`||s===`asset`?Vo(c):(Xo(c,{recursive:!0,force:!1}),Dn(o)),An();for(let e of d)w?.({kind:`delete`,path:z(l,ew(e)),docName:e});Ve?.(`files`),q(t,200,Je,{deletedDocNames:d},{handler:`delete-path`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Xa=J(xi,async(e,t,n)=>Po(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":Jo(n.path),"ok.cleanup.path.role":$o(n.path)}},async()=>{try{if(yV(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:r}=n;if(!SJ(r)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&KC(r)?`file`:e,a=JC(r);i===`file`&&GJ(l,r);let o=i===`folder`&&wJ(r);if(i===`file`&&(LC(a)||zC(a))||o||CJ(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(i===`asset`){An(),Ve?.(`files`),q(t,200,Re,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let s=m(),c=i===`file`?s.has(a)?[a]:[]:TJ(s,i,r);if(An(),c.length===0){q(t,200,Re,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Ir(c,`deleted-upstream`),Mt)for(let e of c)LC(e)||zC(e)||(Mt.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of c)w?.({kind:`delete`,path:z(l,ew(e)),docName:e});i===`folder`&&Dn(r),Ve?.(`files`),q(t,200,Re,{deletedDocNames:c},{handler:`trash-cleanup`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Za=J(g,async(e,t)=>{try{let e=m(),n=[];for(let[t,r]of e){let e=$C(t),i,a;if(r.title!==void 0)i=r.title,a=r.icon;else{i=t;try{let n=V(z(l,`${t}${e}`),`utf-8`);i=lL(n,t),a=uL(n)}catch(e){Y.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:i,docExt:e,size:r.size,modified:r.modified,icon:a})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),q(t,200,De,{pages:n},{handler:`pages`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),k=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!nY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(LC(n)||zC(n)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${n}' is a reserved document name.`,{handler:`suggest-links`});return}q(t,200,C,await eq({hocuspocus:a,fileIndex:m(),docName:n}),{handler:`suggest-links`})}catch(e){if(e instanceof NK){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 Qa(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 cJ(e,T??l)}catch(e){if(e instanceof sB){G(t,cB(e.reason),e.reason,uB(e.reason),{handler:`upload-asset`,cause:e});return}G(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:r,tempPath:i,sha:a,byteLength:o,parentDocName:s,placement:c}=n,u=()=>{if(B(i))try{Zl(i)}catch{}},d=JP(xt,{parentDocName:s,placement:c||void 0},t,{handler:`upload-asset`});if(!d.ok){u();return}let{parentDocName:f,placement:p}=d.value,{agentId:m,agentName:g}=gi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(o===0){u(),G(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(f.includes(`\0`)||f.includes(`..`)||f.startsWith(`/`)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let _=z(l),v;try{v=p===`parent-dir`?`./`:h?.()??`./`}catch(e){u(),Y.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),G(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!Va(v)){u(),G(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let y=rJ(f,Da(v),_);if(!Lj(y,_)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{OJ(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{zl(y,{recursive:!0})}catch(e){if(!PJ(e)){u();let n=lB(e);G(t,cB(n),n,uB(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=Kl(y),n;try{n=Kl(_)}catch{n=_}if(!Lj(e,n)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(Is(e)!==`ENOENT`){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let b=iJ(i,4100),x=await uj(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 sJ(y,a,o);if(n){u();let r=Pj(R(l,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:m,agentName:g,dedup:!0,mime:S??null,size:o,destPath:r,httpStatus:200},`[upload] dedup hit`),q(t,200,_n,{src:n,path:r,deduped:!0},{handler:`upload-asset`});return}}let w;if(!r||r===`upload`||$q.test(r)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=r?Tl(r).slice(1):``,n=C??t??``;w=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else w=nJ(r);try{let n=hB(i,y,w),r=Pj(R(l,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:m,agentName:g,dedup:!1,mime:S??null,size:o,destPath:r,httpStatus:200},`[upload] write ok`),q(t,200,_n,{src:n,path:r,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof sB?n.reason:`urn:ok:error:storage-error`;Y.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:cw(e),agentId:m,agentName:g,filename:w,size:o,reason:r,httpStatus:cB(r),err:n},`[upload] write failed`),G(t,cB(r),r,uB(r),{handler:`upload-asset`,cause:n})}}let $a=`/api/local-op/clone`,eo=`/api/local-op/ok-init`,to=600*1e3,no={stdio:[`ignore`,`ignore`,`pipe`]},ro={stdio:[`ignore`,`pipe`,`pipe`]},io={stdio:`ignore`},ao=`local-op-clone`,j=J(Ue,oo,{handler:ao,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ao})});async function oo(e,t,n){let{url:r,dir:i,branch:a}=n;if(!UU(r)){G(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:ao,cause:Error(`url=${r}`)});return}if(!qU(i)){G(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:ao,cause:Error(`dir=${i}`)});return}if(!fn.tryAcquire($a)){G(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:ao,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=pw(t,ao),s=null,c=fW({cliArgs:it,url:r,dir:i,branch:a,timeoutMs:to,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&Y.warn({stderr:ML(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=oW(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(ML(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 so(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:ao},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),fn.release($a)}})(),t.on(`close`,()=>{c.cancel()})}async function so(e,t){let n=z(WU(e)),r=SM(n),i=iB(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=it,s=e=>{let n=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...o,e,...n]},c=async e=>{let t=bl(a,s(e),zP({...no,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 ku(500);let t=iB(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=As(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=As(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 co=`local-op-ok-init`,lo=J(ta,async(e,t,n)=>{let{projectPath:r}=n;if(!El(r)){G(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:co,cause:Error(`projectPath=${r}`)});return}let i;try{i=Kl(r)}catch(e){q(t,200,_a,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:co});return}if(!qU(i)){G(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:co,cause:Error(`projectPath=${r}`)});return}let a=zu(i).kind;if(a!==`directory`&&a!==`linked`){Y.warn({project:Cl(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${Cl(i)} result=not-a-git-worktree kind=${a}`),q(t,200,_a,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:co});return}if(lH(i)){Y.warn({project:Cl(i),result:`already-initialized`},`[ok-init] action=init project=${Cl(i)} result=already-initialized`),q(t,200,_a,{ok:!0,projectPath:i},{handler:co});return}if(!fn.tryAcquire(eo)){G(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:co,extraHeaders:{"Retry-After":`2`}});return}try{await _s(async()=>{BH(i)}),Y.warn({project:Cl(i),result:`success`},`[ok-init] action=init project=${Cl(i)} result=success`),q(t,200,_a,{ok:!0,projectPath:i},{handler:co})}catch(e){let n=e instanceof Error?e.message:String(e);Y.warn({project:Cl(i),result:`failed`,reason:n},`[ok-init] action=init project=${Cl(i)} result=failed reason=${n}`),q(t,200,_a,{ok:!1,reason:`init-failed`,message:n},{handler:co})}finally{fn.release(eo)}},{handler:co,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:co})}),uo=`/api/local-op/auth/login`,fo=`/api/local-op/auth/status`,po=`/api/local-op/auth/repos`,mo=`/api/local-op/auth/signout`,ho=`/api/local-op/auth/pat`,go=`/api/local-op/auth/gh-login`,_o=at??15e3,vo=960*1e3,Co=()=>_L(T??l),To={current:null},Eo={current:null};function Do(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!fn.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=pw(t,n),l=e=>{if(!(t.writableEnded||t.destroyed))try{t.write(e)}catch{}},u=setInterval(()=>{l(`${JSON.stringify({type:`ping`})}\n`)},_o);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}qq(e,$e),l(`${JSON.stringify(e)}\n`)});i.current=f;let p=()=>{d(),i.current===f&&console.warn(JSON.stringify({event:`ok-local-op:auth-stream-detached`,channel:`auth`,transport:`http`,handler:n}))};t.on(`close`,p),f.done.finally(()=>{if(d(),t.off(`close`,p),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===f&&(i.current=null,fn.release(r))})}let Oo=`local-op-auth-login`,ko=J(Xi,jo,{handler:Oo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Oo})});async function jo(e,t,n){let r=n.host??Co();Do({res:t,handler:Oo,guardKey:uo,inFlight:To,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>eW({cliArgs:it,host:r,timeoutMs:vo,onEvent:e})})}let Mo=`local-op-auth-gh-login`,No=J(Xi,async(e,t,n)=>{let r=n.host??Co(),i=await bW();if(i===null){G(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:Mo});return}Do({res:t,handler:Mo,guardKey:go,inFlight:Eo,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>CW({host:r,ghPath:i,timeoutMs:vo,onEvent:e})})},{handler:Mo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Mo})}),Fo=`local-op-auth-cancel`,Io=J(aee,OH(async(e,t,n)=>{let r=n.channel===`gh-login`?{inFlight:Eo,guardKey:go}:{inFlight:To,guardKey:uo},i=r.inFlight.current;i&&(i.cancel(),r.inFlight.current=null,fn.release(r.guardKey)),q(t,200,Gr,{},{handler:Fo})},{handler:Fo,title:`Failed to cancel the sign-in.`}),{handler:Fo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Fo})}),Ro=`local-op-auth-status`,zo=J(Xi,async(e,t,n)=>{let r=n.host??Co();if(!fn.tryAcquire(fo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Ro,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=it,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=bl(e,i,zP({...ro,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,r.kill(`SIGTERM`)},3e4),s=[];r.stdout.on(`data`,e=>s.push(e)),r.on(`close`,()=>{if(clearTimeout(o),a){n(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(s).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
|
|
1227
1227
|
`).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}let s=await bW()!==null;o===null?q(t,200,Zr,{authenticated:!1,ghAvailable:s},{handler:Ro}):q(t,200,Zr,{...o,ghAvailable:s},{handler:Ro})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Ro,cause:e})}finally{fn.release(fo)}},{handler:Ro,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ro})}),Bo=`local-op-auth-pat`,Ho=J(cee,async(e,t,n)=>{let r=n.host??Co();if(!fn.tryAcquire(ho)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:Bo,extraHeaders:{"Retry-After":`5`}});return}try{let e=await tW({cliArgs:it,host:r,token:n.token});e.ok?(Kq($e),q(t,200,cr,{host:e.host,login:e.login},{handler:Bo})):G(t,400,`urn:ok:error:auth-failed`,e.error,{handler:Bo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:Bo,cause:e})}finally{fn.release(ho)}},{handler:Bo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Bo})}),Uo=`local-op-auth-repos`,Wo=J(Xi,Go,{handler:Uo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Uo})});async function Go(e,t,n){let r=n.host??Co();if(!fn.tryAcquire(po)){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=pw(t,Uo),[a,...o]=it,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=bl(a,s,zP({...ro,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},to);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
|
|
1228
|
-
`);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{Y.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),fn.release(po))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),fn.release(po))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),fn.release(po))})}let Zo=`local-op-auth-signout`,Qo=J(Xi,async(e,t,n)=>{let r=n.host??Co();if(!fn.tryAcquire(mo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Zo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=it,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=bl(e,i,zP({...io,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,Gr,{},{handler:Zo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Zo,cause:e})}finally{fn.release(mo)}},{handler:Zo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zo})}),es=`/api/local-op/auth/set-identity`,ns=`local-op-auth-set-identity`,rs=J(_i,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:ns});return}if(!fn.tryAcquire(es)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ns,extraHeaders:{"Retry-After":`5`}});return}try{DH(T,r,i),$e?.()?.refreshIdentity().catch(()=>{}),q(t,200,Gr,{},{handler:ns})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ns,cause:e})}finally{fn.release(es)}},{handler:ns,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ns})});async function is(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();if(!e){q(t,200,Rr,{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,Rr,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 ls=J(d,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,Nr,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function ds(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();q(t,200,le,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let fs=J(re,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,dt,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function ps(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!T){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let o=JC(i),s=a.documents.get(o)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=$e?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){G(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=gs({baseDir:T,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),o=JC(i),s=a.documents.get(o),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Ft?Ft(o):null;t!==null&&(c=t,l=!0)}else{$z(L(T,i),T);try{c=V(L(T,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,zt,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),o=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=JC(i),t=a.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=Ft?Ft(e):null;t!==null&&!Xq(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Y.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(t,200,zt,{file:i,base:o,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function hs(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=sK(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,oa,{plan:await CK({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof YG){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof XG){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 vs=J(fa,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=sK(a);if(typeof a==`string`&&a.length>0&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,Pt,{result:await vK(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function ys(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,x,{packs:lK()},{handler:`seed-packs`})}}let bs=J(fee,async(e,t,n)=>{if(n.out!==void 0&&!qU(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,Ln,await OR({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function xs(e,t){if(r(e,t,{handler:`installed-agents`}))try{await kae(e,t,Fn.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:cw(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let Ss=J(g,async(e,t)=>{if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,Er,{tags:Le.getAllTags()},{handler:`tags-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Cs(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let r;try{r=decodeURIComponent(n)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){G(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=Le.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:Un(e),matchingTags:t,snippet:null}));q(t,200,Di,{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 Ts(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=z(l),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${kl}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let Es=/^[A-Za-z0-9_-]+$/;function Ds(e,t,n=`template`){return!e||!Es.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 Os(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}${kl}`))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 ks(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 js=kH({GET:J(g,async(e,t)=>{try{let n=Ts(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await PN(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,fj.parse)(await uu(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,Ht,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:J(fe,async(e,t,n)=>{try{if(on){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=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Ts(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=yie({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`&&(Ai(e,ki(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await ji(`folder-config-put`))}q(t,200,oe,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function Ms(e,t,n,r){if(!t)return!1;let i=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=a.documents.get(i);return o&&hw(o)?(bw(r,new yw({file:`${i}.md`}),n),!0):!1}function Ns(e,t,n){let r=a.documents.get(e);return r&&hw(r)?(bw(n,new yw({file:`${e}.md`}),t),!0):!1}let Ps=J(g,OH(async(e,t)=>{let n=wN(z(l));q(t,200,hi,{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}),Fs=e=>{let{body:t}=ia(e);return{frontmatter:rt(e)??{},body:t}},Ls=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ds(r,t,`template-get`))return;let i=Ts(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Os(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=xn(await uu(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,li,{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}),Rs=J(see,async(e,t,n)=>{try{if(on){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Ds(r,t,`template-put`))return;let i=Ts(n.folder,t,`folder`,`template-put`);if(!i||Ms(i.folderRel,r,`template-put`,t))return;let a=eP({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:ks(n.frontmatter)});if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!B(o),l=R(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=Xs(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=gi(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{dS(h.dc.document,a.content,`agent`)},h.origin);let g=await fr(u);if(g?.kind===`failure`){hr(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){gr(t,`template-put`);return}Ai(e,ki(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await ji(`template-put`),q(t,200,or,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),zs=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ds(r,t,`template-delete`))return;let i=Ts(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=yV({agentId:a.get(`agentId`)??void 0,agentName:a.get(`agentName`)??void 0,colorSeed:a.get(`colorSeed`)??void 0,clientName:a.get(`clientName`)??void 0,clientVersion:a.get(`clientVersion`)??void 0,label:a.get(`label`)??void 0,summary:a.get(`summary`)??void 0},ut);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Ms(i.folderRel,r,`template-delete`,t))return;await Ir([Xs(i.folderRel,r)],`deleted-upstream`);let s=Nie({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&&(Ai(o,ki(`template`,i.folderRel,r),`template-delete: ${s.path}`),await ji(`template-delete`)),q(t,200,jn,{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}),Bs=kH({GET:Ls,PUT:Rs,POST:J(uee,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Ds(n.fromName,t,`template-move`)||!Ds(n.toName,t,`template-move`))return;let r=Ts(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Ts(n.toFolder,t,`folder`,`template-move`);if(!i||Ms(r.folderRel,n.fromName,`template-move`,t))return;await Ir([Xs(r.folderRel,n.fromName)],`renamed`);let a=await Pie({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await $J(T,e,t);return n||QJ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Os(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=lr(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=Mie({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ks(n.frontmatter)});t.ok||(o=t.error)}}if(Ai(e,ki(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await ji(`template-move`),Ve?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,Ji,{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:zs},{handler:`template`}),Vs=J(Pi,async(e,t,n)=>{try{if(on){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!nY(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=nr(r);if(LC(i)||zC(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let o=kJ(l,`file`,i);if(!B(o)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let c=a.documents.get(i);if(n.deleteSource){let e=$e?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=c!==void 0&&hw(c),a=n.has(r);if(i||a){bw(t,new yw({file:r}),`template-import`);return}}let u=``;if(c)u=c.getText(`source`).toString();else{let e=await a.openDirectConnection(i);try{let n=e.document;if(!n){G(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=AJ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Ds(d,t,`template-import`))return;let f=Ts(n.targetFolder,t,`folder`,`template-import`);if(!f||Ms(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=ia(u),h=Lt(p),g={};try{h.trim()&&(g=(0,fj.parse)(h))}catch{}let _=n.title||g?.title||lL(u,d),v=g?.description||``,y=Array.isArray(g?.tags)?g.tags:[],b={...g};delete b.template,delete b.title;let x=``;Object.keys(b).length>0&&(x=`${(0,fj.stringify)(b).trim()}\n`),x=x?`---\n${x}---\n${m}`:m;let S=eP({name:d,body:x,frontmatter:{title:_,description:v,tags:y}});if(!S.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:S.error.code,cause:Error(S.error.message)});return}let C=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),ee=!B(C),te=R(f.resolvedContentDir,C).split(/[\\/]/).filter(Boolean).join(`/`),ne=Xs(f.folderRel,d),{agentId:re,agentName:ie,colorSeed:ae,clientName:oe}=gi(n),se=await s.getSession(ne,re,{displayName:ie,colorSeed:ae,clientName:oe});se.dc.document.transact(()=>{dS(se.dc.document,S.content,`agent`)},se.origin);let ce=await fr(ne);if(ce?.kind===`failure`){hr(t,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){gr(t,`template-import`);return}Ai(e,ki(`template`,f.folderRel,d),`template-import: ${te}`),n.deleteSource&&(await Ir([i],`deleted-upstream`),Mt&&Mt.setDeleted(i),Vo(o),w?.({kind:`delete`,path:o,docName:i})),await ji(`template-import`),Ve?.(`files`),q(t,200,Wn,{path:te,created:ee,warnings:S.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Hs(e,t,n){return!e||e.length>64||!mt.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function Us(e,t,n){let r=Ci.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 Ws=ft??nu();function Gs(e){return z(e===`global`?Ws:l,`.ok`,`skills`)}let Ks=LL.project;function qs(){if(!T)return null;let e=[],t=null;for(let n of He){let r=en[n];if(!r)continue;let i=z(T,...r.split(`/`),Ks);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 Js(){let e=qs();if(!e)return null;let t;try{let{frontmatter:n}=Fs(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Ks,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Ys(e,t,n){return zL(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 Xs(e,t){return`${Mn}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Zs(e){return e===`navigation`||e===`relevance`?e:void 0}function Qs(e,t){return R(t===`global`?Ws:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function $s(e){return e===`global`?Ws:T}async function ec(e,t){let n=await vF(e,t);return _z(t,e,He),n!==null}function tc(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=Wl(e,{withFileTypes:!0})}catch(r){return F(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!mt.test(a.name))continue;if(n.length>=500){i=!0;break}let r=z(e,a.name,`SKILL.md`);if(!B(r))continue;let o,s;try{let{frontmatter:e}=Fs(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:Qs(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let nc=J(g,OH(async(e,t)=>{let n=tc(Gs(`project`),`project`),r=tc(Gs(`global`),`global`),i=T?hF(T).skills:{},a=hF(Ws).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=kz(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Ks)?null:Js();q(t,200,Vi,{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}),rc=O({managed:M().nullable(),importable:P().int().nonnegative()}),ic=()=>({managed:T?MR(T)?.manageEditorSkills??null:null,importable:T?Wz({projectDir:T,skillsRoot:Gs(`project`)}):0}),ac=kH({GET:J(g,async(e,t)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,rc,ic(),{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 NR(T,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await Gz({projectDir:T,skillsRoot:Gs(`project`)});e.adopted.length+e.collided.length>0&&Ve?.(`files`)}q(t,200,rc,ic(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),oc=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Hs(r,t,`skill-get`))return;let i=Us(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Ks&&i===`project`){let e=qs();if(e){let{frontmatter:n,body:a}=Fs(await uu(e.skillMd,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:e.relPath,frontmatter:{name:typeof n.name==`string`?n.name:r,description:typeof n.description==`string`?n.description:``},body:a,files:xz(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Gs(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}=Fs(await uu(o,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:Qs(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:xz(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}),sc=J(qt,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Hs(n.name,t,`skill-put`)||Ys(n.name,t,`skill-put`))return;let r=VN({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=Gs(n.scope),a=z(i,n.name,`SKILL.md`),o=!B(a),c=R(i,a).split(/[\\/]/).filter(Boolean).join(`/`),l=pr(n.scope,n.name);if(Ns(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{dS(m.dc.document,r.content,`agent`)},m.origin);let h=await fr(l);if(h?.kind===`failure`){hr(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){gr(t,`skill-put`);return}n.scope===`project`&&(Ai(e,ki(`skill`,``,n.name),`${o?`skill-create`:`skill-edit`}: ${c}`),await ji(`skill-put`)),Ve?.(`files`),q(t,200,an,{path:c,created:o,warnings:r.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),cc=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Hs(r,t,`skill-delete`)||Ys(r,t,`skill-delete`))return;let i=Us(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Gs(i),o=n.searchParams,s=yV({agentId:o.get(`agentId`)??void 0,agentName:o.get(`agentName`)??void 0,colorSeed:o.get(`colorSeed`)??void 0,clientName:o.get(`clientName`)??void 0,clientVersion:o.get(`clientVersion`)??void 0,label:o.get(`label`)??void 0,summary:o.get(`summary`)??void 0},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Ir([pr(i,r)],`deleted-upstream`);let c=Tie({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`&&(Ai(s,ki(`skill`,``,r),`skill-delete: ${c.path}`),await ji(`skill-delete`)),Ve?.(`files`));let l=$s(i);l&&await ec(l,r),q(t,200,nt,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),lc=kH({GET:oc,PUT:sc,POST:J(Qt,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Hs(n.fromName,t,`skill-move`)||!Hs(n.toName,t,`skill-move`)||Ys(n.fromName,t,`skill-move`)||Ys(n.toName,t,`skill-move`))return;let r=Gs(n.scope);await Ir([pr(n.scope,n.fromName)],`renamed`);let i=await Eie({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await $J(T,e,t);return n||QJ(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=Fs(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=Sie({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{mc(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=Qs(z(r,n.fromName),n.scope),p=Qs(z(r,n.toName),n.scope);n.scope===`project`&&(Ai(e,ki(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await ji(`skill-move`));let m=$s(n.scope);if(m){let e=await vF(m,n.fromName);if(e){let t=iz(e.hosts);_z(n.fromName,m,t);let i=gz(z(r,n.toName),n.toName,m,t);await _F(m,n.toName,{...e,hosts:i})}}if(Ve?.(`files`),a){let e=a.code===`WRITE_ERROR`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:a.code,cause:Error(a.message)});return}q(t,200,ke,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),DELETE:cc},{handler:`skill`});function uc(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 dc(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function fc(e,t){let n=t.replace(/\.md$/i,``);return`${Xr(e).replace(/\/SKILL$/,``)}/${n}`}function pc(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of Wl(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 mc(e,t,n){if(!Ie)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{Ie.deleteDocument(e),Le?.deleteDocument(e);return}Ie.renameDocument(e,t,r),Le?.renameDocument(e,t,r)};r(Xr(t),Xr(n),z(e,n,`SKILL.md`));for(let i of pc(e,n))r(fc(t,i),fc(n,i),z(e,n,i));Ve?.(`backlinks`),Ve?.(`graph`)}let hc=kH({GET:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Hs(r,t,`skill-file-get`))return;let i=Us(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Ks&&i===`project`?qs():null,s=o&&a===`SKILL.md`?`reference`:uc(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(Gs(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${kl}`)){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?gn.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 uu(u);if(f.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,yt,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:J(ve,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Hs(n.name,t,`skill-file-put`)||Ys(n.name,t,`skill-file-put`))return;let r=uc(n.path);if(r===null){G(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=Gs(n.scope);if(!B(z(i,n.name,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=n.path.replace(/\\/g,`/`),o=dc(n.scope,r,a),c;if(o){let e=fc(n.name,a);if(Ns(e,`skill-file-put`,t))return;if(c=!B(z(i,n.name,a)),c&&UN(z(i,n.name))>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:o,colorSeed:l,clientName:u}=gi(n),d=await s.getSession(e,r,{displayName:o,colorSeed:l,clientName:u});d.dc.document.transact(()=>{dS(d.dc.document,n.content,`agent`)},d.origin);let f=await fr(e);if(f?.kind===`failure`){hr(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){gr(t,`skill-file-put`);return}}else{let e=Cie({skillsRoot:i,name:n.name,relPath:a,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}n.scope===`project`&&(Ai(e,ki(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${a}`),await ji(`skill-file-put`)),Ve?.(`files`),q(t,200,Pe,{path:a,created:c,kind:r,content:o},{handler:`skill-file-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!Hs(r,t,`skill-file-delete`)||Ys(r,t,`skill-file-delete`))return;let i=Us(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=uc(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=yV({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=Gs(i);dc(i,o,a)&&await Ir([fc(r,a)],`deleted-upstream`);let l=wie({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`&&(Ai(s,ki(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await ji(`skill-file-delete`)),l.existed&&Ve?.(`files`),q(t,200,ct,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),gc=J(At,async(e,t,n)=>{try{let e=Gs(n.scope);if(!Hs(n.name,t,`skill-install`)||Ys(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=$s(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=uz(i,n.name);if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${a.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let o=n.scope===`global`?n.targets?He.filter(e=>n.targets?.some(t=>t===e)):[...He]:n.targets===void 0?fz(r,Zz(r)??void 0):He.filter(e=>n.targets?.some(t=>t===e)),s=[],c=[];o.length===0&&n.targets===void 0&&(s.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),c.push(`no-targets`)),a.hasScripts&&(s.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),c.push(`scripts-present`));let l=iz(hF(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&_z(n.name,r,l);let u=gz(i,n.name,r,o);u.length===0?await vF(r,n.name):await _F(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),Ve?.(`files`),q(t,200,v,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),_c=J(bn,async(e,t,n)=>{try{if(!Hs(n.name,t,`skill-uninstall`)||Ys(n.name,t,`skill-uninstall`))return;let e=$s(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 ec(e,n.name);Ve?.(`files`),q(t,200,wt,{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`}),vc=kH({GET:J(g,OH(async(e,t)=>{let n=T?Zz(T):null;q(t,200,Be,{targets:fz(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(mn,OH(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=fz(T,Zz(T)??void 0),o=Gs(`project`);await Qz(T,r);let{reprojected:s,bundleHosts:c}=await Jz({projectDir:T,skillsRoot:o,targets:r});Ve?.(`files`),q(t,200,dn,{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`}),yc=J(we,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Hs(n.name,t,`skill-restore`)||Ys(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=be?.current;if(!r){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await AK({shadow:r,contentDir:l,contentRoot:Fe??`.`,name:n.name,version:n.version});if(!i.ok){let[e,n]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[i.code];G(t,e,n,i.error,{handler:`skill-restore`,detail:i.code});return}let a=[],o=uz(z(l,`.ok`,`skills`,n.name),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),a.push("Run `install` to push the restored version to your editors."),Ai(e,ki(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await ji(`skill-restore`),Ve?.(`files`),q(t,200,Ke,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),bc=J(c,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!Hs(n.name,t,`skill-update`)||Ys(n.name,t,`skill-update`))return;if(!Sz(n.name)){G(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let r=Dz(n.name);if(r===null||r.version===void 0){G(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let i=z(Gs(`project`),n.name,`SKILL.md`);if(!B(i)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let a;try{a=wz(V(i,`utf-8`))}catch{}let o,c=be?.current;if(c)try{let e=Oe?.()??`main`;o=(await EC(c,Fe??`.`,[uC],e,`Before updating ${n.name} (${a??`unversioned`} → ${r.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=pr(`project`,n.name);if(Ns(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{dS(m.dc.document,r.content,`agent`)},m.origin);let h=await fr(l);if(h?.kind===`failure`){hr(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){gr(t,`skill-update`);return}Ai(e,ki(`skill`,``,n.name),`skill-pack-update: ${n.name} (${a??`unversioned`} → ${r.version})`),await ji(`skill-update`),Ve?.(`files`),q(t,200,$n,{name:n.name,version:r.version,...a===void 0?{}:{previousVersion:a},...o===void 0?{}:{checkpointRef:o}},{handler:`skill-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function xc(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])=>It({kind:`folder`,path:e,modifiedTs:t}))}function Sc(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 Cc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function wc(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 Tc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Ec(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Dc(e,t,n,r){let i=r.documents.filter(e=>!ur(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Ut?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Ut.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Ut.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Wt?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Ut.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function Oc(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Sc(e.document.content,t):void 0}}async function kc(e){let t=performance.now();if(Rc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await zc(),i=await Dc(e.query,e.intent,e.semanticParam,n),a=se(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>Oc(t,e.query)),o;if(i.status){let t=a.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),n=t>0;o={...i.status,applied:n},rae({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 Ac(){let e=Gs(`project`);if(!B(e))return[];let t;try{t=Wl(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!mt.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=Xl(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function jc(){let e=[];for(let t of Ac()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=Fs(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(It({kind:`page`,path:pr(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function Mc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Nc=new Map;async function Pc(){let e=[],t=[],n=new Set;for(let[r,i]of S()){if(LC(r)||zC(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(It({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=Mc(i),o=Nc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await uu(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=lL(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=It({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Nc.set(r,{key:a,doc:u}),e.push(u)}for(let e of Nc.keys())n.has(e)||Nc.delete(e);let r=mJ(),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`),Hq().add(1)),{documents:[...e,...jc(),...i,...xc([...e,...i])],truncated:a}}function Fc(){return Ac().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Ic(){return te?`gen:${te()}|skills${Fc()}`:`${[...S()].filter(([e])=>!LC(e)&&!zC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Mc(t)}`).join(``)}|skills${Fc()}`}let Lc=jt===void 0;jt?.then(()=>{Lc=!0},e=>{Lc=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Rc(){return!Lc}async function zc(){let e=`${l}${T??``}`,t=Ic(),n=eY.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 Pc();if(!e)return Wq().add(1,{mode:`cold`}),{corpus:ra(t),truncated:n};let a=ee(e,t);if(a.rebuilt){Wq().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 Wq().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}})();eY.set(e,{fingerprint:t,pending:a});try{let n=await a;return eY.get(e)?.pending===a&&eY.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw eY.get(e)?.pending===a&&eY.delete(e),t}}function Bc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{zc().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}Bc();let Vc=kH({GET:J(g,OH(async(e,t)=>{let n=ws(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Cc(n.get(`intent`)),o=Zs(n.get(`ranking`)),s=wc(n.get(`scope`)??n.get(`scopes`)),c=Tc(n.get(`semantic`)),l=Ec(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,p,await kc({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(lee,OH(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Cc(n.intent),a=Zs(n.ranking),o=wc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Tc(n.semantic),l=Ec(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,p,await kc({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`}),Hc=J(g,OH(async(e,t)=>{q(t,200,hee,{...await gR(nu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Uc(e,t){if(r(e,t,{handler:`handoff`}))try{await Rae(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:Fn.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:cw(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Wc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await QP(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:cw(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Gc=J(Ti,async(e,t,n)=>{try{if(!T){fL(`no-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`no-remote`},{handler:dL});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!hse(e,n.kind)){fL(`invalid-path`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`invalid-path`},{handler:dL});return}let r=bse(T);if(r===null){if(gL(T).kind===`no-remote`){fL(`no-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`no-remote`},{handler:dL});return}fL(`detached-head`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`detached-head`},{handler:dL});return}let i=gL(T);if(i.kind===`no-remote`){fL(`no-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`no-remote`},{handler:dL});return}if(i.kind===`non-github`){fL(`non-github-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`non-github-remote`},{handler:dL});return}if(!Tse(T,r)){fL(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,wr,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:dL});return}let a=KJ(T,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=gse(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=_se(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${ig(s)}`,u=await vse(T,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);fL(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,wr,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:dL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:dL,cause:e})}},{handler:dL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:dL})}),Kc=J(g,async(e,t)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:mH});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(!_r(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:mH});return}if(!fH(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:mH});return}q(t,200,Zn,await pH(T,r,i,a),{handler:mH})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mH,cause:e})}},{handler:mH,method:`GET`,skipBodyParse:!0}),qc=J(Ki,async(e,t,n)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:NL});return}if(!fH(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:NL});return}let e=KJ(T,l);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;q(t,200,oee,await IL(T,n.branch,r,n.kind),{handler:NL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:NL,cause:e})}},{handler:NL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:NL})}),Jc=J(zi,async(e,t,n)=>{if(yV(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:yH});return}if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:yH});return}try{q(t,200,ei,await _s(()=>xH(T,n.branch,{fastForward:n.fastForward===!0})),{handler:yH})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yH,cause:e})}},{handler:yH,method:`POST`});async function Yc(e){let[t,...n]=it,r=[...n,...e];return await new Promise((e,n)=>{let i=bl(t,r,zP({...ro,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},xL),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 ${xL}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=ML(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 Xc=J(g,async(e,t)=>{if(!fn.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:vL,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Yc([`share`,`owners`,`--json`]),n=TL(wL(e));jL(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,Mi,n,{handler:vL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vL,cause:e})}finally{fn.release(`/api/share/publish/owners`)}},{handler:vL,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:vL})}),Zc=J(g,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!CL(r)||!SL(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:yL});return}if(!fn.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:yL,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Yc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=DL(wL(e));jL(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,si,n,{handler:yL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yL,cause:e})}finally{fn.release(`/api/share/publish/name-check`)}},{handler:yL,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:yL})}),Qc=J(Hn,async(e,t,n)=>{if(!T){jL(`publish-create`,`no-project`),q(t,200,Hr,{ok:!1,error:`no-project`},{handler:bL});return}if(!CL(n.owner)||!SL(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:bL});return}if(!fn.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:bL,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 Yc(e),i=AL(wL(r));jL(`publish-create`,i.ok?`ok`:i.error),i.ok&&$e?.()?.refreshRemote().catch(()=>{}),q(t,200,Hr,i,{handler:bL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:bL,cause:e})}finally{fn.release(`/api/share/publish`)}},{handler:bL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:bL})}),$c=J(_,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,Zt,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),el=T?SM(T):null;async function tl(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:bM(e.headers),previewUrl:null,port:el?As(el)?.port??0:0,singleFile:on};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,xe,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let nl=`local-op-embeddings-set-key`,rl=`local-op-embeddings-clear-key`,il=`/api/local-op/embeddings`;function al(){let e=Yt?.();return{projectDir:T??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let ol=J(mr,async(e,t,n)=>{if(!fn.tryAcquire(il)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:nl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=al();await new NP(Jt).setForProject(e,r,n.key),Ut?.reloadCredential(),q(t,200,xr,{keyPresent:!0},{handler:nl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:nl,cause:e})}finally{fn.release(il)}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:nl})}),sl=J(g,async(e,t)=>{if(!fn.tryAcquire(il)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:rl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=al();await new NP(Jt).clearForProject(e,n),Ut?.reloadCredential(),q(t,200,xr,{keyPresent:!1},{handler:rl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:rl,cause:e})}finally{fn.release(il)}},{handler:rl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:rl})}),cl=`local-op-embeddings-test`,ll=`/api/local-op/embeddings/test`,ul=J(g,async(e,t)=>{if(!fn.tryAcquire(ll)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:cl,extraHeaders:{"Retry-After":`5`}});return}try{let e=Yt?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await EP(new NP(Jt),T??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await fae({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,En,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:cl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:cl,cause:e})}finally{fn.release(ll)}},{handler:cl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:cl})}),dl=J(g,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Ut){let t=Ut.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Yt?.()?.baseUrl??`https://api.openai.com/v1`,o=await EP(new NP(Jt),T??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of m())!LC(e)&&!zC(e)&&!ur(e)&&(f+=1);q(t,200,Fr,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0});async function fl(e,t){let n=$t?.()??Lr;try{let r=await qi(e,HI(l,n,{docName:t,projectDir:T??l,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=tn?.()??`warning`;if(Ie&&a!==`off`&&!UC(t)){Ie.updateDocumentFromMarkdown(t,e);let r=eL({projectDir:T??l,contentDir:l,baseConfig:n,backlinkIndex:Ie,linksValidation:a,admittedDocNames:br,docFilePathFor:e=>LJ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:LJ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function pl(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=WI({projectDir:T??l,contentDir:l});return mI(t.schemas,n)}let ml=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!nY(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=$t?.()??Lr,i=[],a=zI(l,n??void 0,e=>i.push(e)),o=VI(T??l,BI(r,a),e=>i.push(e));n===null&&i.push(...pl(o)),q(t,200,Nt,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),hl=J(ce,async(e,t,n)=>{let r;try{r=$I(z(l),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Ve?.(`lint-config`);try{let e=$t?.()??Lr,n=[],r=zI(l,void 0,e=>n.push(e)),i=VI(T??l,BI(e,r),e=>n.push(e));n.push(...pl(i)),q(t,200,Nt,{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`}),gl=J(dee,async(e,t,n)=>{let r;try{let e=z(T??l),t=n.parentPath??[];r=n.delete?$oe(e,n.file):n.field!==void 0&&n.removeField?Zoe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Qoe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Yoe(e,n.file,n.field,n.constraint,t):Xoe(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Ve?.(`files`),Ve?.(`lint-config`);try{let e=$t?.()??Lr,n=[],r=zI(l,void 0,e=>n.push(e)),i=VI(T??l,BI(e,r),e=>n.push(e));n.push(...pl(i)),q(t,200,Nt,{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`}),_l=J(g,async(e,t)=>{try{let e=z(T??l),{schemas:n,truncated:r}=woe(e),i=new Set(n),a=!1;if(Tt!==void 0){let t=bJ({contentDir:l,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&&dr(a)){let t=R(e,z(l,a));!t.startsWith(`..`)&&!El(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,In,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),vl=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},yl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!nY(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=LJ(l,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=$t?.()??Lr,a=[],o=await UI({projectDir:T??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:vl});q(t,200,b,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof RF){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}),xl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!SJ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=$t?.()??Lr;q(t,200,da,await GI({projectDir:T??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:vl}),{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}),Sl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!SJ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!SJ(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=LJ(l,o)??`${o}.md`}let s=$t?.()??Lr;q(t,200,ne,await nse(eL({projectDir:T??l,contentDir:l,baseConfig:s,liveSourceFor:vl,backlinkIndex:Ie??null,linksValidation:tn?.(),admittedDocNames:br,docFilePathFor:e=>LJ(l,e)}),{targetPath:i}),{handler:`audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),wl=J(aa,async(t,n,r)=>{try{let t=DJ(r.docName,n,`lint-fix`);if(t===null)return;let i=nr(t),a=yV(r,ut);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(LC(i)||zC(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=LJ(l,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}OJ(z(l,f),l);let p=$t?.()??Lr,{stored:m}=yi(a.summary),h=await s.getSession(i,o,{displayName:c,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Goe({projectDir:T??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=qn(d),n=Vn[t]??Vr(u??o);Ze?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{XE(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,JE(h))},h.origin),a.kind!==`anonymous`&&sP(i,o,c,u,void 0,a.kind===`agent`?vi({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{Ze?.touchMode(o,`idle`)}let t=await fr(i);if(t?.kind===`failure`){hr(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){gr(n,`lint-fix`);return}sr(i,`lint-fix`);try{b=await qi(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,Rt,{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 RF){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof yw){bw(n,e,`lint-fix`);return}if(e instanceof Tw){Dw(n,e,`lint-fix`);return}if(e instanceof oD){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`}),Dl=`link-preview`,Ol=new IU({cacheDir:on?null:z(T??l,`.ok`,`local`,`link-previews`)}),Al=null,jl=()=>(Al??=Ol.init(),Al),Ml=sn??DU;async function Nl(e){let t=await Ml(e);return t.ok?{ok:!0,metadata:await MU({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Ml})}:{ok:!1,reason:t.reason}}let Pl=()=>{try{return cn?.()===!0}catch{return!1}},Fl={"/api/config":tl,"/api/asset":Ba,"/api/asset-text":Wa,"/api/document":Wi,"/api/documents":Gi,"/api/backlinks":Yi,"/api/backlink-counts":Zi,"/api/link-preview":J(Vt,async(e,t,n)=>{try{if(!Pl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,de,{ok:!1,reason:`disabled`},{handler:Dl});return}await jl();let e=!1,r=await Ol.load(n.url,()=>(e=!0,Nl(n.url)));Ol.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,de,i,{handler:Dl})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Dl,cause:e})}},{handler:Dl,method:`POST`,preBodyGate:(e,t)=>{let n=zU({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:Dl}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Dl}),!1)}}),"/api/forward-links":Qi,"/api/link-graph":$i,"/api/dead-links":sa,"/api/orphans":ea,"/api/hubs":na,"/api/tags":Ss,"/api/pages":Za,"/api/folder-config":js,"/api/template":Bs,"/api/template/import":Vs,"/api/templates":Ps,"/api/skill":lc,"/api/skill-file":hc,"/api/skills":nc,"/api/skills/management":ac,"/api/skill/install":gc,"/api/skill/uninstall":_c,"/api/skill/restore":yc,"/api/skill/update":bc,"/api/skill-targets":vc,"/api/search":Vc,"/api/semantic-status":dl,"/api/lint/config":ml,"/api/lint/markdownlint-config":hl,"/api/lint/frontmatter-schema":gl,"/api/lint/frontmatter-schemas":_l,"/api/lint":yl,"/api/lint/audit":xl,"/api/lint/fix":wl,"/api/audit":Sl,"/api/suggest-links":k,"/api/page-headings":Ja,"/api/create-page":Ka,"/api/create-folder":qa,"/api/duplicate-path":E,"/api/rename-path":Ya,"/api/delete-path":D,"/api/trash/cleanup":Xa,"/api/upload":Qa,"/api/agent-write":Ni,"/api/agent-write-md":Fi,"/api/agent-write-batch":Li,"/api/frontmatter-patch":Ri,"/api/agent-patch":ca,"/api/agent-undo":la,"/api/agent-activity":ua,"/api/agent-burst-diff":ma,"/api/save-version":ba,"/api/history":xa,"/api/rollback":wa,"/api/metrics/reconciliation":Ta,"/api/metrics/parse-health":Ea,"/api/metrics/agent-presence":Na,"/api/metrics/agent-effects":Pa,"/api/metrics/watcher-recent":Ia,"/api/__embed-detect":La,"/api/server-info":Oa,"/api/acp/catalog":ja,"/api/share/construct-url":Gc,"/api/share/target-status":qc,"/api/git/branch-info":Kc,"/api/git/checkout":Jc,"/api/share/publish/owners":Xc,"/api/share/publish/name-check":Zc,"/api/share/publish":Qc,"/api/principal":Ma,"/api/rescue":Ga,"/api/workspace":Ra,"/api/sync/status":is,"/api/sync/trigger":ls,"/api/sync/conflicts":ds,"/api/sync/conflict-content":ps,"/api/sync/resolve-conflict":fs,"/api/local-op/clone":j,"/api/local-op/ok-init":lo,"/api/local-op/auth/login":ko,"/api/local-op/auth/status":zo,"/api/local-op/auth/pat":Ho,"/api/local-op/auth/gh-login":No,"/api/local-op/auth/cancel":Io,"/api/local-op/auth/repos":Wo,"/api/local-op/auth/signout":Qo,"/api/local-op/auth/set-identity":rs,"/api/local-op/embeddings/set-key":ol,"/api/local-op/embeddings/clear-key":sl,"/api/local-op/embeddings/test":ul,"/api/installed-agents":xs,"/api/spawn-cursor":Wc,"/api/handoff":Uc,"/api/install-skill":bs,"/api/skill/install-state":Hc,"/api/seed/plan":hs,"/api/seed/apply":vs,"/api/seed/packs":ys,"/api/client-logs":$c};ye&&(Fl[`/api/test-reset`]=ga,Fl[`/api/test-flush-git`]=ha,Fl[`/api/test-rescan-backlinks`]=va,Fl[`/api/test-rescan-files`]=ya);let Ll=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(`.`)),Rl=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let r=e.url?.split(`?`)[0];if(!r)return;let a=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};Uie({ts:Date.now(),url:r,method:e.method??``,ua:a(`user-agent`),origin:a(`origin`),referer:a(`referer`),host:a(`host`),remote:e.socket?.remoteAddress,secChUa:a(`sec-ch-ua`),secChUaMobile:a(`sec-ch-ua-mobile`),secChUaPlatform:a(`sec-ch-ua-platform`),secFetchSite:a(`sec-fetch-site`),secFetchDest:a(`sec-fetch-dest`),secFetchMode:a(`sec-fetch-mode`),secFetchUser:a(`sec-fetch-user`)});let o=e.method??`GET`,s=r;r.startsWith(`/api/history/`)?s=`/api/history/:sha`:r.startsWith(`/api/tags/`)?s=`/api/tags/:name`:Fl[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?aw(e):void 0;if(c!==void 0&&(sw(e,c),typeof t.setHeader==`function`&&t.setHeader(rw,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Y.info({event:`api.access`,requestId:c,method:o,route:s,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${o} ${s} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(r.startsWith(`/api/`)){let r=e.headers.origin;if(r!==void 0&&!Nj(r,n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(r!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,r),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${rw}, ${Rn.protocol}, ${Rn.runtime}, ${Rn.kind}`),t.setHeader(`Access-Control-Expose-Headers`,rw)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Ll.has(r)||Rl.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!Sj(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(on&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!Sj(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=xo.extract(wo.active(),e.headers),u=Lo(),d=Date.now();await wo.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:So.SERVER,attributes:{[us]:o,[ss]:s,[cs]:r,[os]:`http`,[as]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=Fl[r],a=!1;if(i)a=!0,await i(e,t);else if(r.startsWith(`/api/history/`)){let n=decodeURIComponent(r.slice(13));n&&(a=!0,await Sa(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await Cs(e,t,n))}a||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${o} ${r}`});let s=t.statusCode;n.setAttribute(ms,s),s>=500&&n.setStatus({code:bo.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:bo.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s,cause:e}),e}finally{n.end();let e=(Date.now()-d)/1e3;kq().record(e,{[us]:o,[ss]:s,[ms]:t.statusCode})}}))}}}function aY(e){let t=e?.code;return typeof t==`string`?t:void 0}function oY(e){let t;try{t=Wl(e.contentDir,{withFileTypes:!0})}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&qC(n.name,Fa)&&e.basenameIndex.add(n.name)}async function sY(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await du(i,{withFileTypes:!0})}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=Pj(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await lu(a)}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await fu(a)}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Fj(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await pu(i)}catch(t){let n=aY(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()&&qC(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()&&qC(a,Ca)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const cY=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(),lY=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function uY(e){return lY.includes(e)}function dY(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function fY(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!uY(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 pY=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=dY(e,this.payload)}};function mY(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=cY.safeParse(t);return n.success?n.data:void 0}var hY=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const gY=F(`conflict-storage`);var _Y=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(SM(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){gY.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){gY.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||zl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Ql(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return gY.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-Df2gTERY.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(!Fj(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);$z(r,t),ts(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`]),gY.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await bS(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){gY.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}),gY.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(!Fj(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch($z(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-Df2gTERY.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);$z(a,i),ts(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);ts(a,n,`utf-8`);break;case`delete`:B(a)&&Vo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function vY(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 yY(e,t){let n=SM(e);try{zl(n,{recursive:!0}),Ql(L(n,pe),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=ds(e);zl(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`};Ql(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const bY=new Map;let xY=!1;function SY(e,t){try{let n=vY(e,t);for(let e of bY.keys())yY(e,n)}catch{}}function CY(e){bY.set(e,(bY.get(e)??0)+1),xY||(xY=!0,process.on(`uncaughtExceptionMonitor`,SY));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=bY.get(e)??0;n<=1?bY.delete(e):bY.set(e,n-1)}}}function wY(e){let t=e.scheduler??m,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function TY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function EY(e){if(!B(e))return{};let t;try{t=(0,fj.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(!TY(t))return{};let n=t.telemetry;if(!TY(n))return{};let r=n.localSink;return TY(r)?r:{}}function DY(e){return typeof e==`boolean`?e:void 0}function OY(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function kY(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function AY(e){if(TY(e))return OY(e.maxBytes)}function jY(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=EY(Mo(`project`,e.projectDir)),n=EY(Mo(`project-local`,e.projectDir));if((DY(n.enabled)??DY(t.enabled)??!0)===!1)return null;let r=AY(n.spans)??AY(t.spans)??52428800,i=AY(n.logs)??AY(t.logs)??26214400,a=kY(n.attributeDenylist)??kY(t.attributeDenylist)??Ba;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var MY;(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})(MY||={});var NY;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(NY||={});const PY=MY.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),FY=e=>{switch(typeof e){case`undefined`:return PY.undefined;case`string`:return PY.string;case`number`:return Number.isNaN(e)?PY.nan:PY.number;case`boolean`:return PY.boolean;case`function`:return PY.function;case`bigint`:return PY.bigint;case`symbol`:return PY.symbol;case`object`:return Array.isArray(e)?PY.array:e===null?PY.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?PY.promise:typeof Map<`u`&&e instanceof Map?PY.map:typeof Set<`u`&&e instanceof Set?PY.set:typeof Date<`u`&&e instanceof Date?PY.date:PY.object;default:return PY.unknown}},X=MY.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 IY=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,MY.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()}};IY.create=e=>new IY(e);const LY=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===PY.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,MY.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${MY.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${MY.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${MY.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}"`:MY.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,MY.assertNever(e)}return{message:n}};let RY=LY;function zY(){return RY}const BY=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 VY(e,t){let n=zY(),r=BY({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===LY?void 0:LY].filter(e=>!!e)});e.common.issues.push(r)}var HY=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 UY;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 UY;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 UY=Object.freeze({status:`aborted`}),WY=e=>({status:`dirty`,value:e}),GY=e=>({status:`valid`,value:e}),KY=e=>e.status===`aborted`,qY=e=>e.status===`dirty`,JY=e=>e.status===`valid`,YY=e=>typeof Promise<`u`&&e instanceof Promise;var XY;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(XY||={});var ZY=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 QY=(e,t)=>{if(JY(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 IY(e.common.issues);return this._error=t,this._error}}};function $Y(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 eX=class{get description(){return this._def.description}_getType(e){return FY(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:FY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new HY,ctx:{common:e.parent.common,data:e.data,parsedType:FY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(YY(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:FY(e)};return QY(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:FY(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return JY(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=>JY(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:FY(e)},r=this._parse({data:e,path:n.path,parent:n});return QY(n,await(YY(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 nZ({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 rZ.create(this,this._def)}nullable(){return iZ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return LX.create(this)}promise(){return tZ.create(this,this._def)}or(e){return BX.create([this,e],this._def)}and(e){return WX.create(this,e,this._def)}transform(e){return new nZ({...$Y(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new aZ({...$Y(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new cZ({typeName:Z.ZodBranded,type:this,...$Y(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new oZ({...$Y(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 lZ.create(this,e)}readonly(){return uZ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const tX=/^c[^\s-]{8,}$/i,nX=/^[0-9a-z]+$/,rX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iX=/^[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,aX=/^[a-z0-9_-]{21}$/i,oX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sX=/^[-+]?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)?)??$/,cX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let lX;const uX=/^(?:(?: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])$/,dX=/^(?:(?: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])$/,fX=/^(([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]))$/,pX=/^(([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])$/,mX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gX=`((\\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])))`,_X=RegExp(`^${gX}$`);function vX(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 yX(e){return RegExp(`^${vX(e)}$`)}function bX(e){let t=`${gX}T${vX(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xX(e,t){return!!((t===`v4`||!t)&&uX.test(e)||(t===`v6`||!t)&&fX.test(e))}function SX(e,t){if(!oX.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 CX(e,t){return!!((t===`v4`||!t)&&dX.test(e)||(t===`v6`||!t)&&pX.test(e))}var wX=class e extends eX{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==PY.string){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.string,received:t.parsedType}),UY}let t=new HY,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),VY(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),VY(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?VY(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&VY(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)cX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)lX||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),lX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)iX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)aX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)tX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)nX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)rX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(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),VY(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),VY(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),VY(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),VY(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),VY(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?bX(r).test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?_X.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?yX(r).test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?sX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?SX(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?CX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?mX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?hX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):MY.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,...XY.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...XY.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...XY.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...XY.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...XY.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...XY.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...XY.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...XY.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...XY.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...XY.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...XY.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...XY.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...XY.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...XY.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,...XY.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,...XY.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...XY.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...XY.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...XY.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...XY.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...XY.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...XY.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...XY.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...XY.errToObj(t)})}nonempty(e){return this.min(1,XY.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}};wX.create=e=>new wX({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...$Y(e)});function TX(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 EX=class e extends eX{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)!==PY.number){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.number,received:t.parsedType}),UY}let t,n=new HY;for(let r of this._def.checks)r.kind===`int`?MY.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),VY(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),VY(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),VY(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?TX(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),VY(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),VY(t,{code:X.not_finite,message:r.message}),n.dirty()):MY.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,XY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,XY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,XY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,XY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:XY.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:XY.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:XY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:XY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:XY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:XY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:XY.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:XY.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:XY.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:XY.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`&&MY.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)}};EX.create=e=>new EX({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...$Y(e)});var DX=class e extends eX{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)!==PY.bigint)return this._getInvalidInput(e);let t,n=new HY;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),VY(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),VY(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),VY(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):MY.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.bigint,received:t.parsedType}),UY}gte(e,t){return this.setLimit(`min`,e,!0,XY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,XY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,XY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,XY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:XY.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:XY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:XY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:XY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:XY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:XY.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}};DX.create=e=>new DX({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...$Y(e)});var OX=class extends eX{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==PY.boolean){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.boolean,received:t.parsedType}),UY}return GY(e.data)}};OX.create=e=>new OX({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...$Y(e)});var kX=class e extends eX{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==PY.date){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.date,received:t.parsedType}),UY}if(Number.isNaN(e.data.getTime()))return VY(this._getOrReturnCtx(e),{code:X.invalid_date}),UY;let t=new HY,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),VY(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),VY(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):MY.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:XY.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:XY.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)}};kX.create=e=>new kX({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...$Y(e)});var AX=class extends eX{_parse(e){if(this._getType(e)!==PY.symbol){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.symbol,received:t.parsedType}),UY}return GY(e.data)}};AX.create=e=>new AX({typeName:Z.ZodSymbol,...$Y(e)});var jX=class extends eX{_parse(e){if(this._getType(e)!==PY.undefined){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.undefined,received:t.parsedType}),UY}return GY(e.data)}};jX.create=e=>new jX({typeName:Z.ZodUndefined,...$Y(e)});var MX=class extends eX{_parse(e){if(this._getType(e)!==PY.null){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.null,received:t.parsedType}),UY}return GY(e.data)}};MX.create=e=>new MX({typeName:Z.ZodNull,...$Y(e)});var NX=class extends eX{constructor(){super(...arguments),this._any=!0}_parse(e){return GY(e.data)}};NX.create=e=>new NX({typeName:Z.ZodAny,...$Y(e)});var PX=class extends eX{constructor(){super(...arguments),this._unknown=!0}_parse(e){return GY(e.data)}};PX.create=e=>new PX({typeName:Z.ZodUnknown,...$Y(e)});var FX=class extends eX{_parse(e){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.never,received:t.parsedType}),UY}};FX.create=e=>new FX({typeName:Z.ZodNever,...$Y(e)});var IX=class extends eX{_parse(e){if(this._getType(e)!==PY.undefined){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.void,received:t.parsedType}),UY}return GY(e.data)}};IX.create=e=>new IX({typeName:Z.ZodVoid,...$Y(e)});var LX=class e extends eX{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==PY.array)return VY(t,{code:X.invalid_type,expected:PY.array,received:t.parsedType}),UY;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(VY(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&&(VY(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&&(VY(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 ZY(t,e,t.path,n)))).then(e=>HY.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new ZY(t,e,t.path,n)));return HY.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:XY.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:XY.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:XY.toString(n)}})}nonempty(e){return this.min(1,e)}};LX.create=(e,t)=>new LX({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...$Y(t)});function RX(e){if(e instanceof zX){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=rZ.create(RX(r))}return new zX({...e._def,shape:()=>t})}else if(e instanceof LX)return new LX({...e._def,type:RX(e.element)});else if(e instanceof rZ)return rZ.create(RX(e.unwrap()));else if(e instanceof iZ)return iZ.create(RX(e.unwrap()));else if(e instanceof GX)return GX.create(e.items.map(e=>RX(e)));else return e}var zX=class e extends eX{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=MY.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==PY.object){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.object,received:t.parsedType}),UY}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof FX&&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 ZY(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof FX){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&&(VY(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 ZY(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=>HY.mergeObjectSync(t,e)):HY.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return XY.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:XY.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 MY.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 MY.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return RX(this)}partial(t){let n={};for(let e of MY.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 MY.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof rZ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return QX(MY.objectKeys(this.shape))}};zX.create=(e,t)=>new zX({shape:()=>e,unknownKeys:`strip`,catchall:FX.create(),typeName:Z.ZodObject,...$Y(t)}),zX.strictCreate=(e,t)=>new zX({shape:()=>e,unknownKeys:`strict`,catchall:FX.create(),typeName:Z.ZodObject,...$Y(t)}),zX.lazycreate=(e,t)=>new zX({shape:e,unknownKeys:`strip`,catchall:FX.create(),typeName:Z.ZodObject,...$Y(t)});var BX=class extends eX{_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 IY(e.ctx.common.issues));return VY(t,{code:X.invalid_union,unionErrors:n}),UY}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 IY(e));return VY(t,{code:X.invalid_union,unionErrors:i}),UY}}get options(){return this._def.options}};BX.create=(e,t)=>new BX({options:e,typeName:Z.ZodUnion,...$Y(t)});const VX=e=>e instanceof XX?VX(e.schema):e instanceof nZ?VX(e.innerType()):e instanceof ZX?[e.value]:e instanceof $X?e.options:e instanceof eZ?MY.objectValues(e.enum):e instanceof aZ?VX(e._def.innerType):e instanceof jX?[void 0]:e instanceof MX?[null]:e instanceof rZ?[void 0,...VX(e.unwrap())]:e instanceof iZ?[null,...VX(e.unwrap())]:e instanceof cZ||e instanceof uZ?VX(e.unwrap()):e instanceof oZ?VX(e._def.innerType):[];var HX=class e extends eX{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==PY.object)return VY(t,{code:X.invalid_type,expected:PY.object,received:t.parsedType}),UY;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}):(VY(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),UY)}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=VX(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,...$Y(r)})}};function UX(e,t){let n=FY(e),r=FY(t);if(e===t)return{valid:!0,data:e};if(n===PY.object&&r===PY.object){let n=MY.objectKeys(t),r=MY.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=UX(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===PY.array&&r===PY.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=UX(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===PY.date&&r===PY.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var WX=class extends eX{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(KY(e)||KY(r))return UY;let i=UX(e.value,r.value);return i.valid?((qY(e)||qY(r))&&t.dirty(),{status:t.value,value:i.data}):(VY(n,{code:X.invalid_intersection_types}),UY)};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}))}};WX.create=(e,t,n)=>new WX({left:e,right:t,typeName:Z.ZodIntersection,...$Y(n)});var GX=class e extends eX{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PY.array)return VY(n,{code:X.invalid_type,expected:PY.array,received:n.parsedType}),UY;if(n.data.length<this._def.items.length)return VY(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),UY;!this._def.rest&&n.data.length>this._def.items.length&&(VY(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 ZY(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>HY.mergeArray(t,e)):HY.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};GX.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new GX({items:e,typeName:Z.ZodTuple,rest:null,...$Y(t)})};var KX=class e extends eX{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!==PY.object)return VY(n,{code:X.invalid_type,expected:PY.object,received:n.parsedType}),UY;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new ZY(n,e,n.path,e)),value:a._parse(new ZY(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?HY.mergeObjectAsync(t,r):HY.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof eX?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...$Y(r)}):new e({keyType:wX.create(),valueType:t,typeName:Z.ZodRecord,...$Y(n)})}},qX=class extends eX{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!==PY.map)return VY(n,{code:X.invalid_type,expected:PY.map,received:n.parsedType}),UY;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new ZY(n,e,n.path,[a,`key`])),value:i._parse(new ZY(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 UY;(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 UY;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};qX.create=(e,t,n)=>new qX({valueType:t,keyType:e,typeName:Z.ZodMap,...$Y(n)});var JX=class e extends eX{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PY.set)return VY(n,{code:X.invalid_type,expected:PY.set,received:n.parsedType}),UY;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(VY(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&&(VY(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 UY;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 ZY(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:XY.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:XY.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};JX.create=(e,t)=>new JX({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...$Y(t)});var YX=class e extends eX{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==PY.function)return VY(t,{code:X.invalid_type,expected:PY.function,received:t.parsedType}),UY;function n(e,n){return BY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zY(),LY].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return BY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zY(),LY].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 tZ){let e=this;return GY(async function(...t){let o=new IY([]),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 GY(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new IY([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new IY([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:GX.create(t).rest(PX.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||GX.create([]).rest(PX.create()),returns:n||PX.create(),typeName:Z.ZodFunction,...$Y(r)})}},XX=class extends eX{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})}};XX.create=(e,t)=>new XX({getter:e,typeName:Z.ZodLazy,...$Y(t)});var ZX=class extends eX{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return VY(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),UY}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZX.create=(e,t)=>new ZX({value:e,typeName:Z.ZodLiteral,...$Y(t)});function QX(e,t){return new $X({values:e,typeName:Z.ZodEnum,...$Y(t)})}var $X=class e extends eX{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return VY(t,{expected:MY.joinValues(n),received:t.parsedType,code:X.invalid_type}),UY}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return VY(t,{received:t.data,code:X.invalid_enum_value,options:n}),UY}return GY(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})}};$X.create=QX;var eZ=class extends eX{_parse(e){let t=MY.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==PY.string&&n.parsedType!==PY.number){let e=MY.objectValues(t);return VY(n,{expected:MY.joinValues(e),received:n.parsedType,code:X.invalid_type}),UY}if(this._cache||=new Set(MY.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=MY.objectValues(t);return VY(n,{received:n.data,code:X.invalid_enum_value,options:e}),UY}return GY(e.data)}get enum(){return this._def.values}};eZ.create=(e,t)=>new eZ({values:e,typeName:Z.ZodNativeEnum,...$Y(t)});var tZ=class extends eX{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==PY.promise&&t.common.async===!1?(VY(t,{code:X.invalid_type,expected:PY.promise,received:t.parsedType}),UY):GY((t.parsedType===PY.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};tZ.create=(e,t)=>new tZ({type:e,typeName:Z.ZodPromise,...$Y(t)});var nZ=class extends eX{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=>{VY(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 UY;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?UY:r.status===`dirty`||t.value===`dirty`?WY(r.value):r});{if(t.value===`aborted`)return UY;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?UY:r.status===`dirty`||t.value===`dirty`?WY(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`?UY:(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`?UY:(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(!JY(e))return UY;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=>JY(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):UY);MY.assertNever(r)}};nZ.create=(e,t,n)=>new nZ({schema:e,typeName:Z.ZodEffects,effect:t,...$Y(n)}),nZ.createWithPreprocess=(e,t,n)=>new nZ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...$Y(n)});var rZ=class extends eX{_parse(e){return this._getType(e)===PY.undefined?GY(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rZ.create=(e,t)=>new rZ({innerType:e,typeName:Z.ZodOptional,...$Y(t)});var iZ=class extends eX{_parse(e){return this._getType(e)===PY.null?GY(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};iZ.create=(e,t)=>new iZ({innerType:e,typeName:Z.ZodNullable,...$Y(t)});var aZ=class extends eX{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===PY.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};aZ.create=(e,t)=>new aZ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...$Y(t)});var oZ=class extends eX{_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 YY(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new IY(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new IY(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};oZ.create=(e,t)=>new oZ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...$Y(t)});var sZ=class extends eX{_parse(e){if(this._getType(e)!==PY.nan){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.nan,received:t.parsedType}),UY}return{status:`valid`,value:e.data}}};sZ.create=e=>new sZ({typeName:Z.ZodNaN,...$Y(e)});var cZ=class extends eX{_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}},lZ=class e extends eX{_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`?UY:e.status===`dirty`?(t.dirty(),WY(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`?UY: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})}},uZ=class extends eX{_parse(e){let t=this._def.innerType._parse(e),n=e=>(JY(e)&&(e.value=Object.freeze(e.value)),e);return YY(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};uZ.create=(e,t)=>new uZ({innerType:e,typeName:Z.ZodReadonly,...$Y(t)}),zX.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||={}),wX.create,EX.create,sZ.create,DX.create,OX.create,kX.create,AX.create,jX.create,MX.create,NX.create,PX.create,FX.create,IX.create,LX.create;const dZ=zX.create;zX.strictCreate,BX.create,HX.create,WX.create,GX.create,KX.create,qX.create,JX.create,YX.create,XX.create,ZX.create,$X.create,eZ.create,tZ.create,nZ.create,rZ.create,iZ.create,nZ.createWithPreprocess,lZ.create;const fZ=Ia(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);_o.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Ha(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ea(e,t,n),e.parseAsync=async(t,n)=>Oa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>La(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)}),pZ=Ia(`ZodMiniObject`,(e,t)=>{Ta.init(e,t),fZ.init(e,t),to(e,`shape`,()=>t.shape)});function mZ(e,t){return new pZ({type:`object`,shape:e??{},...Pa(t)})}function hZ(e){return!!e._zod}function gZ(e){let t=Object.values(e);if(t.length===0)return mZ({});let n=t.every(hZ),r=t.every(e=>!hZ(e));if(n)return mZ(e);if(r)return dZ(e);throw Error(`Mixed Zod versions detected in object shape.`)}function _Z(e,t){return hZ(e)?Ea(e,t):e.safeParse(t)}async function vZ(e,t){return hZ(e)?await La(e,t):await e.safeParseAsync(t)}function yZ(e){if(!e)return;let t;if(t=hZ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function bZ(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 gZ(e)}}if(hZ(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 xZ(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 SZ(e){return e.description}function CZ(e){if(hZ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function wZ(e){if(hZ(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 TZ=`2025-11-25`,EZ=[TZ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],DZ=`io.modelcontextprotocol/related-task`,OZ=uo(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),kZ=k([A(),P().int()]),AZ=A();io({ttl:P().optional(),pollInterval:P().optional()});const jZ=O({ttl:P().optional()}),MZ=O({taskId:A()}),NZ=io({progressToken:kZ.optional(),[DZ]:MZ.optional()}),PZ=O({_meta:NZ.optional()}),FZ=PZ.extend({task:jZ.optional()}),IZ=e=>FZ.safeParse(e).success,LZ=O({method:A(),params:PZ.loose().optional()}),RZ=O({_meta:NZ.optional()}),zZ=O({method:A(),params:RZ.loose().optional()}),BZ=io({_meta:NZ.optional()}),VZ=k([A(),P().int()]),HZ=O({jsonrpc:D(`2.0`),id:VZ,...LZ.shape}).strict(),UZ=e=>HZ.safeParse(e).success,WZ=O({jsonrpc:D(`2.0`),...zZ.shape}).strict(),GZ=e=>WZ.safeParse(e).success,KZ=O({jsonrpc:D(`2.0`),id:VZ,result:BZ}).strict(),qZ=e=>KZ.safeParse(e).success;var JZ;(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`})(JZ||={});const YZ=O({jsonrpc:D(`2.0`),id:VZ.optional(),error:O({code:P().int(),message:A(),data:E().optional()})}).strict(),XZ=e=>YZ.safeParse(e).success,ZZ=k([HZ,WZ,KZ,YZ]);k([KZ,YZ]);const QZ=BZ.strict(),$Z=RZ.extend({requestId:VZ.optional(),reason:A().optional()}),eQ=zZ.extend({method:D(`notifications/cancelled`),params:$Z}),tQ=O({icons:N(O({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:za([`light`,`dark`]).optional()})).optional()}),nQ=O({name:A(),title:A().optional()}),rQ=nQ.extend({...nQ.shape,...tQ.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),iQ=co(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,so(O({form:so(O({applyDefaults:M().optional()}),j(A(),E())).optional(),url:OZ.optional()}),j(A(),E()).optional())),aQ=io({list:OZ.optional(),cancel:OZ.optional(),requests:io({sampling:io({createMessage:OZ.optional()}).optional(),elicitation:io({create:OZ.optional()}).optional()}).optional()}),oQ=io({list:OZ.optional(),cancel:OZ.optional(),requests:io({tools:io({call:OZ.optional()}).optional()}).optional()}),sQ=O({experimental:j(A(),OZ).optional(),sampling:O({context:OZ.optional(),tools:OZ.optional()}).optional(),elicitation:iQ.optional(),roots:O({listChanged:M().optional()}).optional(),tasks:aQ.optional(),extensions:j(A(),OZ).optional()}),cQ=PZ.extend({protocolVersion:A(),capabilities:sQ,clientInfo:rQ}),lQ=LZ.extend({method:D(`initialize`),params:cQ}),uQ=e=>lQ.safeParse(e).success,dQ=O({experimental:j(A(),OZ).optional(),logging:OZ.optional(),completions:OZ.optional(),prompts:O({listChanged:M().optional()}).optional(),resources:O({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:O({listChanged:M().optional()}).optional(),tasks:oQ.optional(),extensions:j(A(),OZ).optional()}),fQ=BZ.extend({protocolVersion:A(),capabilities:dQ,serverInfo:rQ,instructions:A().optional()}),pQ=zZ.extend({method:D(`notifications/initialized`),params:RZ.optional()}),mQ=e=>pQ.safeParse(e).success,hQ=LZ.extend({method:D(`ping`),params:PZ.optional()}),gQ=O({progress:P(),total:Xa(P()),message:Xa(A())}),_Q=O({...RZ.shape,...gQ.shape,progressToken:kZ}),vQ=zZ.extend({method:D(`notifications/progress`),params:_Q}),yQ=PZ.extend({cursor:AZ.optional()}),bQ=LZ.extend({params:yQ.optional()}),xQ=BZ.extend({nextCursor:AZ.optional()}),SQ=za([`working`,`input_required`,`completed`,`failed`,`cancelled`]),CQ=O({taskId:A(),status:SQ,ttl:k([P(),xa()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Xa(P()),statusMessage:Xa(A())}),wQ=BZ.extend({task:CQ}),TQ=RZ.merge(CQ),EQ=zZ.extend({method:D(`notifications/tasks/status`),params:TQ}),DQ=LZ.extend({method:D(`tasks/get`),params:PZ.extend({taskId:A()})}),OQ=BZ.merge(CQ),kQ=LZ.extend({method:D(`tasks/result`),params:PZ.extend({taskId:A()})});BZ.loose();const AQ=bQ.extend({method:D(`tasks/list`)}),jQ=xQ.extend({tasks:N(CQ)}),MQ=LZ.extend({method:D(`tasks/cancel`),params:PZ.extend({taskId:A()})}),NQ=BZ.merge(CQ),PQ=O({uri:A(),mimeType:Xa(A()),_meta:j(A(),E()).optional()}),FQ=PQ.extend({text:A()}),IQ=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),LQ=PQ.extend({blob:IQ}),RQ=za([`user`,`assistant`]),zQ=O({audience:N(RQ).optional(),priority:P().min(0).max(1).optional(),lastModified:vo({offset:!0}).optional()}),BQ=O({...nQ.shape,...tQ.shape,uri:A(),description:Xa(A()),mimeType:Xa(A()),size:Xa(P()),annotations:zQ.optional(),_meta:Xa(io({}))}),VQ=O({...nQ.shape,...tQ.shape,uriTemplate:A(),description:Xa(A()),mimeType:Xa(A()),annotations:zQ.optional(),_meta:Xa(io({}))}),HQ=bQ.extend({method:D(`resources/list`)}),UQ=xQ.extend({resources:N(BQ)}),WQ=bQ.extend({method:D(`resources/templates/list`)}),GQ=xQ.extend({resourceTemplates:N(VQ)}),KQ=PZ.extend({uri:A()}),qQ=KQ,JQ=LZ.extend({method:D(`resources/read`),params:qQ}),YQ=BZ.extend({contents:N(k([FQ,LQ]))}),XQ=zZ.extend({method:D(`notifications/resources/list_changed`),params:RZ.optional()}),ZQ=KQ,QQ=LZ.extend({method:D(`resources/subscribe`),params:ZQ}),$Q=KQ,e$=LZ.extend({method:D(`resources/unsubscribe`),params:$Q}),t$=RZ.extend({uri:A()}),n$=zZ.extend({method:D(`notifications/resources/updated`),params:t$}),r$=O({name:A(),description:Xa(A()),required:Xa(M())}),i$=O({...nQ.shape,...tQ.shape,description:Xa(A()),arguments:Xa(N(r$)),_meta:Xa(io({}))}),a$=bQ.extend({method:D(`prompts/list`)}),o$=xQ.extend({prompts:N(i$)}),s$=PZ.extend({name:A(),arguments:j(A(),A()).optional()}),c$=LZ.extend({method:D(`prompts/get`),params:s$}),l$=O({type:D(`text`),text:A(),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),u$=O({type:D(`image`),data:IQ,mimeType:A(),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),d$=O({type:D(`audio`),data:IQ,mimeType:A(),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),f$=O({type:D(`tool_use`),name:A(),id:A(),input:j(A(),E()),_meta:j(A(),E()).optional()}),p$=O({type:D(`resource`),resource:k([FQ,LQ]),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),m$=k([l$,u$,d$,BQ.extend({type:D(`resource_link`)}),p$]),h$=O({role:RQ,content:m$}),g$=BZ.extend({description:A().optional(),messages:N(h$)}),_$=zZ.extend({method:D(`notifications/prompts/list_changed`),params:RZ.optional()}),v$=O({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),y$=O({taskSupport:za([`required`,`optional`,`forbidden`]).optional()}),b$=O({...nQ.shape,...tQ.shape,description:A().optional(),inputSchema:O({type:D(`object`),properties:j(A(),OZ).optional(),required:N(A()).optional()}).catchall(E()),outputSchema:O({type:D(`object`),properties:j(A(),OZ).optional(),required:N(A()).optional()}).catchall(E()).optional(),annotations:v$.optional(),execution:y$.optional(),_meta:j(A(),E()).optional()}),x$=bQ.extend({method:D(`tools/list`)}),S$=xQ.extend({tools:N(b$)}),C$=BZ.extend({content:N(m$).default([]),structuredContent:j(A(),E()).optional(),isError:M().optional()});C$.or(BZ.extend({toolResult:E()}));const w$=FZ.extend({name:A(),arguments:j(A(),E()).optional()}),T$=LZ.extend({method:D(`tools/call`),params:w$}),E$=zZ.extend({method:D(`notifications/tools/list_changed`),params:RZ.optional()});O({autoRefresh:M().default(!0),debounceMs:P().int().nonnegative().default(300)});const D$=za([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),O$=PZ.extend({level:D$}),k$=LZ.extend({method:D(`logging/setLevel`),params:O$}),A$=RZ.extend({level:D$,logger:A().optional(),data:E()}),j$=zZ.extend({method:D(`notifications/message`),params:A$}),M$=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()}),N$=O({mode:za([`auto`,`required`,`none`]).optional()}),P$=O({type:D(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(m$).default([]),structuredContent:O({}).loose().optional(),isError:M().optional(),_meta:j(A(),E()).optional()}),F$=eo(`type`,[l$,u$,d$]),I$=eo(`type`,[l$,u$,d$,f$,P$]),L$=O({role:RQ,content:k([I$,N(I$)]),_meta:j(A(),E()).optional()}),R$=FZ.extend({messages:N(L$),modelPreferences:M$.optional(),systemPrompt:A().optional(),includeContext:za([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(A()).optional(),metadata:OZ.optional(),tools:N(b$).optional(),toolChoice:N$.optional()}),z$=LZ.extend({method:D(`sampling/createMessage`),params:R$}),B$=BZ.extend({model:A(),stopReason:Xa(za([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:RQ,content:F$}),V$=BZ.extend({model:A(),stopReason:Xa(za([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:RQ,content:k([I$,N(I$)])}),H$=O({type:D(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),U$=O({type:D(`string`),title:A().optional(),description:A().optional(),minLength:P().optional(),maxLength:P().optional(),format:za([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),W$=O({type:za([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),G$=O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),K$=O({type:D(`string`),title:A().optional(),description:A().optional(),oneOf:N(O({const:A(),title:A()})),default:A().optional()}),q$=k([k([O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),k([G$,K$]),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()})])]),H$,U$,W$]),J$=k([FZ.extend({mode:D(`form`).optional(),message:A(),requestedSchema:O({type:D(`object`),properties:j(A(),q$),required:N(A()).optional()})}),FZ.extend({mode:D(`url`),message:A(),elicitationId:A(),url:A().url()})]),Y$=LZ.extend({method:D(`elicitation/create`),params:J$}),X$=RZ.extend({elicitationId:A()}),Z$=zZ.extend({method:D(`notifications/elicitation/complete`),params:X$}),Q$=BZ.extend({action:za([`accept`,`decline`,`cancel`]),content:co(e=>e===null?void 0:e,j(A(),k([A(),P(),M(),N(A())])).optional())}),$$=O({type:D(`ref/resource`),uri:A()}),e1=O({type:D(`ref/prompt`),name:A()}),t1=PZ.extend({ref:k([e1,$$]),argument:O({name:A(),value:A()}),context:O({arguments:j(A(),A()).optional()}).optional()}),n1=LZ.extend({method:D(`completion/complete`),params:t1});function r1(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function i1(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const a1=BZ.extend({completion:io({values:N(A()).max(100),total:Xa(P().int()),hasMore:Xa(M())})}),o1=O({uri:A().startsWith(`file://`),name:A().optional(),_meta:j(A(),E()).optional()}),s1=LZ.extend({method:D(`roots/list`),params:PZ.optional()}),c1=BZ.extend({roots:N(o1)}),l1=zZ.extend({method:D(`notifications/roots/list_changed`),params:RZ.optional()});k([hQ,lQ,n1,k$,c$,a$,HQ,WQ,JQ,QQ,e$,T$,x$,DQ,kQ,AQ,MQ]),k([eQ,vQ,pQ,l1,EQ]),k([QZ,B$,V$,Q$,c1,OQ,jQ,wQ]),k([hQ,z$,Y$,s1,DQ,kQ,AQ,MQ]),k([eQ,vQ,j$,n$,XQ,E$,_$,EQ,Z$]),k([QZ,fQ,a1,g$,o$,UQ,GQ,YQ,C$,S$,OQ,jQ,wQ]);var u1=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===JZ.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new d1(e.elicitations,n)}return new e(t,n,r)}},d1=class extends u1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(JZ.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function f1(e){return e===`completed`||e===`failed`||e===`cancelled`}const p1=Symbol(`Let zodToJsonSchema decide on which parser to use`),m1={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`},h1=e=>typeof e==`string`?{...m1,name:e}:{...m1,...e},g1=e=>{let t=h1(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 _1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function v1(e,t,n,r,i){e[t]=n,_1(e,t,r,i)}const y1=(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 b1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?y1(t,e.currentPath):t.join(`/`)}}function x1(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=d0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&v1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&v1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(v1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),v1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function S1(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?v1(n,`minimum`,r.value,r.message,t):v1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),v1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?v1(n,`maximum`,r.value,r.message,t):v1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),v1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:v1(n,`multipleOf`,r.value,r.message,t);break}return n}function C1(){return{type:`boolean`}}function w1(e,t){return d0(e.type._def,t)}const T1=(e,t)=>d0(e.innerType._def,t);function E1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>E1(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 D1(e,t)}}const D1=(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`:v1(n,`minimum`,r.value,r.message,t);break;case`max`:v1(n,`maximum`,r.value,r.message,t);break}return n};function O1(e,t){return{...d0(e.innerType._def,t),default:e.defaultValue()}}function k1(e,t){return t.effectStrategy===`input`?d0(e.schema._def,t):b1(t)}function A1(e){return{type:`string`,enum:Array.from(e.values)}}const j1=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function M1(e,t){let n=[d0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),d0(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(j1(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 N1(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 P1;const F1={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:()=>(P1===void 0&&(P1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),P1),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 I1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:v1(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`:B1(n,`email`,r.message,t);break;case`format:idn-email`:B1(n,`idn-email`,r.message,t);break;case`pattern:zod`:V1(n,F1.email,r.message,t);break}break;case`url`:B1(n,`uri`,r.message,t);break;case`uuid`:B1(n,`uuid`,r.message,t);break;case`regex`:V1(n,r.regex,r.message,t);break;case`cuid`:V1(n,F1.cuid,r.message,t);break;case`cuid2`:V1(n,F1.cuid2,r.message,t);break;case`startsWith`:V1(n,RegExp(`^${L1(r.value,t)}`),r.message,t);break;case`endsWith`:V1(n,RegExp(`${L1(r.value,t)}$`),r.message,t);break;case`datetime`:B1(n,`date-time`,r.message,t);break;case`date`:B1(n,`date`,r.message,t);break;case`time`:B1(n,`time`,r.message,t);break;case`duration`:B1(n,`duration`,r.message,t);break;case`length`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),v1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:V1(n,RegExp(L1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&B1(n,`ipv4`,r.message,t),r.version!==`v4`&&B1(n,`ipv6`,r.message,t);break;case`base64url`:V1(n,F1.base64url,r.message,t);break;case`jwt`:V1(n,F1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&V1(n,F1.ipv4Cidr,r.message,t),r.version!==`v4`&&V1(n,F1.ipv6Cidr,r.message,t);break;case`emoji`:V1(n,F1.emoji(),r.message,t);break;case`ulid`:V1(n,F1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:B1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:v1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:V1(n,F1.base64,r.message,t);break}break;case`nanoid`:V1(n,F1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function L1(e,t){return t.patternStrategy===`escape`?z1(e):e}const R1=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function z1(e){let t=``;for(let n=0;n<e.length;n++)R1.has(e[n])||(t+=`\\`),t+=e[n];return t}function B1(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}}})):v1(e,`format`,t,n,r)}function V1(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:H1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):v1(e,`pattern`,H1(t,r),n,r)}function H1(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
1228
|
+
`);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{Y.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),fn.release(po))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),fn.release(po))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),fn.release(po))})}let Zo=`local-op-auth-signout`,Qo=J(Xi,async(e,t,n)=>{let r=n.host??Co();if(!fn.tryAcquire(mo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Zo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=it,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=bl(e,i,zP({...io,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,Gr,{},{handler:Zo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Zo,cause:e})}finally{fn.release(mo)}},{handler:Zo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zo})}),es=`/api/local-op/auth/set-identity`,ns=`local-op-auth-set-identity`,rs=J(_i,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:ns});return}if(!fn.tryAcquire(es)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ns,extraHeaders:{"Retry-After":`5`}});return}try{DH(T,r,i),$e?.()?.refreshIdentity().catch(()=>{}),q(t,200,Gr,{},{handler:ns})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ns,cause:e})}finally{fn.release(es)}},{handler:ns,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ns})});async function is(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();if(!e){q(t,200,Rr,{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,Rr,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 ls=J(d,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,Nr,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function ds(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();q(t,200,le,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let fs=J(re,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,dt,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function ps(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!T){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let o=JC(i),s=a.documents.get(o)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=$e?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){G(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=gs({baseDir:T,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),o=JC(i),s=a.documents.get(o),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Ft?Ft(o):null;t!==null&&(c=t,l=!0)}else{$z(L(T,i),T);try{c=V(L(T,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,zt,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),o=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=JC(i),t=a.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=Ft?Ft(e):null;t!==null&&!Xq(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Y.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(t,200,zt,{file:i,base:o,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function hs(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=sK(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,oa,{plan:await CK({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof YG){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof XG){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 vs=J(fa,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=sK(a);if(typeof a==`string`&&a.length>0&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,Pt,{result:await vK(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function ys(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,x,{packs:lK()},{handler:`seed-packs`})}}let bs=J(fee,async(e,t,n)=>{if(n.out!==void 0&&!qU(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,Ln,await OR({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function xs(e,t){if(r(e,t,{handler:`installed-agents`}))try{await kae(e,t,Fn.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:cw(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let Ss=J(g,async(e,t)=>{if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,Er,{tags:Le.getAllTags()},{handler:`tags-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Cs(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let r;try{r=decodeURIComponent(n)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){G(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=Le.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:Un(e),matchingTags:t,snippet:null}));q(t,200,Di,{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 Ts(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=z(l),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${kl}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let Es=/^[A-Za-z0-9_-]+$/;function Ds(e,t,n=`template`){return!e||!Es.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 Os(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}${kl}`))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 ks(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 js=kH({GET:J(g,async(e,t)=>{try{let n=Ts(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await PN(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,fj.parse)(await uu(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,Ht,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:J(fe,async(e,t,n)=>{try{if(on){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=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Ts(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=yie({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`&&(Ai(e,ki(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await ji(`folder-config-put`))}q(t,200,oe,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function Ms(e,t,n,r){if(!t)return!1;let i=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=a.documents.get(i);return o&&hw(o)?(bw(r,new yw({file:`${i}.md`}),n),!0):!1}function Ns(e,t,n){let r=a.documents.get(e);return r&&hw(r)?(bw(n,new yw({file:`${e}.md`}),t),!0):!1}let Ps=J(g,OH(async(e,t)=>{let n=wN(z(l));q(t,200,hi,{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}),Fs=e=>{let{body:t}=ia(e);return{frontmatter:rt(e)??{},body:t}},Ls=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ds(r,t,`template-get`))return;let i=Ts(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Os(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=xn(await uu(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,li,{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}),Rs=J(see,async(e,t,n)=>{try{if(on){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Ds(r,t,`template-put`))return;let i=Ts(n.folder,t,`folder`,`template-put`);if(!i||Ms(i.folderRel,r,`template-put`,t))return;let a=eP({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:ks(n.frontmatter)});if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!B(o),l=R(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=Xs(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=gi(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{dS(h.dc.document,a.content,`agent`)},h.origin);let g=await fr(u);if(g?.kind===`failure`){hr(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){gr(t,`template-put`);return}Ai(e,ki(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await ji(`template-put`),q(t,200,or,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),zs=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ds(r,t,`template-delete`))return;let i=Ts(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=yV({agentId:a.get(`agentId`)??void 0,agentName:a.get(`agentName`)??void 0,colorSeed:a.get(`colorSeed`)??void 0,clientName:a.get(`clientName`)??void 0,clientVersion:a.get(`clientVersion`)??void 0,label:a.get(`label`)??void 0,summary:a.get(`summary`)??void 0},ut);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Ms(i.folderRel,r,`template-delete`,t))return;await Ir([Xs(i.folderRel,r)],`deleted-upstream`);let s=Nie({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&&(Ai(o,ki(`template`,i.folderRel,r),`template-delete: ${s.path}`),await ji(`template-delete`)),q(t,200,jn,{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}),Bs=kH({GET:Ls,PUT:Rs,POST:J(uee,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Ds(n.fromName,t,`template-move`)||!Ds(n.toName,t,`template-move`))return;let r=Ts(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Ts(n.toFolder,t,`folder`,`template-move`);if(!i||Ms(r.folderRel,n.fromName,`template-move`,t))return;await Ir([Xs(r.folderRel,n.fromName)],`renamed`);let a=await Pie({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await $J(T,e,t);return n||QJ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Os(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=lr(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=Mie({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ks(n.frontmatter)});t.ok||(o=t.error)}}if(Ai(e,ki(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await ji(`template-move`),Ve?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,Ji,{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:zs},{handler:`template`}),Vs=J(Pi,async(e,t,n)=>{try{if(on){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!nY(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=nr(r);if(LC(i)||zC(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let o=kJ(l,`file`,i);if(!B(o)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let c=a.documents.get(i);if(n.deleteSource){let e=$e?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=c!==void 0&&hw(c),a=n.has(r);if(i||a){bw(t,new yw({file:r}),`template-import`);return}}let u=``;if(c)u=c.getText(`source`).toString();else{let e=await a.openDirectConnection(i);try{let n=e.document;if(!n){G(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=AJ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Ds(d,t,`template-import`))return;let f=Ts(n.targetFolder,t,`folder`,`template-import`);if(!f||Ms(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=ia(u),h=Lt(p),g={};try{h.trim()&&(g=(0,fj.parse)(h))}catch{}let _=n.title||g?.title||lL(u,d),v=g?.description||``,y=Array.isArray(g?.tags)?g.tags:[],b={...g};delete b.template,delete b.title;let x=``;Object.keys(b).length>0&&(x=`${(0,fj.stringify)(b).trim()}\n`),x=x?`---\n${x}---\n${m}`:m;let S=eP({name:d,body:x,frontmatter:{title:_,description:v,tags:y}});if(!S.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:S.error.code,cause:Error(S.error.message)});return}let C=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),ee=!B(C),te=R(f.resolvedContentDir,C).split(/[\\/]/).filter(Boolean).join(`/`),ne=Xs(f.folderRel,d),{agentId:re,agentName:ie,colorSeed:ae,clientName:oe}=gi(n),se=await s.getSession(ne,re,{displayName:ie,colorSeed:ae,clientName:oe});se.dc.document.transact(()=>{dS(se.dc.document,S.content,`agent`)},se.origin);let ce=await fr(ne);if(ce?.kind===`failure`){hr(t,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){gr(t,`template-import`);return}Ai(e,ki(`template`,f.folderRel,d),`template-import: ${te}`),n.deleteSource&&(await Ir([i],`deleted-upstream`),Mt&&Mt.setDeleted(i),Vo(o),w?.({kind:`delete`,path:o,docName:i})),await ji(`template-import`),Ve?.(`files`),q(t,200,Wn,{path:te,created:ee,warnings:S.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Hs(e,t,n){return!e||e.length>64||!mt.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function Us(e,t,n){let r=Ci.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 Ws=ft??nu();function Gs(e){return z(e===`global`?Ws:l,`.ok`,`skills`)}let Ks=LL.project;function qs(){if(!T)return null;let e=[],t=null;for(let n of He){let r=en[n];if(!r)continue;let i=z(T,...r.split(`/`),Ks);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 Js(){let e=qs();if(!e)return null;let t;try{let{frontmatter:n}=Fs(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Ks,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Ys(e,t,n){return zL(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 Xs(e,t){return`${Mn}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Zs(e){return e===`navigation`||e===`relevance`?e:void 0}function Qs(e,t){return R(t===`global`?Ws:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function $s(e){return e===`global`?Ws:T}async function ec(e,t){let n=await vF(e,t);return _z(t,e,He),n!==null}function tc(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=Wl(e,{withFileTypes:!0})}catch(r){return F(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!mt.test(a.name))continue;if(n.length>=500){i=!0;break}let r=z(e,a.name,`SKILL.md`);if(!B(r))continue;let o,s;try{let{frontmatter:e}=Fs(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:Qs(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let nc=J(g,OH(async(e,t)=>{let n=tc(Gs(`project`),`project`),r=tc(Gs(`global`),`global`),i=T?hF(T).skills:{},a=hF(Ws).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=kz(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Ks)?null:Js();q(t,200,Vi,{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}),rc=O({managed:M().nullable(),importable:P().int().nonnegative()}),ic=()=>({managed:T?MR(T)?.manageEditorSkills??null:null,importable:T?Wz({projectDir:T,skillsRoot:Gs(`project`)}):0}),ac=kH({GET:J(g,async(e,t)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,rc,ic(),{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 NR(T,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await Gz({projectDir:T,skillsRoot:Gs(`project`)});e.adopted.length+e.collided.length>0&&Ve?.(`files`)}q(t,200,rc,ic(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),oc=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Hs(r,t,`skill-get`))return;let i=Us(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Ks&&i===`project`){let e=qs();if(e){let{frontmatter:n,body:a}=Fs(await uu(e.skillMd,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:e.relPath,frontmatter:{name:typeof n.name==`string`?n.name:r,description:typeof n.description==`string`?n.description:``},body:a,files:xz(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Gs(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}=Fs(await uu(o,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:Qs(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:xz(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}),sc=J(qt,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Hs(n.name,t,`skill-put`)||Ys(n.name,t,`skill-put`))return;let r=VN({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=Gs(n.scope),a=z(i,n.name,`SKILL.md`),o=!B(a),c=R(i,a).split(/[\\/]/).filter(Boolean).join(`/`),l=pr(n.scope,n.name);if(Ns(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{dS(m.dc.document,r.content,`agent`)},m.origin);let h=await fr(l);if(h?.kind===`failure`){hr(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){gr(t,`skill-put`);return}n.scope===`project`&&(Ai(e,ki(`skill`,``,n.name),`${o?`skill-create`:`skill-edit`}: ${c}`),await ji(`skill-put`)),Ve?.(`files`),q(t,200,an,{path:c,created:o,warnings:r.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),cc=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Hs(r,t,`skill-delete`)||Ys(r,t,`skill-delete`))return;let i=Us(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Gs(i),o=n.searchParams,s=yV({agentId:o.get(`agentId`)??void 0,agentName:o.get(`agentName`)??void 0,colorSeed:o.get(`colorSeed`)??void 0,clientName:o.get(`clientName`)??void 0,clientVersion:o.get(`clientVersion`)??void 0,label:o.get(`label`)??void 0,summary:o.get(`summary`)??void 0},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Ir([pr(i,r)],`deleted-upstream`);let c=Tie({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`&&(Ai(s,ki(`skill`,``,r),`skill-delete: ${c.path}`),await ji(`skill-delete`)),Ve?.(`files`));let l=$s(i);l&&await ec(l,r),q(t,200,nt,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),lc=kH({GET:oc,PUT:sc,POST:J(Qt,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Hs(n.fromName,t,`skill-move`)||!Hs(n.toName,t,`skill-move`)||Ys(n.fromName,t,`skill-move`)||Ys(n.toName,t,`skill-move`))return;let r=Gs(n.scope);await Ir([pr(n.scope,n.fromName)],`renamed`);let i=await Eie({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await $J(T,e,t);return n||QJ(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=Fs(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=Sie({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{mc(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=Qs(z(r,n.fromName),n.scope),p=Qs(z(r,n.toName),n.scope);n.scope===`project`&&(Ai(e,ki(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await ji(`skill-move`));let m=$s(n.scope);if(m){let e=await vF(m,n.fromName);if(e){let t=iz(e.hosts);_z(n.fromName,m,t);let i=gz(z(r,n.toName),n.toName,m,t);await _F(m,n.toName,{...e,hosts:i})}}if(Ve?.(`files`),a){let e=a.code===`WRITE_ERROR`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:a.code,cause:Error(a.message)});return}q(t,200,ke,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),DELETE:cc},{handler:`skill`});function uc(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 dc(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function fc(e,t){let n=t.replace(/\.md$/i,``);return`${Xr(e).replace(/\/SKILL$/,``)}/${n}`}function pc(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of Wl(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 mc(e,t,n){if(!Ie)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{Ie.deleteDocument(e),Le?.deleteDocument(e);return}Ie.renameDocument(e,t,r),Le?.renameDocument(e,t,r)};r(Xr(t),Xr(n),z(e,n,`SKILL.md`));for(let i of pc(e,n))r(fc(t,i),fc(n,i),z(e,n,i));Ve?.(`backlinks`),Ve?.(`graph`)}let hc=kH({GET:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Hs(r,t,`skill-file-get`))return;let i=Us(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Ks&&i===`project`?qs():null,s=o&&a===`SKILL.md`?`reference`:uc(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(Gs(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${kl}`)){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?gn.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 uu(u);if(f.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,yt,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:J(ve,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Hs(n.name,t,`skill-file-put`)||Ys(n.name,t,`skill-file-put`))return;let r=uc(n.path);if(r===null){G(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=Gs(n.scope);if(!B(z(i,n.name,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=n.path.replace(/\\/g,`/`),o=dc(n.scope,r,a),c;if(o){let e=fc(n.name,a);if(Ns(e,`skill-file-put`,t))return;if(c=!B(z(i,n.name,a)),c&&UN(z(i,n.name))>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:o,colorSeed:l,clientName:u}=gi(n),d=await s.getSession(e,r,{displayName:o,colorSeed:l,clientName:u});d.dc.document.transact(()=>{dS(d.dc.document,n.content,`agent`)},d.origin);let f=await fr(e);if(f?.kind===`failure`){hr(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){gr(t,`skill-file-put`);return}}else{let e=Cie({skillsRoot:i,name:n.name,relPath:a,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}n.scope===`project`&&(Ai(e,ki(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${a}`),await ji(`skill-file-put`)),Ve?.(`files`),q(t,200,Pe,{path:a,created:c,kind:r,content:o},{handler:`skill-file-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!Hs(r,t,`skill-file-delete`)||Ys(r,t,`skill-file-delete`))return;let i=Us(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=uc(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=yV({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=Gs(i);dc(i,o,a)&&await Ir([fc(r,a)],`deleted-upstream`);let l=wie({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`&&(Ai(s,ki(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await ji(`skill-file-delete`)),l.existed&&Ve?.(`files`),q(t,200,ct,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),gc=J(At,async(e,t,n)=>{try{let e=Gs(n.scope);if(!Hs(n.name,t,`skill-install`)||Ys(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=$s(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=uz(i,n.name);if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${a.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let o=n.scope===`global`?n.targets?He.filter(e=>n.targets?.some(t=>t===e)):[...He]:n.targets===void 0?fz(r,Zz(r)??void 0):He.filter(e=>n.targets?.some(t=>t===e)),s=[],c=[];o.length===0&&n.targets===void 0&&(s.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),c.push(`no-targets`)),a.hasScripts&&(s.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),c.push(`scripts-present`));let l=iz(hF(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&_z(n.name,r,l);let u=gz(i,n.name,r,o);u.length===0?await vF(r,n.name):await _F(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),Ve?.(`files`),q(t,200,v,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),_c=J(bn,async(e,t,n)=>{try{if(!Hs(n.name,t,`skill-uninstall`)||Ys(n.name,t,`skill-uninstall`))return;let e=$s(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 ec(e,n.name);Ve?.(`files`),q(t,200,wt,{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`}),vc=kH({GET:J(g,OH(async(e,t)=>{let n=T?Zz(T):null;q(t,200,Be,{targets:fz(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(mn,OH(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=fz(T,Zz(T)??void 0),o=Gs(`project`);await Qz(T,r);let{reprojected:s,bundleHosts:c}=await Jz({projectDir:T,skillsRoot:o,targets:r});Ve?.(`files`),q(t,200,dn,{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`}),yc=J(we,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Hs(n.name,t,`skill-restore`)||Ys(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=be?.current;if(!r){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await AK({shadow:r,contentDir:l,contentRoot:Fe??`.`,name:n.name,version:n.version});if(!i.ok){let[e,n]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[i.code];G(t,e,n,i.error,{handler:`skill-restore`,detail:i.code});return}let a=[],o=uz(z(l,`.ok`,`skills`,n.name),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),a.push("Run `install` to push the restored version to your editors."),Ai(e,ki(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await ji(`skill-restore`),Ve?.(`files`),q(t,200,Ke,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),bc=J(c,async(e,t,n)=>{try{let e=yV(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!Hs(n.name,t,`skill-update`)||Ys(n.name,t,`skill-update`))return;if(!Sz(n.name)){G(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let r=Dz(n.name);if(r===null||r.version===void 0){G(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let i=z(Gs(`project`),n.name,`SKILL.md`);if(!B(i)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let a;try{a=wz(V(i,`utf-8`))}catch{}let o,c=be?.current;if(c)try{let e=Oe?.()??`main`;o=(await EC(c,Fe??`.`,[uC],e,`Before updating ${n.name} (${a??`unversioned`} → ${r.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=pr(`project`,n.name);if(Ns(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{dS(m.dc.document,r.content,`agent`)},m.origin);let h=await fr(l);if(h?.kind===`failure`){hr(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){gr(t,`skill-update`);return}Ai(e,ki(`skill`,``,n.name),`skill-pack-update: ${n.name} (${a??`unversioned`} → ${r.version})`),await ji(`skill-update`),Ve?.(`files`),q(t,200,$n,{name:n.name,version:r.version,...a===void 0?{}:{previousVersion:a},...o===void 0?{}:{checkpointRef:o}},{handler:`skill-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function xc(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])=>It({kind:`folder`,path:e,modifiedTs:t}))}function Sc(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 Cc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function wc(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 Tc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Ec(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function Dc(e,t,n,r){let i=r.documents.filter(e=>!ur(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Ut?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Ut.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Ut.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Wt?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Ut.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function Oc(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?Sc(e.document.content,t):void 0}}async function kc(e){let t=performance.now();if(Rc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await zc(),i=await Dc(e.query,e.intent,e.semanticParam,n),a=se(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>Oc(t,e.query)),o;if(i.status){let t=a.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),n=t>0;o={...i.status,applied:n},rae({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 Ac(){let e=Gs(`project`);if(!B(e))return[];let t;try{t=Wl(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!mt.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=Xl(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function jc(){let e=[];for(let t of Ac()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=Fs(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(It({kind:`page`,path:pr(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function Mc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Nc=new Map;async function Pc(){let e=[],t=[],n=new Set;for(let[r,i]of S()){if(LC(r)||zC(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(It({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=Mc(i),o=Nc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await uu(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=lL(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=It({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Nc.set(r,{key:a,doc:u}),e.push(u)}for(let e of Nc.keys())n.has(e)||Nc.delete(e);let r=mJ(),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`),Hq().add(1)),{documents:[...e,...jc(),...i,...xc([...e,...i])],truncated:a}}function Fc(){return Ac().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Ic(){return te?`gen:${te()}|skills${Fc()}`:`${[...S()].filter(([e])=>!LC(e)&&!zC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Mc(t)}`).join(``)}|skills${Fc()}`}let Lc=jt===void 0;jt?.then(()=>{Lc=!0},e=>{Lc=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Rc(){return!Lc}async function zc(){let e=`${l}${T??``}`,t=Ic(),n=eY.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 Pc();if(!e)return Wq().add(1,{mode:`cold`}),{corpus:ra(t),truncated:n};let a=ee(e,t);if(a.rebuilt){Wq().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 Wq().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}})();eY.set(e,{fingerprint:t,pending:a});try{let n=await a;return eY.get(e)?.pending===a&&eY.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw eY.get(e)?.pending===a&&eY.delete(e),t}}function Bc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{zc().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}Bc();let Vc=kH({GET:J(g,OH(async(e,t)=>{let n=ws(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Cc(n.get(`intent`)),o=Zs(n.get(`ranking`)),s=wc(n.get(`scope`)??n.get(`scopes`)),c=Tc(n.get(`semantic`)),l=Ec(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,p,await kc({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(lee,OH(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Cc(n.intent),a=Zs(n.ranking),o=wc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Tc(n.semantic),l=Ec(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,p,await kc({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`}),Hc=J(g,OH(async(e,t)=>{q(t,200,hee,{...await gR(nu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Uc(e,t){if(r(e,t,{handler:`handoff`}))try{await Rae(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:Fn.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:cw(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Wc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await QP(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:cw(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Gc=J(Ti,async(e,t,n)=>{try{if(!T){fL(`no-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`no-remote`},{handler:dL});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!hse(e,n.kind)){fL(`invalid-path`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`invalid-path`},{handler:dL});return}let r=bse(T);if(r===null){if(gL(T).kind===`no-remote`){fL(`no-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`no-remote`},{handler:dL});return}fL(`detached-head`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`detached-head`},{handler:dL});return}let i=gL(T);if(i.kind===`no-remote`){fL(`no-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`no-remote`},{handler:dL});return}if(i.kind===`non-github`){fL(`non-github-remote`,{kind:n.kind}),q(t,200,wr,{ok:!1,error:`non-github-remote`},{handler:dL});return}if(!Tse(T,r)){fL(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,wr,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:dL});return}let a=KJ(T,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=gse(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=_se(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${ig(s)}`,u=await vse(T,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);fL(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,wr,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:dL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:dL,cause:e})}},{handler:dL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:dL})}),Kc=J(g,async(e,t)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:mH});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(!_r(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:mH});return}if(!fH(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:mH});return}q(t,200,Zn,await pH(T,r,i,a),{handler:mH})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mH,cause:e})}},{handler:mH,method:`GET`,skipBodyParse:!0}),qc=J(Ki,async(e,t,n)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:NL});return}if(!fH(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:NL});return}let e=KJ(T,l);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;q(t,200,oee,await IL(T,n.branch,r,n.kind),{handler:NL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:NL,cause:e})}},{handler:NL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:NL})}),Jc=J(zi,async(e,t,n)=>{if(yV(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:yH});return}if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:yH});return}try{q(t,200,ei,await _s(()=>xH(T,n.branch,{fastForward:n.fastForward===!0})),{handler:yH})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yH,cause:e})}},{handler:yH,method:`POST`});async function Yc(e){let[t,...n]=it,r=[...n,...e];return await new Promise((e,n)=>{let i=bl(t,r,zP({...ro,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},xL),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 ${xL}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=ML(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 Xc=J(g,async(e,t)=>{if(!fn.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:vL,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Yc([`share`,`owners`,`--json`]),n=TL(wL(e));jL(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,Mi,n,{handler:vL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vL,cause:e})}finally{fn.release(`/api/share/publish/owners`)}},{handler:vL,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:vL})}),Zc=J(g,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!CL(r)||!SL(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:yL});return}if(!fn.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:yL,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Yc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=DL(wL(e));jL(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,si,n,{handler:yL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yL,cause:e})}finally{fn.release(`/api/share/publish/name-check`)}},{handler:yL,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:yL})}),Qc=J(Hn,async(e,t,n)=>{if(!T){jL(`publish-create`,`no-project`),q(t,200,Hr,{ok:!1,error:`no-project`},{handler:bL});return}if(!CL(n.owner)||!SL(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:bL});return}if(!fn.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:bL,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 Yc(e),i=AL(wL(r));jL(`publish-create`,i.ok?`ok`:i.error),i.ok&&$e?.()?.refreshRemote().catch(()=>{}),q(t,200,Hr,i,{handler:bL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:bL,cause:e})}finally{fn.release(`/api/share/publish`)}},{handler:bL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:bL})}),$c=J(_,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,Zt,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),el=T?SM(T):null;async function tl(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:bM(e.headers),previewUrl:null,port:el?As(el)?.port??0:0,singleFile:on};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,xe,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let nl=`local-op-embeddings-set-key`,rl=`local-op-embeddings-clear-key`,il=`/api/local-op/embeddings`;function al(){let e=Yt?.();return{projectDir:T??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let ol=J(mr,async(e,t,n)=>{if(!fn.tryAcquire(il)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:nl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=al();await new NP(Jt).setForProject(e,r,n.key),Ut?.reloadCredential(),q(t,200,xr,{keyPresent:!0},{handler:nl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:nl,cause:e})}finally{fn.release(il)}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:nl})}),sl=J(g,async(e,t)=>{if(!fn.tryAcquire(il)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:rl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=al();await new NP(Jt).clearForProject(e,n),Ut?.reloadCredential(),q(t,200,xr,{keyPresent:!1},{handler:rl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:rl,cause:e})}finally{fn.release(il)}},{handler:rl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:rl})}),cl=`local-op-embeddings-test`,ll=`/api/local-op/embeddings/test`,ul=J(g,async(e,t)=>{if(!fn.tryAcquire(ll)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:cl,extraHeaders:{"Retry-After":`5`}});return}try{let e=Yt?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await EP(new NP(Jt),T??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await fae({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,En,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:cl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:cl,cause:e})}finally{fn.release(ll)}},{handler:cl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:cl})}),dl=J(g,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Ut){let t=Ut.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Yt?.()?.baseUrl??`https://api.openai.com/v1`,o=await EP(new NP(Jt),T??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of m())!LC(e)&&!zC(e)&&!ur(e)&&(f+=1);q(t,200,Fr,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0});async function fl(e,t){let n=$t?.()??Lr;try{let r=await qi(e,HI(l,n,{docName:t,projectDir:T??l,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=tn?.()??`warning`;if(Ie&&a!==`off`&&!UC(t)){Ie.updateDocumentFromMarkdown(t,e);let r=eL({projectDir:T??l,contentDir:l,baseConfig:n,backlinkIndex:Ie,linksValidation:a,admittedDocNames:br,docFilePathFor:e=>LJ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:LJ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function pl(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=WI({projectDir:T??l,contentDir:l});return mI(t.schemas,n)}let ml=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!nY(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=$t?.()??Lr,i=[],a=zI(l,n??void 0,e=>i.push(e)),o=VI(T??l,BI(r,a),e=>i.push(e));n===null&&i.push(...pl(o)),q(t,200,Nt,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),hl=J(ce,async(e,t,n)=>{let r;try{r=$I(z(l),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Ve?.(`lint-config`);try{let e=$t?.()??Lr,n=[],r=zI(l,void 0,e=>n.push(e)),i=VI(T??l,BI(e,r),e=>n.push(e));n.push(...pl(i)),q(t,200,Nt,{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`}),gl=J(dee,async(e,t,n)=>{let r;try{let e=z(T??l),t=n.parentPath??[];r=n.delete?$oe(e,n.file):n.field!==void 0&&n.removeField?Zoe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Qoe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Yoe(e,n.file,n.field,n.constraint,t):Xoe(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Ve?.(`files`),Ve?.(`lint-config`);try{let e=$t?.()??Lr,n=[],r=zI(l,void 0,e=>n.push(e)),i=VI(T??l,BI(e,r),e=>n.push(e));n.push(...pl(i)),q(t,200,Nt,{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`}),_l=J(g,async(e,t)=>{try{let e=z(T??l),{schemas:n,truncated:r}=woe(e),i=new Set(n),a=!1;if(Tt!==void 0){let t=bJ({contentDir:l,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&&dr(a)){let t=R(e,z(l,a));!t.startsWith(`..`)&&!El(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,In,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),vl=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},yl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!nY(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=LJ(l,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=$t?.()??Lr,a=[],o=await UI({projectDir:T??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:vl});q(t,200,b,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof RF){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}),xl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!SJ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=$t?.()??Lr;q(t,200,da,await GI({projectDir:T??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:vl}),{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}),Sl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!SJ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!SJ(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=LJ(l,o)??`${o}.md`}let s=$t?.()??Lr;q(t,200,ne,await nse(eL({projectDir:T??l,contentDir:l,baseConfig:s,liveSourceFor:vl,backlinkIndex:Ie??null,linksValidation:tn?.(),admittedDocNames:br,docFilePathFor:e=>LJ(l,e)}),{targetPath:i}),{handler:`audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),wl=J(aa,async(t,n,r)=>{try{let t=DJ(r.docName,n,`lint-fix`);if(t===null)return;let i=nr(t),a=yV(r,ut);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(LC(i)||zC(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=LJ(l,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}OJ(z(l,f),l);let p=$t?.()??Lr,{stored:m}=yi(a.summary),h=await s.getSession(i,o,{displayName:c,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Goe({projectDir:T??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=qn(d),n=Vn[t]??Vr(u??o);Ze?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{XE(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,JE(h))},h.origin),a.kind!==`anonymous`&&sP(i,o,c,u,void 0,a.kind===`agent`?vi({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{Ze?.touchMode(o,`idle`)}let t=await fr(i);if(t?.kind===`failure`){hr(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){gr(n,`lint-fix`);return}sr(i,`lint-fix`);try{b=await qi(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,Rt,{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 RF){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof yw){bw(n,e,`lint-fix`);return}if(e instanceof Tw){Dw(n,e,`lint-fix`);return}if(e instanceof oD){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`}),Dl=`link-preview`,Ol=new IU({cacheDir:on?null:z(T??l,`.ok`,`local`,`link-previews`)}),Al=null,jl=()=>(Al??=Ol.init(),Al),Ml=sn??DU;async function Nl(e){let t=await Ml(e);return t.ok?{ok:!0,metadata:await MU({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Ml})}:{ok:!1,reason:t.reason}}let Pl=()=>{try{return cn?.()===!0}catch{return!1}},Fl={"/api/config":tl,"/api/asset":Ba,"/api/asset-text":Wa,"/api/document":Wi,"/api/documents":Gi,"/api/backlinks":Yi,"/api/backlink-counts":Zi,"/api/link-preview":J(Vt,async(e,t,n)=>{try{if(!Pl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,de,{ok:!1,reason:`disabled`},{handler:Dl});return}await jl();let e=!1,r=await Ol.load(n.url,()=>(e=!0,Nl(n.url)));Ol.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,de,i,{handler:Dl})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Dl,cause:e})}},{handler:Dl,method:`POST`,preBodyGate:(e,t)=>{let n=zU({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:Dl}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Dl}),!1)}}),"/api/forward-links":Qi,"/api/link-graph":$i,"/api/dead-links":sa,"/api/orphans":ea,"/api/hubs":na,"/api/tags":Ss,"/api/pages":Za,"/api/folder-config":js,"/api/template":Bs,"/api/template/import":Vs,"/api/templates":Ps,"/api/skill":lc,"/api/skill-file":hc,"/api/skills":nc,"/api/skills/management":ac,"/api/skill/install":gc,"/api/skill/uninstall":_c,"/api/skill/restore":yc,"/api/skill/update":bc,"/api/skill-targets":vc,"/api/search":Vc,"/api/semantic-status":dl,"/api/lint/config":ml,"/api/lint/markdownlint-config":hl,"/api/lint/frontmatter-schema":gl,"/api/lint/frontmatter-schemas":_l,"/api/lint":yl,"/api/lint/audit":xl,"/api/lint/fix":wl,"/api/audit":Sl,"/api/suggest-links":k,"/api/page-headings":Ja,"/api/create-page":Ka,"/api/create-folder":qa,"/api/duplicate-path":E,"/api/rename-path":Ya,"/api/delete-path":D,"/api/trash/cleanup":Xa,"/api/upload":Qa,"/api/agent-write":Ni,"/api/agent-write-md":Fi,"/api/agent-write-batch":Li,"/api/frontmatter-patch":Ri,"/api/agent-patch":ca,"/api/agent-undo":la,"/api/agent-activity":ua,"/api/agent-burst-diff":ma,"/api/save-version":ba,"/api/history":xa,"/api/rollback":wa,"/api/metrics/reconciliation":Ta,"/api/metrics/parse-health":Ea,"/api/metrics/agent-presence":Na,"/api/metrics/agent-effects":Pa,"/api/metrics/watcher-recent":Ia,"/api/__embed-detect":La,"/api/server-info":Oa,"/api/acp/catalog":ja,"/api/share/construct-url":Gc,"/api/share/target-status":qc,"/api/git/branch-info":Kc,"/api/git/checkout":Jc,"/api/share/publish/owners":Xc,"/api/share/publish/name-check":Zc,"/api/share/publish":Qc,"/api/principal":Ma,"/api/rescue":Ga,"/api/workspace":Ra,"/api/sync/status":is,"/api/sync/trigger":ls,"/api/sync/conflicts":ds,"/api/sync/conflict-content":ps,"/api/sync/resolve-conflict":fs,"/api/local-op/clone":j,"/api/local-op/ok-init":lo,"/api/local-op/auth/login":ko,"/api/local-op/auth/status":zo,"/api/local-op/auth/pat":Ho,"/api/local-op/auth/gh-login":No,"/api/local-op/auth/cancel":Io,"/api/local-op/auth/repos":Wo,"/api/local-op/auth/signout":Qo,"/api/local-op/auth/set-identity":rs,"/api/local-op/embeddings/set-key":ol,"/api/local-op/embeddings/clear-key":sl,"/api/local-op/embeddings/test":ul,"/api/installed-agents":xs,"/api/spawn-cursor":Wc,"/api/handoff":Uc,"/api/install-skill":bs,"/api/skill/install-state":Hc,"/api/seed/plan":hs,"/api/seed/apply":vs,"/api/seed/packs":ys,"/api/client-logs":$c};ye&&(Fl[`/api/test-reset`]=ga,Fl[`/api/test-flush-git`]=ha,Fl[`/api/test-rescan-backlinks`]=va,Fl[`/api/test-rescan-files`]=ya);let Ll=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(`.`)),Rl=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let r=e.url?.split(`?`)[0];if(!r)return;let a=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};Uie({ts:Date.now(),url:r,method:e.method??``,ua:a(`user-agent`),origin:a(`origin`),referer:a(`referer`),host:a(`host`),remote:e.socket?.remoteAddress,secChUa:a(`sec-ch-ua`),secChUaMobile:a(`sec-ch-ua-mobile`),secChUaPlatform:a(`sec-ch-ua-platform`),secFetchSite:a(`sec-fetch-site`),secFetchDest:a(`sec-fetch-dest`),secFetchMode:a(`sec-fetch-mode`),secFetchUser:a(`sec-fetch-user`)});let o=e.method??`GET`,s=r;r.startsWith(`/api/history/`)?s=`/api/history/:sha`:r.startsWith(`/api/tags/`)?s=`/api/tags/:name`:Fl[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?aw(e):void 0;if(c!==void 0&&(sw(e,c),typeof t.setHeader==`function`&&t.setHeader(rw,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Y.info({event:`api.access`,requestId:c,method:o,route:s,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${o} ${s} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(r.startsWith(`/api/`)){let r=e.headers.origin;if(r!==void 0&&!Nj(r,n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(r!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,r),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${rw}, ${Rn.protocol}, ${Rn.runtime}, ${Rn.kind}`),t.setHeader(`Access-Control-Expose-Headers`,rw)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Ll.has(r)||Rl.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!Sj(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(on&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!Sj(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=xo.extract(wo.active(),e.headers),u=Lo(),d=Date.now();await wo.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:So.SERVER,attributes:{[us]:o,[ss]:s,[cs]:r,[os]:`http`,[as]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=Fl[r],a=!1;if(i)a=!0,await i(e,t);else if(r.startsWith(`/api/history/`)){let n=decodeURIComponent(r.slice(13));n&&(a=!0,await Sa(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await Cs(e,t,n))}a||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${o} ${r}`});let s=t.statusCode;n.setAttribute(ms,s),s>=500&&n.setStatus({code:bo.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:bo.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s,cause:e}),e}finally{n.end();let e=(Date.now()-d)/1e3;kq().record(e,{[us]:o,[ss]:s,[ms]:t.statusCode})}}))}}}function aY(e){let t=e?.code;return typeof t==`string`?t:void 0}function oY(e){let t;try{t=Wl(e.contentDir,{withFileTypes:!0})}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&qC(n.name,Fa)&&e.basenameIndex.add(n.name)}async function sY(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await du(i,{withFileTypes:!0})}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=Pj(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await lu(a)}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await fu(a)}catch(t){let n=aY(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Fj(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await pu(i)}catch(t){let n=aY(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()&&qC(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()&&qC(a,Ca)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const cY=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(),lY=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function uY(e){return lY.includes(e)}function dY(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function fY(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!uY(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 pY=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=dY(e,this.payload)}};function mY(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=cY.safeParse(t);return n.success?n.data:void 0}var hY=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const gY=F(`conflict-storage`);var _Y=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(SM(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){gY.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){gY.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||zl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Ql(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return gY.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-B6bZ5eA-.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(!Fj(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);$z(r,t),ts(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`]),gY.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await bS(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){gY.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}),gY.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(!Fj(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch($z(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-B6bZ5eA-.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);$z(a,i),ts(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);ts(a,n,`utf-8`);break;case`delete`:B(a)&&Vo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function vY(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 yY(e,t){let n=SM(e);try{zl(n,{recursive:!0}),Ql(L(n,pe),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=ds(e);zl(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`};Ql(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const bY=new Map;let xY=!1;function SY(e,t){try{let n=vY(e,t);for(let e of bY.keys())yY(e,n)}catch{}}function CY(e){bY.set(e,(bY.get(e)??0)+1),xY||(xY=!0,process.on(`uncaughtExceptionMonitor`,SY));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=bY.get(e)??0;n<=1?bY.delete(e):bY.set(e,n-1)}}}function wY(e){let t=e.scheduler??m,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function TY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function EY(e){if(!B(e))return{};let t;try{t=(0,fj.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(!TY(t))return{};let n=t.telemetry;if(!TY(n))return{};let r=n.localSink;return TY(r)?r:{}}function DY(e){return typeof e==`boolean`?e:void 0}function OY(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function kY(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function AY(e){if(TY(e))return OY(e.maxBytes)}function jY(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=EY(Mo(`project`,e.projectDir)),n=EY(Mo(`project-local`,e.projectDir));if((DY(n.enabled)??DY(t.enabled)??!0)===!1)return null;let r=AY(n.spans)??AY(t.spans)??52428800,i=AY(n.logs)??AY(t.logs)??26214400,a=kY(n.attributeDenylist)??kY(t.attributeDenylist)??Ba;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var MY;(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})(MY||={});var NY;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(NY||={});const PY=MY.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),FY=e=>{switch(typeof e){case`undefined`:return PY.undefined;case`string`:return PY.string;case`number`:return Number.isNaN(e)?PY.nan:PY.number;case`boolean`:return PY.boolean;case`function`:return PY.function;case`bigint`:return PY.bigint;case`symbol`:return PY.symbol;case`object`:return Array.isArray(e)?PY.array:e===null?PY.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?PY.promise:typeof Map<`u`&&e instanceof Map?PY.map:typeof Set<`u`&&e instanceof Set?PY.set:typeof Date<`u`&&e instanceof Date?PY.date:PY.object;default:return PY.unknown}},X=MY.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 IY=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,MY.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()}};IY.create=e=>new IY(e);const LY=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===PY.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,MY.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${MY.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${MY.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${MY.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}"`:MY.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,MY.assertNever(e)}return{message:n}};let RY=LY;function zY(){return RY}const BY=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 VY(e,t){let n=zY(),r=BY({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===LY?void 0:LY].filter(e=>!!e)});e.common.issues.push(r)}var HY=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 UY;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 UY;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 UY=Object.freeze({status:`aborted`}),WY=e=>({status:`dirty`,value:e}),GY=e=>({status:`valid`,value:e}),KY=e=>e.status===`aborted`,qY=e=>e.status===`dirty`,JY=e=>e.status===`valid`,YY=e=>typeof Promise<`u`&&e instanceof Promise;var XY;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(XY||={});var ZY=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 QY=(e,t)=>{if(JY(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 IY(e.common.issues);return this._error=t,this._error}}};function $Y(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 eX=class{get description(){return this._def.description}_getType(e){return FY(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:FY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new HY,ctx:{common:e.parent.common,data:e.data,parsedType:FY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(YY(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:FY(e)};return QY(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:FY(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return JY(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=>JY(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:FY(e)},r=this._parse({data:e,path:n.path,parent:n});return QY(n,await(YY(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 nZ({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 rZ.create(this,this._def)}nullable(){return iZ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return LX.create(this)}promise(){return tZ.create(this,this._def)}or(e){return BX.create([this,e],this._def)}and(e){return WX.create(this,e,this._def)}transform(e){return new nZ({...$Y(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new aZ({...$Y(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new cZ({typeName:Z.ZodBranded,type:this,...$Y(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new oZ({...$Y(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 lZ.create(this,e)}readonly(){return uZ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const tX=/^c[^\s-]{8,}$/i,nX=/^[0-9a-z]+$/,rX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iX=/^[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,aX=/^[a-z0-9_-]{21}$/i,oX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sX=/^[-+]?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)?)??$/,cX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let lX;const uX=/^(?:(?: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])$/,dX=/^(?:(?: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])$/,fX=/^(([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]))$/,pX=/^(([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])$/,mX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gX=`((\\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])))`,_X=RegExp(`^${gX}$`);function vX(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 yX(e){return RegExp(`^${vX(e)}$`)}function bX(e){let t=`${gX}T${vX(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xX(e,t){return!!((t===`v4`||!t)&&uX.test(e)||(t===`v6`||!t)&&fX.test(e))}function SX(e,t){if(!oX.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 CX(e,t){return!!((t===`v4`||!t)&&dX.test(e)||(t===`v6`||!t)&&pX.test(e))}var wX=class e extends eX{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==PY.string){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.string,received:t.parsedType}),UY}let t=new HY,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),VY(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),VY(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?VY(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&VY(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)cX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)lX||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),lX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)iX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)aX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)tX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)nX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)rX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(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),VY(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),VY(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),VY(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),VY(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),VY(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?bX(r).test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?_X.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?yX(r).test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?sX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?SX(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?CX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?mX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?hX.test(e.data)||(n=this._getOrReturnCtx(e,n),VY(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):MY.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,...XY.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...XY.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...XY.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...XY.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...XY.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...XY.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...XY.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...XY.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...XY.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...XY.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...XY.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...XY.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...XY.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...XY.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,...XY.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,...XY.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...XY.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...XY.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...XY.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...XY.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...XY.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...XY.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...XY.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...XY.errToObj(t)})}nonempty(e){return this.min(1,XY.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}};wX.create=e=>new wX({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...$Y(e)});function TX(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 EX=class e extends eX{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)!==PY.number){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.number,received:t.parsedType}),UY}let t,n=new HY;for(let r of this._def.checks)r.kind===`int`?MY.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),VY(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),VY(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),VY(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?TX(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),VY(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),VY(t,{code:X.not_finite,message:r.message}),n.dirty()):MY.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,XY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,XY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,XY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,XY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:XY.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:XY.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:XY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:XY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:XY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:XY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:XY.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:XY.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:XY.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:XY.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`&&MY.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)}};EX.create=e=>new EX({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...$Y(e)});var DX=class e extends eX{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)!==PY.bigint)return this._getInvalidInput(e);let t,n=new HY;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),VY(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),VY(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),VY(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):MY.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.bigint,received:t.parsedType}),UY}gte(e,t){return this.setLimit(`min`,e,!0,XY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,XY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,XY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,XY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:XY.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:XY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:XY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:XY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:XY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:XY.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}};DX.create=e=>new DX({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...$Y(e)});var OX=class extends eX{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==PY.boolean){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.boolean,received:t.parsedType}),UY}return GY(e.data)}};OX.create=e=>new OX({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...$Y(e)});var kX=class e extends eX{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==PY.date){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.date,received:t.parsedType}),UY}if(Number.isNaN(e.data.getTime()))return VY(this._getOrReturnCtx(e),{code:X.invalid_date}),UY;let t=new HY,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),VY(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),VY(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):MY.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:XY.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:XY.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)}};kX.create=e=>new kX({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...$Y(e)});var AX=class extends eX{_parse(e){if(this._getType(e)!==PY.symbol){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.symbol,received:t.parsedType}),UY}return GY(e.data)}};AX.create=e=>new AX({typeName:Z.ZodSymbol,...$Y(e)});var jX=class extends eX{_parse(e){if(this._getType(e)!==PY.undefined){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.undefined,received:t.parsedType}),UY}return GY(e.data)}};jX.create=e=>new jX({typeName:Z.ZodUndefined,...$Y(e)});var MX=class extends eX{_parse(e){if(this._getType(e)!==PY.null){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.null,received:t.parsedType}),UY}return GY(e.data)}};MX.create=e=>new MX({typeName:Z.ZodNull,...$Y(e)});var NX=class extends eX{constructor(){super(...arguments),this._any=!0}_parse(e){return GY(e.data)}};NX.create=e=>new NX({typeName:Z.ZodAny,...$Y(e)});var PX=class extends eX{constructor(){super(...arguments),this._unknown=!0}_parse(e){return GY(e.data)}};PX.create=e=>new PX({typeName:Z.ZodUnknown,...$Y(e)});var FX=class extends eX{_parse(e){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.never,received:t.parsedType}),UY}};FX.create=e=>new FX({typeName:Z.ZodNever,...$Y(e)});var IX=class extends eX{_parse(e){if(this._getType(e)!==PY.undefined){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.void,received:t.parsedType}),UY}return GY(e.data)}};IX.create=e=>new IX({typeName:Z.ZodVoid,...$Y(e)});var LX=class e extends eX{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==PY.array)return VY(t,{code:X.invalid_type,expected:PY.array,received:t.parsedType}),UY;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(VY(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&&(VY(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&&(VY(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 ZY(t,e,t.path,n)))).then(e=>HY.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new ZY(t,e,t.path,n)));return HY.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:XY.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:XY.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:XY.toString(n)}})}nonempty(e){return this.min(1,e)}};LX.create=(e,t)=>new LX({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...$Y(t)});function RX(e){if(e instanceof zX){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=rZ.create(RX(r))}return new zX({...e._def,shape:()=>t})}else if(e instanceof LX)return new LX({...e._def,type:RX(e.element)});else if(e instanceof rZ)return rZ.create(RX(e.unwrap()));else if(e instanceof iZ)return iZ.create(RX(e.unwrap()));else if(e instanceof GX)return GX.create(e.items.map(e=>RX(e)));else return e}var zX=class e extends eX{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=MY.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==PY.object){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.object,received:t.parsedType}),UY}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof FX&&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 ZY(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof FX){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&&(VY(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 ZY(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=>HY.mergeObjectSync(t,e)):HY.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return XY.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:XY.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 MY.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 MY.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return RX(this)}partial(t){let n={};for(let e of MY.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 MY.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof rZ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return QX(MY.objectKeys(this.shape))}};zX.create=(e,t)=>new zX({shape:()=>e,unknownKeys:`strip`,catchall:FX.create(),typeName:Z.ZodObject,...$Y(t)}),zX.strictCreate=(e,t)=>new zX({shape:()=>e,unknownKeys:`strict`,catchall:FX.create(),typeName:Z.ZodObject,...$Y(t)}),zX.lazycreate=(e,t)=>new zX({shape:e,unknownKeys:`strip`,catchall:FX.create(),typeName:Z.ZodObject,...$Y(t)});var BX=class extends eX{_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 IY(e.ctx.common.issues));return VY(t,{code:X.invalid_union,unionErrors:n}),UY}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 IY(e));return VY(t,{code:X.invalid_union,unionErrors:i}),UY}}get options(){return this._def.options}};BX.create=(e,t)=>new BX({options:e,typeName:Z.ZodUnion,...$Y(t)});const VX=e=>e instanceof XX?VX(e.schema):e instanceof nZ?VX(e.innerType()):e instanceof ZX?[e.value]:e instanceof $X?e.options:e instanceof eZ?MY.objectValues(e.enum):e instanceof aZ?VX(e._def.innerType):e instanceof jX?[void 0]:e instanceof MX?[null]:e instanceof rZ?[void 0,...VX(e.unwrap())]:e instanceof iZ?[null,...VX(e.unwrap())]:e instanceof cZ||e instanceof uZ?VX(e.unwrap()):e instanceof oZ?VX(e._def.innerType):[];var HX=class e extends eX{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==PY.object)return VY(t,{code:X.invalid_type,expected:PY.object,received:t.parsedType}),UY;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}):(VY(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),UY)}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=VX(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,...$Y(r)})}};function UX(e,t){let n=FY(e),r=FY(t);if(e===t)return{valid:!0,data:e};if(n===PY.object&&r===PY.object){let n=MY.objectKeys(t),r=MY.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=UX(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===PY.array&&r===PY.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=UX(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===PY.date&&r===PY.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var WX=class extends eX{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(KY(e)||KY(r))return UY;let i=UX(e.value,r.value);return i.valid?((qY(e)||qY(r))&&t.dirty(),{status:t.value,value:i.data}):(VY(n,{code:X.invalid_intersection_types}),UY)};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}))}};WX.create=(e,t,n)=>new WX({left:e,right:t,typeName:Z.ZodIntersection,...$Y(n)});var GX=class e extends eX{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PY.array)return VY(n,{code:X.invalid_type,expected:PY.array,received:n.parsedType}),UY;if(n.data.length<this._def.items.length)return VY(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),UY;!this._def.rest&&n.data.length>this._def.items.length&&(VY(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 ZY(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>HY.mergeArray(t,e)):HY.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};GX.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new GX({items:e,typeName:Z.ZodTuple,rest:null,...$Y(t)})};var KX=class e extends eX{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!==PY.object)return VY(n,{code:X.invalid_type,expected:PY.object,received:n.parsedType}),UY;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new ZY(n,e,n.path,e)),value:a._parse(new ZY(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?HY.mergeObjectAsync(t,r):HY.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof eX?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...$Y(r)}):new e({keyType:wX.create(),valueType:t,typeName:Z.ZodRecord,...$Y(n)})}},qX=class extends eX{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!==PY.map)return VY(n,{code:X.invalid_type,expected:PY.map,received:n.parsedType}),UY;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new ZY(n,e,n.path,[a,`key`])),value:i._parse(new ZY(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 UY;(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 UY;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};qX.create=(e,t,n)=>new qX({valueType:t,keyType:e,typeName:Z.ZodMap,...$Y(n)});var JX=class e extends eX{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PY.set)return VY(n,{code:X.invalid_type,expected:PY.set,received:n.parsedType}),UY;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(VY(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&&(VY(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 UY;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 ZY(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:XY.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:XY.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};JX.create=(e,t)=>new JX({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...$Y(t)});var YX=class e extends eX{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==PY.function)return VY(t,{code:X.invalid_type,expected:PY.function,received:t.parsedType}),UY;function n(e,n){return BY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zY(),LY].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return BY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,zY(),LY].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 tZ){let e=this;return GY(async function(...t){let o=new IY([]),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 GY(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new IY([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new IY([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:GX.create(t).rest(PX.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||GX.create([]).rest(PX.create()),returns:n||PX.create(),typeName:Z.ZodFunction,...$Y(r)})}},XX=class extends eX{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})}};XX.create=(e,t)=>new XX({getter:e,typeName:Z.ZodLazy,...$Y(t)});var ZX=class extends eX{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return VY(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),UY}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZX.create=(e,t)=>new ZX({value:e,typeName:Z.ZodLiteral,...$Y(t)});function QX(e,t){return new $X({values:e,typeName:Z.ZodEnum,...$Y(t)})}var $X=class e extends eX{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return VY(t,{expected:MY.joinValues(n),received:t.parsedType,code:X.invalid_type}),UY}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return VY(t,{received:t.data,code:X.invalid_enum_value,options:n}),UY}return GY(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})}};$X.create=QX;var eZ=class extends eX{_parse(e){let t=MY.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==PY.string&&n.parsedType!==PY.number){let e=MY.objectValues(t);return VY(n,{expected:MY.joinValues(e),received:n.parsedType,code:X.invalid_type}),UY}if(this._cache||=new Set(MY.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=MY.objectValues(t);return VY(n,{received:n.data,code:X.invalid_enum_value,options:e}),UY}return GY(e.data)}get enum(){return this._def.values}};eZ.create=(e,t)=>new eZ({values:e,typeName:Z.ZodNativeEnum,...$Y(t)});var tZ=class extends eX{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==PY.promise&&t.common.async===!1?(VY(t,{code:X.invalid_type,expected:PY.promise,received:t.parsedType}),UY):GY((t.parsedType===PY.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};tZ.create=(e,t)=>new tZ({type:e,typeName:Z.ZodPromise,...$Y(t)});var nZ=class extends eX{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=>{VY(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 UY;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?UY:r.status===`dirty`||t.value===`dirty`?WY(r.value):r});{if(t.value===`aborted`)return UY;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?UY:r.status===`dirty`||t.value===`dirty`?WY(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`?UY:(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`?UY:(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(!JY(e))return UY;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=>JY(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):UY);MY.assertNever(r)}};nZ.create=(e,t,n)=>new nZ({schema:e,typeName:Z.ZodEffects,effect:t,...$Y(n)}),nZ.createWithPreprocess=(e,t,n)=>new nZ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...$Y(n)});var rZ=class extends eX{_parse(e){return this._getType(e)===PY.undefined?GY(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rZ.create=(e,t)=>new rZ({innerType:e,typeName:Z.ZodOptional,...$Y(t)});var iZ=class extends eX{_parse(e){return this._getType(e)===PY.null?GY(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};iZ.create=(e,t)=>new iZ({innerType:e,typeName:Z.ZodNullable,...$Y(t)});var aZ=class extends eX{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===PY.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};aZ.create=(e,t)=>new aZ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...$Y(t)});var oZ=class extends eX{_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 YY(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new IY(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new IY(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};oZ.create=(e,t)=>new oZ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...$Y(t)});var sZ=class extends eX{_parse(e){if(this._getType(e)!==PY.nan){let t=this._getOrReturnCtx(e);return VY(t,{code:X.invalid_type,expected:PY.nan,received:t.parsedType}),UY}return{status:`valid`,value:e.data}}};sZ.create=e=>new sZ({typeName:Z.ZodNaN,...$Y(e)});var cZ=class extends eX{_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}},lZ=class e extends eX{_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`?UY:e.status===`dirty`?(t.dirty(),WY(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`?UY: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})}},uZ=class extends eX{_parse(e){let t=this._def.innerType._parse(e),n=e=>(JY(e)&&(e.value=Object.freeze(e.value)),e);return YY(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};uZ.create=(e,t)=>new uZ({innerType:e,typeName:Z.ZodReadonly,...$Y(t)}),zX.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||={}),wX.create,EX.create,sZ.create,DX.create,OX.create,kX.create,AX.create,jX.create,MX.create,NX.create,PX.create,FX.create,IX.create,LX.create;const dZ=zX.create;zX.strictCreate,BX.create,HX.create,WX.create,GX.create,KX.create,qX.create,JX.create,YX.create,XX.create,ZX.create,$X.create,eZ.create,tZ.create,nZ.create,rZ.create,iZ.create,nZ.createWithPreprocess,lZ.create;const fZ=Ia(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);_o.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Ha(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ea(e,t,n),e.parseAsync=async(t,n)=>Oa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>La(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)}),pZ=Ia(`ZodMiniObject`,(e,t)=>{Ta.init(e,t),fZ.init(e,t),to(e,`shape`,()=>t.shape)});function mZ(e,t){return new pZ({type:`object`,shape:e??{},...Pa(t)})}function hZ(e){return!!e._zod}function gZ(e){let t=Object.values(e);if(t.length===0)return mZ({});let n=t.every(hZ),r=t.every(e=>!hZ(e));if(n)return mZ(e);if(r)return dZ(e);throw Error(`Mixed Zod versions detected in object shape.`)}function _Z(e,t){return hZ(e)?Ea(e,t):e.safeParse(t)}async function vZ(e,t){return hZ(e)?await La(e,t):await e.safeParseAsync(t)}function yZ(e){if(!e)return;let t;if(t=hZ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function bZ(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 gZ(e)}}if(hZ(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 xZ(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 SZ(e){return e.description}function CZ(e){if(hZ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function wZ(e){if(hZ(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 TZ=`2025-11-25`,EZ=[TZ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],DZ=`io.modelcontextprotocol/related-task`,OZ=uo(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),kZ=k([A(),P().int()]),AZ=A();io({ttl:P().optional(),pollInterval:P().optional()});const jZ=O({ttl:P().optional()}),MZ=O({taskId:A()}),NZ=io({progressToken:kZ.optional(),[DZ]:MZ.optional()}),PZ=O({_meta:NZ.optional()}),FZ=PZ.extend({task:jZ.optional()}),IZ=e=>FZ.safeParse(e).success,LZ=O({method:A(),params:PZ.loose().optional()}),RZ=O({_meta:NZ.optional()}),zZ=O({method:A(),params:RZ.loose().optional()}),BZ=io({_meta:NZ.optional()}),VZ=k([A(),P().int()]),HZ=O({jsonrpc:D(`2.0`),id:VZ,...LZ.shape}).strict(),UZ=e=>HZ.safeParse(e).success,WZ=O({jsonrpc:D(`2.0`),...zZ.shape}).strict(),GZ=e=>WZ.safeParse(e).success,KZ=O({jsonrpc:D(`2.0`),id:VZ,result:BZ}).strict(),qZ=e=>KZ.safeParse(e).success;var JZ;(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`})(JZ||={});const YZ=O({jsonrpc:D(`2.0`),id:VZ.optional(),error:O({code:P().int(),message:A(),data:E().optional()})}).strict(),XZ=e=>YZ.safeParse(e).success,ZZ=k([HZ,WZ,KZ,YZ]);k([KZ,YZ]);const QZ=BZ.strict(),$Z=RZ.extend({requestId:VZ.optional(),reason:A().optional()}),eQ=zZ.extend({method:D(`notifications/cancelled`),params:$Z}),tQ=O({icons:N(O({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:za([`light`,`dark`]).optional()})).optional()}),nQ=O({name:A(),title:A().optional()}),rQ=nQ.extend({...nQ.shape,...tQ.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),iQ=co(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,so(O({form:so(O({applyDefaults:M().optional()}),j(A(),E())).optional(),url:OZ.optional()}),j(A(),E()).optional())),aQ=io({list:OZ.optional(),cancel:OZ.optional(),requests:io({sampling:io({createMessage:OZ.optional()}).optional(),elicitation:io({create:OZ.optional()}).optional()}).optional()}),oQ=io({list:OZ.optional(),cancel:OZ.optional(),requests:io({tools:io({call:OZ.optional()}).optional()}).optional()}),sQ=O({experimental:j(A(),OZ).optional(),sampling:O({context:OZ.optional(),tools:OZ.optional()}).optional(),elicitation:iQ.optional(),roots:O({listChanged:M().optional()}).optional(),tasks:aQ.optional(),extensions:j(A(),OZ).optional()}),cQ=PZ.extend({protocolVersion:A(),capabilities:sQ,clientInfo:rQ}),lQ=LZ.extend({method:D(`initialize`),params:cQ}),uQ=e=>lQ.safeParse(e).success,dQ=O({experimental:j(A(),OZ).optional(),logging:OZ.optional(),completions:OZ.optional(),prompts:O({listChanged:M().optional()}).optional(),resources:O({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:O({listChanged:M().optional()}).optional(),tasks:oQ.optional(),extensions:j(A(),OZ).optional()}),fQ=BZ.extend({protocolVersion:A(),capabilities:dQ,serverInfo:rQ,instructions:A().optional()}),pQ=zZ.extend({method:D(`notifications/initialized`),params:RZ.optional()}),mQ=e=>pQ.safeParse(e).success,hQ=LZ.extend({method:D(`ping`),params:PZ.optional()}),gQ=O({progress:P(),total:Xa(P()),message:Xa(A())}),_Q=O({...RZ.shape,...gQ.shape,progressToken:kZ}),vQ=zZ.extend({method:D(`notifications/progress`),params:_Q}),yQ=PZ.extend({cursor:AZ.optional()}),bQ=LZ.extend({params:yQ.optional()}),xQ=BZ.extend({nextCursor:AZ.optional()}),SQ=za([`working`,`input_required`,`completed`,`failed`,`cancelled`]),CQ=O({taskId:A(),status:SQ,ttl:k([P(),xa()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Xa(P()),statusMessage:Xa(A())}),wQ=BZ.extend({task:CQ}),TQ=RZ.merge(CQ),EQ=zZ.extend({method:D(`notifications/tasks/status`),params:TQ}),DQ=LZ.extend({method:D(`tasks/get`),params:PZ.extend({taskId:A()})}),OQ=BZ.merge(CQ),kQ=LZ.extend({method:D(`tasks/result`),params:PZ.extend({taskId:A()})});BZ.loose();const AQ=bQ.extend({method:D(`tasks/list`)}),jQ=xQ.extend({tasks:N(CQ)}),MQ=LZ.extend({method:D(`tasks/cancel`),params:PZ.extend({taskId:A()})}),NQ=BZ.merge(CQ),PQ=O({uri:A(),mimeType:Xa(A()),_meta:j(A(),E()).optional()}),FQ=PQ.extend({text:A()}),IQ=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),LQ=PQ.extend({blob:IQ}),RQ=za([`user`,`assistant`]),zQ=O({audience:N(RQ).optional(),priority:P().min(0).max(1).optional(),lastModified:vo({offset:!0}).optional()}),BQ=O({...nQ.shape,...tQ.shape,uri:A(),description:Xa(A()),mimeType:Xa(A()),size:Xa(P()),annotations:zQ.optional(),_meta:Xa(io({}))}),VQ=O({...nQ.shape,...tQ.shape,uriTemplate:A(),description:Xa(A()),mimeType:Xa(A()),annotations:zQ.optional(),_meta:Xa(io({}))}),HQ=bQ.extend({method:D(`resources/list`)}),UQ=xQ.extend({resources:N(BQ)}),WQ=bQ.extend({method:D(`resources/templates/list`)}),GQ=xQ.extend({resourceTemplates:N(VQ)}),KQ=PZ.extend({uri:A()}),qQ=KQ,JQ=LZ.extend({method:D(`resources/read`),params:qQ}),YQ=BZ.extend({contents:N(k([FQ,LQ]))}),XQ=zZ.extend({method:D(`notifications/resources/list_changed`),params:RZ.optional()}),ZQ=KQ,QQ=LZ.extend({method:D(`resources/subscribe`),params:ZQ}),$Q=KQ,e$=LZ.extend({method:D(`resources/unsubscribe`),params:$Q}),t$=RZ.extend({uri:A()}),n$=zZ.extend({method:D(`notifications/resources/updated`),params:t$}),r$=O({name:A(),description:Xa(A()),required:Xa(M())}),i$=O({...nQ.shape,...tQ.shape,description:Xa(A()),arguments:Xa(N(r$)),_meta:Xa(io({}))}),a$=bQ.extend({method:D(`prompts/list`)}),o$=xQ.extend({prompts:N(i$)}),s$=PZ.extend({name:A(),arguments:j(A(),A()).optional()}),c$=LZ.extend({method:D(`prompts/get`),params:s$}),l$=O({type:D(`text`),text:A(),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),u$=O({type:D(`image`),data:IQ,mimeType:A(),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),d$=O({type:D(`audio`),data:IQ,mimeType:A(),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),f$=O({type:D(`tool_use`),name:A(),id:A(),input:j(A(),E()),_meta:j(A(),E()).optional()}),p$=O({type:D(`resource`),resource:k([FQ,LQ]),annotations:zQ.optional(),_meta:j(A(),E()).optional()}),m$=k([l$,u$,d$,BQ.extend({type:D(`resource_link`)}),p$]),h$=O({role:RQ,content:m$}),g$=BZ.extend({description:A().optional(),messages:N(h$)}),_$=zZ.extend({method:D(`notifications/prompts/list_changed`),params:RZ.optional()}),v$=O({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),y$=O({taskSupport:za([`required`,`optional`,`forbidden`]).optional()}),b$=O({...nQ.shape,...tQ.shape,description:A().optional(),inputSchema:O({type:D(`object`),properties:j(A(),OZ).optional(),required:N(A()).optional()}).catchall(E()),outputSchema:O({type:D(`object`),properties:j(A(),OZ).optional(),required:N(A()).optional()}).catchall(E()).optional(),annotations:v$.optional(),execution:y$.optional(),_meta:j(A(),E()).optional()}),x$=bQ.extend({method:D(`tools/list`)}),S$=xQ.extend({tools:N(b$)}),C$=BZ.extend({content:N(m$).default([]),structuredContent:j(A(),E()).optional(),isError:M().optional()});C$.or(BZ.extend({toolResult:E()}));const w$=FZ.extend({name:A(),arguments:j(A(),E()).optional()}),T$=LZ.extend({method:D(`tools/call`),params:w$}),E$=zZ.extend({method:D(`notifications/tools/list_changed`),params:RZ.optional()});O({autoRefresh:M().default(!0),debounceMs:P().int().nonnegative().default(300)});const D$=za([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),O$=PZ.extend({level:D$}),k$=LZ.extend({method:D(`logging/setLevel`),params:O$}),A$=RZ.extend({level:D$,logger:A().optional(),data:E()}),j$=zZ.extend({method:D(`notifications/message`),params:A$}),M$=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()}),N$=O({mode:za([`auto`,`required`,`none`]).optional()}),P$=O({type:D(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(m$).default([]),structuredContent:O({}).loose().optional(),isError:M().optional(),_meta:j(A(),E()).optional()}),F$=eo(`type`,[l$,u$,d$]),I$=eo(`type`,[l$,u$,d$,f$,P$]),L$=O({role:RQ,content:k([I$,N(I$)]),_meta:j(A(),E()).optional()}),R$=FZ.extend({messages:N(L$),modelPreferences:M$.optional(),systemPrompt:A().optional(),includeContext:za([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(A()).optional(),metadata:OZ.optional(),tools:N(b$).optional(),toolChoice:N$.optional()}),z$=LZ.extend({method:D(`sampling/createMessage`),params:R$}),B$=BZ.extend({model:A(),stopReason:Xa(za([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:RQ,content:F$}),V$=BZ.extend({model:A(),stopReason:Xa(za([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:RQ,content:k([I$,N(I$)])}),H$=O({type:D(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),U$=O({type:D(`string`),title:A().optional(),description:A().optional(),minLength:P().optional(),maxLength:P().optional(),format:za([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),W$=O({type:za([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),G$=O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),K$=O({type:D(`string`),title:A().optional(),description:A().optional(),oneOf:N(O({const:A(),title:A()})),default:A().optional()}),q$=k([k([O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),k([G$,K$]),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()})])]),H$,U$,W$]),J$=k([FZ.extend({mode:D(`form`).optional(),message:A(),requestedSchema:O({type:D(`object`),properties:j(A(),q$),required:N(A()).optional()})}),FZ.extend({mode:D(`url`),message:A(),elicitationId:A(),url:A().url()})]),Y$=LZ.extend({method:D(`elicitation/create`),params:J$}),X$=RZ.extend({elicitationId:A()}),Z$=zZ.extend({method:D(`notifications/elicitation/complete`),params:X$}),Q$=BZ.extend({action:za([`accept`,`decline`,`cancel`]),content:co(e=>e===null?void 0:e,j(A(),k([A(),P(),M(),N(A())])).optional())}),$$=O({type:D(`ref/resource`),uri:A()}),e1=O({type:D(`ref/prompt`),name:A()}),t1=PZ.extend({ref:k([e1,$$]),argument:O({name:A(),value:A()}),context:O({arguments:j(A(),A()).optional()}).optional()}),n1=LZ.extend({method:D(`completion/complete`),params:t1});function r1(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function i1(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const a1=BZ.extend({completion:io({values:N(A()).max(100),total:Xa(P().int()),hasMore:Xa(M())})}),o1=O({uri:A().startsWith(`file://`),name:A().optional(),_meta:j(A(),E()).optional()}),s1=LZ.extend({method:D(`roots/list`),params:PZ.optional()}),c1=BZ.extend({roots:N(o1)}),l1=zZ.extend({method:D(`notifications/roots/list_changed`),params:RZ.optional()});k([hQ,lQ,n1,k$,c$,a$,HQ,WQ,JQ,QQ,e$,T$,x$,DQ,kQ,AQ,MQ]),k([eQ,vQ,pQ,l1,EQ]),k([QZ,B$,V$,Q$,c1,OQ,jQ,wQ]),k([hQ,z$,Y$,s1,DQ,kQ,AQ,MQ]),k([eQ,vQ,j$,n$,XQ,E$,_$,EQ,Z$]),k([QZ,fQ,a1,g$,o$,UQ,GQ,YQ,C$,S$,OQ,jQ,wQ]);var u1=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===JZ.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new d1(e.elicitations,n)}return new e(t,n,r)}},d1=class extends u1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(JZ.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function f1(e){return e===`completed`||e===`failed`||e===`cancelled`}const p1=Symbol(`Let zodToJsonSchema decide on which parser to use`),m1={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`},h1=e=>typeof e==`string`?{...m1,name:e}:{...m1,...e},g1=e=>{let t=h1(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 _1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function v1(e,t,n,r,i){e[t]=n,_1(e,t,r,i)}const y1=(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 b1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?y1(t,e.currentPath):t.join(`/`)}}function x1(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=d0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&v1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&v1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(v1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),v1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function S1(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?v1(n,`minimum`,r.value,r.message,t):v1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),v1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?v1(n,`maximum`,r.value,r.message,t):v1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),v1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:v1(n,`multipleOf`,r.value,r.message,t);break}return n}function C1(){return{type:`boolean`}}function w1(e,t){return d0(e.type._def,t)}const T1=(e,t)=>d0(e.innerType._def,t);function E1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>E1(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 D1(e,t)}}const D1=(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`:v1(n,`minimum`,r.value,r.message,t);break;case`max`:v1(n,`maximum`,r.value,r.message,t);break}return n};function O1(e,t){return{...d0(e.innerType._def,t),default:e.defaultValue()}}function k1(e,t){return t.effectStrategy===`input`?d0(e.schema._def,t):b1(t)}function A1(e){return{type:`string`,enum:Array.from(e.values)}}const j1=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function M1(e,t){let n=[d0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),d0(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(j1(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 N1(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 P1;const F1={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:()=>(P1===void 0&&(P1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),P1),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 I1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:v1(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`:B1(n,`email`,r.message,t);break;case`format:idn-email`:B1(n,`idn-email`,r.message,t);break;case`pattern:zod`:V1(n,F1.email,r.message,t);break}break;case`url`:B1(n,`uri`,r.message,t);break;case`uuid`:B1(n,`uuid`,r.message,t);break;case`regex`:V1(n,r.regex,r.message,t);break;case`cuid`:V1(n,F1.cuid,r.message,t);break;case`cuid2`:V1(n,F1.cuid2,r.message,t);break;case`startsWith`:V1(n,RegExp(`^${L1(r.value,t)}`),r.message,t);break;case`endsWith`:V1(n,RegExp(`${L1(r.value,t)}$`),r.message,t);break;case`datetime`:B1(n,`date-time`,r.message,t);break;case`date`:B1(n,`date`,r.message,t);break;case`time`:B1(n,`time`,r.message,t);break;case`duration`:B1(n,`duration`,r.message,t);break;case`length`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),v1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:V1(n,RegExp(L1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&B1(n,`ipv4`,r.message,t),r.version!==`v4`&&B1(n,`ipv6`,r.message,t);break;case`base64url`:V1(n,F1.base64url,r.message,t);break;case`jwt`:V1(n,F1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&V1(n,F1.ipv4Cidr,r.message,t),r.version!==`v4`&&V1(n,F1.ipv6Cidr,r.message,t);break;case`emoji`:V1(n,F1.emoji(),r.message,t);break;case`ulid`:V1(n,F1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:B1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:v1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:V1(n,F1.base64,r.message,t);break}break;case`nanoid`:V1(n,F1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function L1(e,t){return t.patternStrategy===`escape`?z1(e):e}const R1=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function z1(e){let t=``;for(let n=0;n<e.length;n++)R1.has(e[n])||(t+=`\\`),t+=e[n];return t}function B1(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}}})):v1(e,`format`,t,n,r)}function V1(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:H1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):v1(e,`pattern`,H1(t,r),n,r)}function H1(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
1229
1229
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
1230
1230
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function U1(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]:d0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??b1(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:d0(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}=I1(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}=w1(e.keyType._def,t);return{...n,propertyNames:i}}return n}function W1(e,t){return t.mapStrategy===`record`?U1(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[d0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||b1(t),d0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||b1(t)],minItems:2,maxItems:2}}}function G1(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 K1(e){return e.target===`openAi`?void 0:{not:b1({...e,currentPath:[...e.currentPath,`not`]})}}function q1(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const J1={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Y1(e,t){if(t.target===`openApi3`)return X1(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in J1&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=J1[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 X1(e,t)}const X1=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>d0(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 Z1(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:J1[e.innerType._def.typeName],nullable:!0}:{type:[J1[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=d0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=d0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Q1(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`,_1(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?v1(n,`minimum`,r.value,r.message,t):v1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),v1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?v1(n,`maximum`,r.value,r.message,t):v1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),v1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:v1(n,`multipleOf`,r.value,r.message,t);break}return n}function $1(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=t0(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=d0(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=e0(e,t);return o!==void 0&&(r.additionalProperties=o),r}function e0(e,t){if(e.catchall._def.typeName!==`ZodNever`)return d0(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 t0(e){try{return e.isOptional()}catch{return!0}}const n0=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return d0(e.innerType._def,t);let n=d0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:b1(t)},n]}:b1(t)},r0=(e,t)=>{if(t.pipeStrategy===`input`)return d0(e.in._def,t);if(t.pipeStrategy===`output`)return d0(e.out._def,t);let n=d0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,d0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function i0(e,t){return d0(e.type._def,t)}function a0(e,t){let n={type:`array`,uniqueItems:!0,items:d0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&v1(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&v1(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function o0(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>d0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:d0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>d0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function s0(e){return{not:b1(e)}}function c0(e){return b1(e)}const l0=(e,t)=>d0(e.innerType._def,t),u0=(e,t,n)=>{switch(t){case Z.ZodString:return I1(e,n);case Z.ZodNumber:return Q1(e,n);case Z.ZodObject:return $1(e,n);case Z.ZodBigInt:return S1(e,n);case Z.ZodBoolean:return C1();case Z.ZodDate:return E1(e,n);case Z.ZodUndefined:return s0(n);case Z.ZodNull:return q1(n);case Z.ZodArray:return x1(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return Y1(e,n);case Z.ZodIntersection:return M1(e,n);case Z.ZodTuple:return o0(e,n);case Z.ZodRecord:return U1(e,n);case Z.ZodLiteral:return N1(e,n);case Z.ZodEnum:return A1(e);case Z.ZodNativeEnum:return G1(e);case Z.ZodNullable:return Z1(e,n);case Z.ZodOptional:return n0(e,n);case Z.ZodMap:return W1(e,n);case Z.ZodSet:return a0(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return i0(e,n);case Z.ZodNaN:case Z.ZodNever:return K1(n);case Z.ZodEffects:return k1(e,n);case Z.ZodAny:return b1(n);case Z.ZodUnknown:return c0(n);case Z.ZodDefault:return O1(e,n);case Z.ZodBranded:return w1(e,n);case Z.ZodReadonly:return l0(e,n);case Z.ZodCatch:return T1(e,n);case Z.ZodPipeline:return r0(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>void 0)(t)}};function d0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==p1)return i}if(r&&!n){let e=f0(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=u0(e,e.typeName,t),o=typeof a==`function`?d0(a(),t):a;if(o&&p0(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const f0=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:y1(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`),b1(t)):t.$refStrategy===`seen`?b1(t):void 0}},p0=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),m0=(e,t)=>{let n=g1(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:d0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??b1(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=d0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??b1(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 h0(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function g0(e,t){return hZ(e)?Ya(e,{target:h0(t?.target),io:t?.pipeStrategy??`input`}):m0(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function _0(e){let t=yZ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=wZ(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function v0(e,t){let n=_Z(e,t);if(!n.success)throw n.error;return n.data}var y0=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(eQ,e=>{this._oncancel(e)}),this.setNotificationHandler(vQ,e=>{this._onprogress(e)}),this.setRequestHandler(hQ,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(DQ,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new u1(JZ.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(kQ,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 u1(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 u1(JZ.InvalidParams,`Task not found: ${r}`);if(!f1(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(f1(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[DZ]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(AQ,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 u1(JZ.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(MQ,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new u1(JZ.InvalidParams,`Task not found: ${e.params.taskId}`);if(f1(n.status))throw new u1(JZ.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 u1(JZ.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof u1?e:new u1(JZ.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),u1.fromError(JZ.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),qZ(e)||XZ(e)?this._onresponse(e):UZ(e)?this._onrequest(e,t):GZ(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=u1.fromError(JZ.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?.[DZ]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:JZ.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=IZ(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 u1(JZ.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:JZ.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),qZ(e)?n(e):n(new u1(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(qZ(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),qZ(e)?r(e):r(u1.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 u1?e:new u1(JZ.InternalError,String(e))}}return}let i;try{let r=await this.request(e,wQ,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new u1(JZ.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},f1(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new u1(JZ.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new u1(JZ.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 u1?e:new u1(JZ.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||{},[DZ]: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 u1?e:new u1(JZ.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=_Z(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(u1.fromError(JZ.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},OQ,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},jQ,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},NQ,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||{},[DZ]: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||{},[DZ]: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||{},[DZ]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=_0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=v0(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=_0(e);this._notificationHandlers.set(n,n=>{let r=v0(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`&&UZ(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new u1(JZ.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 u1(JZ.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new u1(JZ.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 u1(JZ.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=EQ.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),f1(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 u1(JZ.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(f1(a.status))throw new u1(JZ.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=EQ.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),f1(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function b0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x0(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];b0(a)&&b0(i)?n[r]={...a,...i}:n[r]=i}return n}var S0=t(Dt(),1),C0=t(qe(),1);function w0(){let e=new S0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,C0.default)(e),e}var T0=class{constructor(e){this._ajv=e??w0()}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)}}},E0=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},B$,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},Q$,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 D0(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 O0(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 k0=class extends y0{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(D$.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 T0,this.setRequestHandler(lQ,e=>this._oninitialize(e)),this.setNotificationHandler(pQ,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(k$,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=D$.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new E0(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=x0(this._capabilities,e)}setRequestHandler(e,t){let n=yZ(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(hZ(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=_Z(T$,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new u1(JZ.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=_Z(wQ,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new u1(JZ.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=_Z(C$,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new u1(JZ.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){O0(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&D0(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:EZ.includes(t)?t:TZ,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`},QZ)}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},V$,t):this.request({method:`sampling/createMessage`,params:e},B$,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},Q$,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},Q$,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new u1(JZ.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof u1?e:new u1(JZ.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},c1,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 A0=Symbol.for(`mcp.completable`);function j0(e){return!!e&&typeof e==`object`&&A0 in e}function M0(e){return e[A0]?.complete}var N0;(function(e){e.Completable=`McpCompletable`})(N0||={});const P0=/^[A-Za-z0-9._-]{1,128}$/;function F0(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`),!P0.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 I0(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 L0(e){let t=F0(e);return I0(e,t.warnings),t.isValid}var R0=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)}},z0=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 k0(e,t)}get experimental(){return this._experimental||={tasks:new R0(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(K0(x$)),this.server.assertCanSetRequestHandler(K0(T$)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(x$,()=>({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=bZ(t.inputSchema);return e?g0(e,{strictUnions:!0,pipeStrategy:`input`}):B0})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=bZ(t.outputSchema);e&&(n.outputSchema=g0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(T$,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new u1(JZ.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new u1(JZ.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 u1(JZ.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new u1(JZ.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 u1&&e.code===JZ.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 vZ(bZ(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=xZ(`error`in r?r.error:`Unknown error`);throw new u1(JZ.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 u1(JZ.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await vZ(bZ(e.outputSchema),t.structuredContent);if(!r.success){let e=xZ(`error`in r?r.error:`Unknown error`);throw new u1(JZ.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 u1(JZ.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(K0(n1)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(n1,async e=>{switch(e.params.ref.type){case`ref/prompt`:return r1(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return i1(e),this.handleResourceCompletion(e,e.params.ref);default:throw new u1(JZ.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new u1(JZ.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new u1(JZ.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return J0;let r=yZ(n.argsSchema)?.[e.params.argument.name];if(!j0(r))return J0;let i=M0(r);return i?q0(await i(e.params.argument.value,e.params.context)):J0}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 J0;throw new u1(JZ.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?q0(await r(e.params.argument.value,e.params.context)):J0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(K0(HQ)),this.server.assertCanSetRequestHandler(K0(WQ)),this.server.assertCanSetRequestHandler(K0(JQ)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(HQ,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(WQ,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(JQ,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new u1(JZ.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 u1(JZ.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(K0(a$)),this.server.assertCanSetRequestHandler(K0(c$)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(a$,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?G0(t.argsSchema):void 0}))})),this.server.setRequestHandler(c$,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new u1(JZ.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new u1(JZ.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await vZ(bZ(n.argsSchema),e.params.arguments);if(!r.success){let t=xZ(`error`in r?r.error:`Unknown error`);throw new u1(JZ.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:gZ(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=gZ(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=>j0(e instanceof Ka?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){L0(e);let l={title:t,description:n,inputSchema:W0(r),outputSchema:W0(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`&&L0(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=gZ(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=gZ(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(U0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!U0(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 B0={type:`object`,properties:{}};function V0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function H0(e){return`_def`in e||`_zod`in e||V0(e)}function U0(e){return typeof e!=`object`||!e||H0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(V0)}function W0(e){if(e){if(U0(e))return gZ(e);if(!H0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function G0(e){let t=yZ(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:SZ(t),required:!CZ(t)})):[]}function K0(e){let t=yZ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=wZ(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function q0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const J0={completion:{values:[],hasMore:!1}};var Y0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},X0=e=>e instanceof Y0?e:new Y0(e.message,{cause:e}),Z0=global.Request,Q0=class extends Z0{constructor(e,t){typeof e==`object`&&n2 in e&&(e=e[n2]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},$0=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)},e2=Symbol(`wrapBodyStream`),t2=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Q0(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[e2]){let e;a.body=new ReadableStream({async pull(t){try{e||=Eu.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Eu.toWeb(r);return new Q0(t,a)},n2=Symbol(`getRequestCache`),r2=Symbol(`requestCache`),i2=Symbol(`incomingKey`),a2=Symbol(`urlKey`),o2=Symbol(`headersKey`),s2=Symbol(`abortControllerKey`),c2={get method(){return this[i2].method||`GET`},get url(){return this[a2]},get headers(){return this[o2]||=$0(this[i2])},[Symbol(`getAbortController`)](){return this[n2](),this[s2]},[n2](){return this[s2]||=new AbortController,this[r2]||=t2(this.method,this[a2],this.headers,this[i2],this[s2])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(c2,e,{get(){return this[n2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(c2,e,{value:function(){return this[n2]()[e]()}})}),Object.defineProperty(c2,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[r2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(c2,Q0.prototype);var l2=(e,t)=>{let n=Object.create(c2);n[i2]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof ju)throw new Y0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[a2]=new URL(r).href}catch(e){throw new Y0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof ju?e.authority:e.headers.host)||t;if(!i)throw new Y0(`Missing host header`);let a;if(e instanceof ju){if(a=e.scheme,!(a===`http`||a===`https`))throw new Y0(`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 Y0(`Invalid host header`);return n[a2]=o.href,n},u2=Symbol(`responseCache`),d2=Symbol(`getResponseCache`),f2=Symbol(`cache`),p2=global.Response,m2=class e{#e;#t;[d2](){return delete this[f2],this[u2]||=new p2(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[u2];if(e){this.#t=e,this[d2]();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[f2]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[f2];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[d2]().headers}get status(){return this[f2]?.[0]??this[d2]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(m2.prototype,e,{get(){return this[d2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(m2.prototype,e,{value:function(){return this[d2]()[e]()}})}),Object.defineProperty(m2.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[u2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(m2,p2),Object.setPrototypeOf(m2.prototype,p2.prototype);async function h2(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function g2(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 _2(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:g2(e.getReader(),t)}var v2=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},y2=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Tu);var b2=Symbol(`outgoingEnded`),x2=Symbol(`incomingDraining`),S2=500,C2=64*1024*1024,w2=e=>{let t=e;if(e.destroyed||t[x2])return;if(t[x2]=!0,e instanceof ju){try{e.stream?.close?.(Tee.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,S2);a.unref?.();let o=e=>{n+=e.length,n>C2&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},T2=()=>new Response(null,{status:400}),E2=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),D2=(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))},O2=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},k2=async(e,t)=>{let[n,r,i]=e[f2],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=v2(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=v2(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())):(O2(t),await _2(r,t)?.catch(e=>D2(e,t))),t[b2]?.()},A2=e=>typeof e.then==`function`,Ese=async(e,t,n={})=>{if(A2(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(E2);if(f2 in e)return k2(e,t);let r=v2(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 h2(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&&O2(t),await g2(n,t,o))}else r[y2]||(t.writeHead(e.status,r),t.end());t[b2]?.()},j2=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Q0&&(Object.defineProperty(global,`Request`,{value:Q0}),Object.defineProperty(global,`Response`,{value:m2})),async(r,i)=>{let a,o;try{o=l2(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[e2]=!0,r.on(`end`,()=>{s=!0}),r instanceof ju&&(i[b2]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{w2(r)})})}),i.on(`finish`,()=>{s||w2(r)})),i.on(`close`,()=>{o[s2]&&(r.errored?o[s2].abort(r.errored.toString()):i.writableFinished||o[s2].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{w2(r)})})}),a=e(o,{incoming:r,outgoing:i}),f2 in a)return k2(a,i)}catch(e){if(a)return D2(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:X0(e)),!a)return}else a=o?E2(e):T2()}try{return await Ese(a,i,t)}catch(e){return D2(e,i)}}},Dse=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:i,id:null}),{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e)){this.onerror?.(Error(`Failed replay events`));try{i.close()}catch{}}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
|
|
1231
1231
|
`;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>ZZ.parse(e)):[ZZ.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(uQ);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(UZ)){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=>uQ(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)UZ(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)UZ(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;UZ(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&&!EZ.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${EZ.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${EZ.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((qZ(e)||XZ(e))&&(n=e.id),n===void 0){if(qZ(e)||XZ(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(qZ(e)||XZ(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)}}}},Ose=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Dse(e),this._requestListener=j2(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 j2(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 M2=`x-ok-connection-id`;function N2(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 P2(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||!kse(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=no(i.error);throw new u1(JZ.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function kse(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const F2=2e3,I2=2e3,Ase=[/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 L2(e){return Ase.some(t=>t.test(e))}function jse(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 El(e)?e:null}catch{return null}}function Mse(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&&El(a)?a:null}function Nse(e){let t=[];for(let n of e.split(`
|
|
@@ -3270,6 +3270,6 @@ native-divergence-injected
|
|
|
3270
3270
|
`).split(`
|
|
3271
3271
|
`),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=eve(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(SM(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(!UC(e))try{let{frontmatter:n,body:r}=ia(t),i=Ze(n?Lt(n):``),a=tve(r),o=new Set([...i,...a]),s=new Set;for(let e of o)for(let t of Ri(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(UC(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=$r(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(()=>xB(`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([pu(t),uu(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 uu(e,`utf-8`))}catch(e){return v9.warn({err:e},`Failed to load tag snapshot; falling back to full rebuild`),!1}if(!$_e(t))return v9.warn({},`Tag snapshot failed validation; falling back to full rebuild`),!1;this.state=b9(),this.fileMeta=new Map(Object.entries(t.files));for(let[e,n]of Object.entries(t.docs)){if(UC(e))continue;let t=new Set(n),r=new Set;for(let e of t)for(let t of Ri(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 Ro(I(e),{recursive:!0}),await Fo(e,JSON.stringify(t,null,2),`utf-8`)}reconcileWithDisk(){return this.enqueue(()=>xB(`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 pu(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 uu(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 du(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=Pj(R(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!KC(r.name))continue;let i=Pj(R(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:JC(i),filePath:n})}}};let S9=!1;function C9(){if(S9)return;let e=Oee;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 nve=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function rve(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(D8).join(` `)} auth git-credential`]}function ive(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=xl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],zP({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(`
|
|
3272
3272
|
`)){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(!Lj(a,t))continue;let s=zV(a,t);i.has(s)||B(a)&&i.set(s,o)}return i}function w9(e){C9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,authStreamHeartbeatMs:g,skipStateManifestCheck:_=!1,singleDocRelPath:v,ephemeral:y=!1}=e,b=F(`server`),x=new g7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),ee=e=>x.deleteReconciledBase(e),te=e=>x.switchReconciledBaseScope(e),ne=e=>x.setBatchInProgress(e),re=()=>x.isBatchInProgress();function ie(){let e=ko({absPath:Mo(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=po(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}b.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ae(){let e=ko({absPath:Mo(`project-local`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=Ga(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||b.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let r=ko({absPath:Mo(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});return r.valid||b.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:Ma(r.value.autoSync?.default)??`off`,source:`committed-default`}}function oe(){let e=ko({absPath:Mo(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?ut(e):Lr}function se(){return ko({absPath:Mo(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ce(){return PP(n,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function le(){let e=ko({absPath:Mo(`project-local`,n,u),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function ue(e){return`${wP(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function de(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=ae();t=n.mode,_t?.setMode(n.mode,n.source).catch(t=>{b.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=ce();Fe.applyConfig({enabled:n.enabled,providerFingerprint:ue(n)}),e===`__config__/project`&&ke?.signal(`lint-config`),b.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}rs();let fe=Cu(),pe=SM(n),me=new Cd({localDir:pe,log:F(`acp-registry`)}),he=new hd(pe,F(`acp-permissions`));if(Ns(pe,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!_)try{i9({lockDir:pe,shadowRepoDir:Vu(n)})}catch(e){throw Cs(pe),e}let ge=wi(),_e=(e,t)=>ge.resolveEmbed(e,t),ve=(e,n)=>{let r=ge.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=z(t,r);if(!Fj(i,z(t)))return null;try{let e=Xl(i);return e.isFile()?e.size:null}catch{return null}},ye,be,xe,Se,Ce,we,Te,Ee,De,Oe,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=ce(),Fe=new Tae({loadEmbedder:e.embedderLoader??(()=>{let t=ce();return dae({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:L(SM(n),`embeddings`),enabled:Pe.enabled,providerFingerprint:ue(Pe)}),Ie=null,Le=new Set,Re=!1,ze=[],Be,Ve,He,Ue=new Promise((e,t)=>{Ve=e,He=t});function We(e){ke?.signal(e)}let Ge=null;function Ke(){Ge!==null&&clearTimeout(Ge),Ge=setTimeout(()=>{Ge=null,be.saveToDisk().catch(e=>{F(`backlinks`).warn({err:e},`Failed to persist debounced cache`)}),xe.saveToDisk().catch(e=>{F(`tag-index`).warn({err:e},`Failed to persist debounced tag snapshot`)})},2e3)}let qe=null,Je=!1,Ye=()=>{try{Y7(n,Xe.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Xe=new d_e(void 0,{onEviction:()=>Vre(),onSizeChange:e=>Hre(e),onMutate:()=>{!Je||qe!==null||(qe=setTimeout(()=>{qe=null,Ye()},2e3))}});for(let[e,r]of m_e(n))HC(e)||nY(e)&&([`.md`,`.mdx`].some(n=>{let r=z(t,`${e}${n}`);return Fj(r,z(t))&&B(r)})||Xe.restore(e,r));Je=!0;let Ze=(e,t)=>{HC(e)||Xe.setRenamed(e,t)},Qe=e=>{if(!HC(e)){if(Xe.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Xe.setDeleted(e)}},$e=e=>{HC(e)||Xe.delete(e)};try{ye=aI({projectDir:n,contentDir:t,singleDocRelPath:v,onAfterRebuild:()=>{be.rebuildFromDisk(S()).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),xe.init().catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),cH(ht).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?F(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):F(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),be=new ZB({projectDir:n,contentDir:t,contentFilter:ye}),xe=new x9({projectDir:n,contentDir:t,contentFilter:ye}),(async()=>{await xe.loadFromDisk()?await xe.reconcileWithDisk():await xe.init()})().catch(e=>{F(`server-factory`).warn({err:e},`[server-factory] tag-index warm boot failed; continuing with empty index`)}),Se={current:f},Ce=s?Qge({getShadow:()=>Se.current??null,getCurrentBranch:()=>gt?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Bu(n)??void 0,isWriterLive:e=>{if(!je&&!De)return F(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(je?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=H7({contentDir:t,projectDir:n,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:Se,ephemeral:y,contentRoot:p,backlinkIndex:be,configHomedirOverride:u,getCurrentBranch:()=>gt?.getLastKnownBranch()??null,resolveEmbed:_e,resolveSize:ve,getPrincipal:()=>Ie,onAgentCommit:()=>ke?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{ke?.emitDiskAck(e,t),!HC(e)&&cM(r,n)&&(Me?.(),We(`files`))},onConfigRejected:(e,t)=>ke?.emitConfigValidationRejected(e,t),onConfigPersisted:de,isRecentlyRemoved:e=>Xe.has(e),mdManager:e.mdManager,getLossRing:()=>Te,durabilityState:x}),Ee=new pge({quiet:r,debounce:a,maxDebounce:o,extensions:[we.extension]});let i=Ee;ze.push(dE(()=>i.documents.size),fE(()=>we.getQueueDepths()),mE(()=>{let e=0;for(let t of i.documents.values())e+=t.directConnectionsCount;return{websocket:i.getConnectionsCount()-e,direct:e}})),gE(),y||(Ne=l_e({getLoadedDocuments:()=>i.documents,forceStore:(e,t)=>we.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=Ij(e,t),r,i;try{r=Kl(n),i=Xl(r).size}catch(t){let n=Is(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new W7(`symlink cycle at content path: ${e}`):t}if(!Lj(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(Is(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let m=Ee.shouldUnloadDocument.bind(Ee);Ee.shouldUnloadDocument=e=>{if(Le.has(e)||Re&&m(e))return!0;let t=e.name;return HC(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:m(e)},Be=async e=>{Le.add(e);try{await Ee.unloadDocument(e)}finally{Le.delete(e)}},ke=new GC(Ee),Ae=new qO(Ee),je=new YO(Ee),De=new lD(Ee);let _=De;ze.push(hE(()=>({active:_.liveSessionCount,limit:_.sessionLimit})));let w=b7({backlinkIndex:be,tagIndex:xe,signalChannel:We});Ee.configuration.extensions.push(w),Ee.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=mY(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==fe)throw new pY(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${fe}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new pY(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(Ie&&n.principalId===Ie.id?o.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Ie.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),Ee.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!zC(t.documentName)&&!BC(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!Sj(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&Oj(a,e.remotePublicHost);if(!Cj(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let ee=z(t);function te(e){if(!nY(e))return null;let t=z(ee,ew(e));return Fj(t,ee)?t:null}Ee.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await f_e(e.documentName,{recentlyRemovedDocs:Xe,resolveFilePath:te,fileExists:B})}}),Ee.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=mY(e.token);Age(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ee.documents.get(e)})}}),Ee.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new P5(e.update);if(t.readVarString(),t.readVarUint()===G5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Gn} rejected — server-only channel`)}});let ne=iY({hocuspocus:Ee,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:De,contentDir:t,contentFilter:ye,serverInstanceId:fe,getFileIndex:()=>ht?ht.getFileIndex():new Map,getAttachmentFolderPath:ie,getAllFilesIndex:()=>ht?ht.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ht?.getFileIndexGeneration()??0,mutateFileIndex:e=>ht?.mutateFileIndex(e),getFolderIndex:()=>ht?ht.getFolderIndex():new Map,getAliasMap:()=>ht?ht.getAliasMap():new Map,getFolderAliasIndex:()=>ht?ht.getFolderAliasIndex():new Map,rescanFiles:()=>ht?.rescanFromDisk(),enableTestRoutes:d,shadowRef:Se,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),getCurrentBranch:()=>gt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ke?.getLatestDiskAckSVsAsBase64()??{},contentRoot:p,backlinkIndex:be,tagIndex:xe,signalChannel:We,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>_t,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:n,resolveEmbed:_e,getBridgeLossReporter:()=>Oe,getPrincipal:()=>Ie,acpRegistry:me,loadAcpCustomAgents:()=>wd(pe,F(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Be,ready:Ue,recentlyRemovedDocs:Xe,serializeDoc:it,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Fe,getSemanticSimilarityFloor:()=>ce().similarityFloor,getLinterBaseConfig:()=>oe(),getLinksValidationSetting:()=>se(),getLinkPreviewsEnabled:le,embeddingsSecretsFile:jP(u),readSemanticProviderConfig:ce,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Me=e}});Ee.configuration.extensions.push(ne);let re=ko({absPath:Mo(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),ae=re.value.bridge.deferGuard.enabled,ue=re.value.bridge.fixedPoint.enabled,he=re.value.bridge.preDrain.enabled;Te=re.value.lossCapture.enabled?new Ane({projectDir:n,maxBytes:re.value.lossCapture.maxBytes}):void 0,re.value.bridge.lossDetector.enabled&&(Oe=PC({shadow:()=>Se.current,ring:Te,getBranch:()=>gt?.getLastKnownBranch()??`main`,contentRoot:p??``}),De.attachBridgeLossReporter(Oe)),Ee.configuration.extensions.push(Z7({mdManager:Eo,schema:To,shadowRef:Se,contentRoot:p,getCurrentBranch:()=>gt?.getLastKnownBranch()??null,resolveEmbed:_e,resolveSize:ve,deferGuardEnabled:ae,lossDetectorEnabled:re.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:ue,preDrainEnabled:he,lossRing:Te})),Ee.configuration.extensions.push(Q_e()),Ee.configuration.extensions.push(kge({getSyncEngine:()=>_t,projectDir:n,contentDir:t}))}catch(e){for(let e of ze.splice(0))e();throw Ne?.dispose(),Ne=null,Cs(pe),e}let et=null,tt=new Map,nt=[];function rt(e,t){let n=z(e,`rescue`),r=z(n,ew(t));return Fj(r,n)?r:null}function it(e){let t=Ee.documents.get(e);return t?_V(t):null}let at=(e,t)=>mV(x,Ee,e,t,_e,ve,Oe);function ot(e){if(!hw(e)||_t?.getConflicts().some(r=>h7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let st=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Ee.documents){if(HC(n))continue;let r=Ee.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{oV(r,i,_e,n)},aV)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},ct=null,T=e=>{e&&(ct===null&&(ct=new Set,setImmediate(()=>{let e=ct;if(ct=null,e)try{for(let t of e)st(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),ct.add(e))};function lt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return xV(e)}}async function dt(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),be.updateDocumentFromMarkdown(e.docName,e.content),Ke(),xe.updateDocumentFromMarkdown(e.docName,e.content),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),$e(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=Ee.documents.get(t);if(!r){be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`);return}let i=C(t)??``,a=it(t)??i,o=uV({docName:t,base:i,ours:a,theirs:n}),s=OV(i).slice(0,6),c=OV(a).slice(0,6),l=OV(n).slice(0,6);switch(b.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:ot(r),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`);break;case`clean`:try{at(t,o.newContent),w(t,o.newContent),xS(),ot(r),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`)}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),ot(r)}break;case`merged`:try{at(t,o.newContent),w(t,n),xS(),ot(r),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`)}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),ot(r)}break;case`conflicts`:try{at(t,o.newContent),w(t,o.newContent),xS(),SS(),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`)}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{SS();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Ee.documents.get(t);if(!n){be.deleteDocument(t),Ke(),xe.deleteDocument(t),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),Qe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=it(t)??``,a=i!==r;if(a&&Se.current){let e=Se.current,n=gt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{gC(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{wS(),b.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{b.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee(t),be.deleteDocument(t),Ke(),xe.deleteDocument(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Ee.closeConnections(t),await Be(n),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),Qe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=Ee.documents.get(t);if(ee(t),w(n,r),be.renameDocument(t,n,r),Ke(),xe.renameDocument(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}b.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),Ze(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=Ee.documents.get(t);if(!n)return;let r=it(t);r===null?b.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),b.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ge.add(e.relativePath),We(`files`),T(Cl(e.relativePath));break;case`asset-delete`:ge.remove(e.relativePath),We(`files`),T(Cl(e.relativePath));break;case`folder-create`:case`folder-delete`:We(`files`);break;case`file-create`:case`file-update`:case`file-delete`:We(`files`);break;default:xV(e)}}catch(t){let n=lt(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let ft=[];async function pt(e){if(re()){ft.push(e);return}await dt(e)}async function mt(){let e=ft.splice(0,ft.length);for(let t of e)await dt(t)}let ht=null,gt=null,_t=null,vt=null;async function yt(e){if(Ee.documents.size===0)return;let t=!1,n=new Promise(e=>{Ee.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Ee.documents.keys());Ee.closeConnections(),Ee.flushPendingStores();for(let e of Ee.documents.values())e.getConnectionsCount()===0&&Ee.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(Ee.documents.keys()),i=[],o=[];if(Se.current){for(let e of n)if(!HC(e))try{let t=it(e);if(t===null){b.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=rt(Se.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:Se.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}zl(I(n),{recursive:!0}),Ql(n,t,`utf-8`),wS(),i.push(e),b.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),b.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else b.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function bt(){return vt||(vt=(async()=>{let e=Date.now(),t=[];Re=!0;for(let e of ze.splice(0))e();try{await Ne?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Ne=null;try{Ps(pe)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}if(Ge!==null&&(clearTimeout(Ge),Ge=null),xe.close(),qe!==null&&(clearTimeout(qe),qe=null),Je)try{Y7(n,Xe.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([Ue.then(()=>`completed`,e=>(b.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&b.warn({},`[server] init did not complete within 5s during shutdown`);let a=Ee.documents.size;Ce?.destroy();try{try{try{gt&&=(await gt.unsubscribe(),null),ht&&=(await ht.unsubscribe(),null);for(let{docName:e,cleanup:t}of nt)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}nt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ke?.destroy(),je?.destroy(),et&&=(await et.disconnect(),null);for(let[e,t]of tt)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}tt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await De.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await tT()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await yt(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await we.flushPendingGitCommit(),await we.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{_t&&=(await _t.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(Se.current){try{let e=(await gs({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Ql(z(Se.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{ZS(Se.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?b.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):b.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Cs(pe,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await ns()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),vt)}let xt=[];async function St(){try{Ie=await G7(n),b.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!Se.current)try{Se.current=await XS(n),b.info({gitDir:Se.current.gitDir},`[server] history repo initialized at ${Se.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),xt.push(`shadow-repo`)}if(Se.current){let e=null;try{e=hG(Se.current.gitDir),RG(Se.current.gitDir,e),bG(Se.current.gitDir,e),b.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){b.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([zG(Se.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){b.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await Ce?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(Se.current)try{await qS(Se.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){b.warn({},`[server] history repo appears corrupted — reinitializing`);try{Se.current=await XS(n)}catch(e){b.error({err:e},`[server] history repo reinit failed`),Se.current=void 0,xt.includes(`shadow-repo`)||xt.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(Se.current)try{let e=z(Se.current.gitDir,`last-known-head`),t=null;try{t=V(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await gs({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await gs({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}b.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await fC(Se.current,p??``,t,r,e),CS()}catch(e){b.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else b.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{Ql(e,r,`utf-8`)}catch(e){b.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){b.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=tG(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;b.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){b.error({err:e},`[server] managed rename recovery failed`),xt.push(`managed-rename-recovery`)}try{let e=gB(n);(e.deleted>0||e.errors>0)&&b.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){b.error({err:e},`[server] upload-tempfile sweep failed`),xt.push(`upload-tempfile-sweep`)}try{et=await Ee.openDirectConnection(Gn),ke?.emitServerInfo(fe,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),xt.push(`cc1-push`)}let r=y?[]:i;for(let e of r)try{let t=await Ee.openDirectConnection(e);tt.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),xt.push(`config-doc:${e}`)}let a=new Map([[Hi,Mo(`project`,n)],[ri,Mo(`project-local`,n)],[Oi,Mo(`user`,n,u)]]);for(let e of r){let t=a.get(e);if(t)try{b.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await yge(t,t=>{let n=Ee.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=m7(n??null,e,t,we.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),de(e)});nt.push({docName:e,cleanup:n}),b.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){b.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),xt.push(`config-file-watcher:${e}`)}}if(!y){let e=(e,t)=>{let n=MW(e,we.managedArtifactCtx);if(!n)return;let r=FW(Ee.documents.get(n)??null,n,t,we.managedArtifactCtx);b.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Yn(n)&&be.ingestGlobalSkillBundles(OW(we.managedArtifactCtx),S()).then(()=>{We(`backlinks`),We(`graph`)}).catch(e=>{b.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=OW(we.managedArtifactCtx),n=await M7(t,e);nt.push({docName:`__skill-files__`,cleanup:n}),b.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),xt.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of wN(n).templates)t.add(e.source_folder)}catch(e){b.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?z(n,e,`.ok`,`templates`):z(n,`.ok`,`templates`)),i=await M7(r,e,e_e);nt.push({docName:`__template-files__`,cleanup:i}),b.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] templates failed to start`),xt.push(`managed-artifact-watcher:templates`)}}try{let e=z(t,`.okignore`),r=z(n,`.gitignore`),i=null;try{let e=xl(`git`,[`rev-parse`,`--git-common-dir`],zP({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=L(z(n,e.stdout.trim()),`info`,`exclude`);B(I(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=b;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await bge(a,(t,r)=>{(async()=>{if(t===e)try{let e=m7(Ee.documents.get(`__config__/okignore`)??null,er,r,we.configPersistenceCtx);o.info({docName:er,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:R(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ye.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:R(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ke?.signal(`files`);else{let e=R(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ke?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:R(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(nt.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){b.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),xt.push(`ignore-files-watcher`)}let o=y7(n).branch??`main`;te(o),be.switchBranch(o);let s=performance.now();try{await Po(`ok.boot.indexes`,void 0,async()=>{let e=S();try{if(await be.loadFromDisk(e)){let t=await be.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&b.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let n=0;for(let e of t.deletedDocNames)HC(e)||Xe.peek(e)?.kind!==`renamed`&&(Xe.setDeleted(e),n++);n>0&&b.info({count:n},`[removal-guard] tombstoned docs deleted while the server was down`)}else await be.rebuildFromDisk(e);try{await be.ingestGlobalSkillBundles(OW(we.managedArtifactCtx),e)}catch(t){b.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}be.saveToDisk().catch(t=>{F(`backlinks`).warn({branch:e,err:t},`Failed to persist startup cache for ${e}`)})}catch(t){b.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let n=performance.now();ht=await Po(`ok.boot.seed-walk`,void 0,async()=>sH(t,pt,ye)),nV(`seedWalkMs`,Math.round(performance.now()-n));{let e=z(t),n=0;for(let[t]of Xe.entries()){if(!nY(t))continue;let r=z(e,`${t}${$C(t)}`);Fj(r,e)&&B(r)&&(Xe.delete(t),n++)}n>0&&b.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{let e=await xe.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&b.info(e,`[tag-index] startup reconcile: offline changes applied`),xe.saveToDisk().catch(e=>{F(`tag-index`).warn({err:e},`Failed to persist startup tag snapshot`)})}catch(e){b.error({err:e},`[tag-index] startup reconcile failed; tag index updates incrementally via watcher events`),xt.push(`tag-index`)}let r=0;try{v===void 0?await sY({contentDir:t,contentFilter:ye,basenameIndex:ge,onSkip:(e,t,n)=>{r++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):oY({contentDir:t,basenameIndex:ge,onSkip:(e,t,n)=>{r++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),r>0&&(b.warn({count:r},`[basename-index] startup seed completed with ${r} skipped entries — embeds under inaccessible subtrees will not resolve`),xt.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),xt.push(`basename-index`)}})}catch(e){b.error({err:e},`[server] disk bridge watcher failed to start`),xt.push(`file-watcher`)}finally{nV(`indexesMs`,Math.round(performance.now()-s)),ht&&rV(`fileCount`,ht.getFileIndex().size)}try{gt=await Fge(n,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),Rne(),Ee.flushPendingStores(),await we.flushPendingGitCommit(),ne(!0),Se.current){let e=S(),t=y7(n).branch??e,r=[];for(let[e,t]of Ee.documents){if(HC(e))continue;let n=null;if(t.transact(()=>{n=it(e)},nve),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await CC(Se.current,e,uC.id,r,t);n&&(Vne(),b.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){b.error({err:e},`[shadow] park failed`)}}},async e=>{let r=ft.length,i=e.newBranch??`main`;if(b.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(ne(!1),await mt(),e.headMoved&&e.newHead){let r=ive(n,z(t),e.oldHead,e.newHead);if(r.size>0){Rie(r.keys());for(let[e,t]of r)sP(e,Nee(t.email),t.name,t.email,rd(e));await we.flushContributors()}}if(await we.flushDeferredStores(`within-branch`),_t!==null)try{await _t.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Bne(),ft.splice(0,ft.length),te(i),Ge!==null&&(clearTimeout(Ge),Ge=null),be.switchBranch(i),ye.rebuildDirCount();try{let e=0;ge.clear(),await sY({contentDir:t,contentFilter:ye,basenameIndex:ge,onSkip:(t,n,r)=>{e++,b.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(b.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),xt.includes(`basename-index-partial`)||xt.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of Ee.documents)if(!HC(e))try{let r=Ij(e,t);if(!B(r)){let t=C(e)??``,r=it(e)??``;if(r!==t&&Se.current){let t=Se.current;queueMicrotask(()=>{gC(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{wS(),b.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{b.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),b.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=V(r,`utf-8`);at(e,a),w(e,a),b.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){b.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}b.info({branch:i,docCount:Ee.documents.size},`[branch-switch] loaded branch ${i} (${Ee.documents.size} docs)`);try{if(await be.loadFromDisk(i)){let e=await be.reconcileWithDisk(i);(e.added>0||e.updated>0||e.deleted>0)&&b.info(e,`[backlinks] branch-switch reconcile for ${i}`)}else await be.rebuildFromDisk(i);try{await be.ingestGlobalSkillBundles(OW(we.managedArtifactCtx),i)}catch(e){b.warn({err:e,branch:i},`[backlinks] branch-switch global skill bundle ingest failed`)}be.saveToDisk(i).catch(e=>{F(`backlinks`).warn({branch:i,err:e},`Failed to persist branch cache for ${i}`)})}catch(e){b.error({err:e,branch:i},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}try{let e=await xe.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&b.info(e,`[tag-index] branch-switch reconcile for ${i}`)}catch(e){b.warn({err:e,branch:i},`[tag-index] branch-switch reconcile failed; falling back to full rebuild`),await xe.init()}if(xe.saveToDisk().catch(e=>{F(`tag-index`).warn({branch:i,err:e},`Failed to persist tag snapshot after branch switch`)}),Se.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Ee.documents)if(!HC(t))try{let n=await TC(Se.current,i,uC.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=uV({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:at(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:at(t,a.newContent),w(t,a.newContent),SS(),e++;{let e=Ee.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){b.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&b.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&Se.current)try{let t=qS(Se.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await HS(Se.current).withMutator(async()=>{for(let e of n.split(`
|
|
3273
|
-
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}ne(!1),await we.flushDeferredStores(`discard-stale`),ke?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&Se.current&&r>0){let t=p??`.`;try{let n=await fC(Se.current,t,e.oldHead,e.newHead,i);CS(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),xt.push(`head-watcher`)}function c(e){for(let r of e)try{let e=Pj(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=JC(e),a=Ee.documents.get(i);if(!a)continue;let o=it(i);o===null?b.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function l(e){for(let r of e)try{let e=Pj(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Ee.documents.get(JC(e));i&&ot(i)}catch(e){b.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let d=rve(h),f=ae();f.mode!==`off`&&b.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{_t=new X_e({projectDir:n,contentDir:t,contentFilter:ye,contentRoot:p,mode:f.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:d,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ne(e),e||we.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:c,onContentConflictsResolved:l,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=Se.current;n&&await hC(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=Se.current;n&&await hC(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Go({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:ro(t.error),configPath:Mo(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await _t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),_t=null}We(`files`),We(`backlinks`),We(`graph`),We(`tags`);let m=tV();m!==void 0&&nV(`readyMs`,m)}return St().then(Ve,He),{hocuspocus:Ee,durabilityState:x,sessionManager:De,cc1Broadcaster:ke,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:Ce,contentFilter:ye,basenameIndex:ge,serverInstanceId:fe,destroy:bt,ready:Ue,degraded:xt,lockDir:pe,get syncEngine(){return _t},resolveEmbed:_e,acpRegistry:me,acpPermissions:he}}function T9(e){return e/1048576}function ave(){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;No(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function ove(){if(E9)return;let e=is().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}=ave();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 sve(){if(!D9){let e=is().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=_ee({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=is().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=SM(e);M9=new ps({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ya(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(){ya(null),await M9?.drain(),M9=null,N9=!1}Co();const cve=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],lve=[`cache`,`tmp`];function uve(e){let t=z(e,oo);if(!(()=>{if(!B(t))return!0;try{return Wl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of cve)B(z(e,t))&&n.push(t);for(let t of lve){let r=z(e,t);try{B(r)&&Xl(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function dve(e){let t=zu(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 fve(e){eV();let t=e.projectDir??e.contentDir,n=jY({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}`)}ls.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}rs({localSink:n?.telemetry}),F9(t),ove(),sve();let{kind:r,gitdir:i}=dve(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Jo(i));let o=CY(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Po(`ok.boot`,{attributes:a},async()=>pve(e)),l=()=>{if(s)try{let e=xo.extract(wo.active(),{traceparent:s});return wo.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 pve(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??F(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?Tj(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new wj("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-CQupI16l.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!B(z(m,`config.yml`)))throw new r5(B(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);B(h)||F(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??BR;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof LR||e instanceof RR){let t=e instanceof RR?e.detected:``,n=e instanceof RR?`too_old`:`not_available`;cW(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ns(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let _=uve(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${oo}/.`);let v=w9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne}=v,re=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ie=e.port??0,ae=e.ephemeral?void 0:Z8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${re}:${ie}`,log:r}),oe=c();oe.headersTimeout=3e4,oe.requestTimeout=6e4;let se=e.serveContentAssets===!1?void 0:yM({contentFilter:v.contentFilter,contentSirv:zs(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:yo,assetExtensions:Fa,blocklistExtensions:ja}),ce=!1;if(e.reactShellDistDir)try{nB(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ce=!0}catch(e){if(e instanceof tB)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let le=e.reactShellDistDir?zs(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ue=e.ephemeral?null:new LO({contentDir:e.contentDir,localDir:C,globalDir:z(nu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:te,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${re}:${ie}`,getMcpStdioCommand:()=>IO(e.localOpCliArgs,ie),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ue!==null&&await ue.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let de=$8({httpServer:oe,hocuspocus:y,mcpHttpHandler:ae,remoteAccess:i,log:r,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:se,reactShellMiddleware:le,ephemeral:e.ephemeral,acpThreadManager:ue}),fe=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},pe=null;a!==null&&(pe=wY({httpServer:oe,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await fe()})})),await R9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);oe.once(`error`,r),oe.listen(e.port,e.host,()=>{oe.removeListener(`error`,r),t()})})}catch(e){if(ce)try{aB(C)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await b().catch(()=>{}),u(C),e}let me=tV();me!==void 0&&nV(`httpListenMs`,me);let he=oe.address(),ge=typeof he==`object`&&he?he.port:e.port??0;if(ie=ge,d(C,ge),ce&&rB(C,ge),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:C,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let _e=!1,ve=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};fe=async()=>{if(_e)return;_e=!0;let e=[],t=async(t,n)=>{try{await ve(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(C),ce&&oB(C)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{pe?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ue!==null&&await t(`acpThreads.destroy`,()=>ue.destroy()),await t(`mount.shutdown`,()=>de.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{de.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{oe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{oe.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ce&&await t(`releaseUiLock`,async()=>aB(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ns()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>ls.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await Gz({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:oe,destroy:fe,lockDir:C,contentDir:e.contentDir,port:ge,ready:x,degraded:S,didAutoInit:f,serverInstance:v,acpThreadManager:ue}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new _Y(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=Bu(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=vs({baseDir:n,timeout:{block:5e3}});s=new Set(await bS(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=JC(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 mve=qa;function hve(e={}){let t=e.home??nu(),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(fs(),1);const B9=L(nu(),`.ok`,`logs`),gve=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function _ve(){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 vve(e){zl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function yve(e){try{if(Xl(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{ql(n,r)}catch{}}try{Zl(`${e}.3`)}catch{}}function bve(e){try{let t=Date.now(),n=10080*60*1e3,r=Wl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Xl(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{Zl(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{Zl(L(e,t.name)),a-=t.size}catch{}}}catch{}}function xve(e){vve(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);yve(n),(e._setTimeout??setTimeout)(()=>bve(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:_ve(),name:e.name,redact:{paths:gve,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 Sve(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 Cve(e){return L(B9,`${e}.${V9()}.log`)}function wve(){return B9}function Tve(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(yl),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 Eve(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],zP({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function Dve(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!Xl(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=BR()}catch(e){throw e instanceof LR||e instanceof RR?(cW(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof RR?`too_old`:`not_available`,detectedVersion:e instanceof RR?e.detected:``},e instanceof RR?`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 Eve(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],zP({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}$/,Ove=yi.map(e=>e.replace(/\/$/,``));async function kve(e){let t=Bu(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(Nve(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ys(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await _s(async()=>{let t=await Ave(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await jve(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=ys(e,{gitIndexFile:L(au(),`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 Mve(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await EH(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;xs(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${Ie}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of Ove){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function Ave(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 jve(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function Mve(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function Nve(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 Pve(e,t){let n;try{n=vl(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 uu(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 Fve=[{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 Fve)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 Ive(e){if(!KC(e))throw new $9(e);let t;try{t=Kl(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Xl(t).isFile())throw new Q9(e);let n=I(t),r=uH(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:JC(R(Lve(e),t).split(kl).join(`/`)),canonicalFilePath:t}}let i=Cl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:JC(i)}}function Lve(e){return z(e,ko({absPath:Mo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function Rve(e){let t=Bl(z(au(),`ok-ephemeral-`)),n=z(t,`.ok`);return zl(n,{recursive:!0}),Ql(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Ql(z(n,`.gitignore`),`local/
|
|
3273
|
+
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}ne(!1),await we.flushDeferredStores(`discard-stale`),ke?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&Se.current&&r>0){let t=p??`.`;try{let n=await fC(Se.current,t,e.oldHead,e.newHead,i);CS(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),xt.push(`head-watcher`)}function c(e){for(let r of e)try{let e=Pj(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=JC(e),a=Ee.documents.get(i);if(!a)continue;let o=it(i);o===null?b.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function l(e){for(let r of e)try{let e=Pj(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Ee.documents.get(JC(e));i&&ot(i)}catch(e){b.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let d=rve(h),f=ae();f.mode!==`off`&&b.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{_t=new X_e({projectDir:n,contentDir:t,contentFilter:ye,contentRoot:p,mode:f.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:d,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ne(e),e||we.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:c,onContentConflictsResolved:l,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=Se.current;n&&await hC(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=Se.current;n&&await hC(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Go({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:ro(t.error),configPath:Mo(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await _t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),_t=null}We(`files`),We(`backlinks`),We(`graph`),We(`tags`);let m=tV();m!==void 0&&nV(`readyMs`,m)}return St().then(Ve,He),{hocuspocus:Ee,durabilityState:x,sessionManager:De,cc1Broadcaster:ke,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:Ce,contentFilter:ye,basenameIndex:ge,serverInstanceId:fe,destroy:bt,ready:Ue,degraded:xt,lockDir:pe,get syncEngine(){return _t},resolveEmbed:_e,acpRegistry:me,acpPermissions:he}}function T9(e){return e/1048576}function ave(){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;No(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function ove(){if(E9)return;let e=is().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}=ave();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 sve(){if(!D9){let e=is().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=_ee({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=is().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=SM(e);M9=new ps({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ya(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(){ya(null),await M9?.drain(),M9=null,N9=!1}Co();const cve=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],lve=[`cache`,`tmp`];function uve(e){let t=z(e,oo);if(!(()=>{if(!B(t))return!0;try{return Wl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of cve)B(z(e,t))&&n.push(t);for(let t of lve){let r=z(e,t);try{B(r)&&Xl(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function dve(e){let t=zu(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 fve(e){eV();let t=e.projectDir??e.contentDir,n=jY({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}`)}ls.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}rs({localSink:n?.telemetry}),F9(t),ove(),sve();let{kind:r,gitdir:i}=dve(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Jo(i));let o=CY(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Po(`ok.boot`,{attributes:a},async()=>pve(e)),l=()=>{if(s)try{let e=xo.extract(wo.active(),{traceparent:s});return wo.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 pve(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??F(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?Tj(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new wj("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-DRXm0IHt.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!B(z(m,`config.yml`)))throw new r5(B(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);B(h)||F(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??BR;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof LR||e instanceof RR){let t=e instanceof RR?e.detected:``,n=e instanceof RR?`too_old`:`not_available`;cW(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ns(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let _=uve(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${oo}/.`);let v=w9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne}=v,re=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ie=e.port??0,ae=e.ephemeral?void 0:Z8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${re}:${ie}`,log:r}),oe=c();oe.headersTimeout=3e4,oe.requestTimeout=6e4;let se=e.serveContentAssets===!1?void 0:yM({contentFilter:v.contentFilter,contentSirv:zs(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:yo,assetExtensions:Fa,blocklistExtensions:ja}),ce=!1;if(e.reactShellDistDir)try{nB(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ce=!0}catch(e){if(e instanceof tB)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let le=e.reactShellDistDir?zs(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ue=e.ephemeral?null:new LO({contentDir:e.contentDir,localDir:C,globalDir:z(nu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:te,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${re}:${ie}`,getMcpStdioCommand:()=>IO(e.localOpCliArgs,ie),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ue!==null&&await ue.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let de=$8({httpServer:oe,hocuspocus:y,mcpHttpHandler:ae,remoteAccess:i,log:r,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:se,reactShellMiddleware:le,ephemeral:e.ephemeral,acpThreadManager:ue}),fe=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},pe=null;a!==null&&(pe=wY({httpServer:oe,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await fe()})})),await R9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);oe.once(`error`,r),oe.listen(e.port,e.host,()=>{oe.removeListener(`error`,r),t()})})}catch(e){if(ce)try{aB(C)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await b().catch(()=>{}),u(C),e}let me=tV();me!==void 0&&nV(`httpListenMs`,me);let he=oe.address(),ge=typeof he==`object`&&he?he.port:e.port??0;if(ie=ge,d(C,ge),ce&&rB(C,ge),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:C,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let _e=!1,ve=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};fe=async()=>{if(_e)return;_e=!0;let e=[],t=async(t,n)=>{try{await ve(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(C),ce&&oB(C)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{pe?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ue!==null&&await t(`acpThreads.destroy`,()=>ue.destroy()),await t(`mount.shutdown`,()=>de.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{de.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{oe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{oe.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ce&&await t(`releaseUiLock`,async()=>aB(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ns()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>ls.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await Gz({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:oe,destroy:fe,lockDir:C,contentDir:e.contentDir,port:ge,ready:x,degraded:S,didAutoInit:f,serverInstance:v,acpThreadManager:ue}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new _Y(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=Bu(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=vs({baseDir:n,timeout:{block:5e3}});s=new Set(await bS(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=JC(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 mve=qa;function hve(e={}){let t=e.home??nu(),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(fs(),1);const B9=L(nu(),`.ok`,`logs`),gve=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function _ve(){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 vve(e){zl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function yve(e){try{if(Xl(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{ql(n,r)}catch{}}try{Zl(`${e}.3`)}catch{}}function bve(e){try{let t=Date.now(),n=10080*60*1e3,r=Wl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Xl(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{Zl(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{Zl(L(e,t.name)),a-=t.size}catch{}}}catch{}}function xve(e){vve(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);yve(n),(e._setTimeout??setTimeout)(()=>bve(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:_ve(),name:e.name,redact:{paths:gve,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 Sve(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 Cve(e){return L(B9,`${e}.${V9()}.log`)}function wve(){return B9}function Tve(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(yl),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 Eve(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],zP({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function Dve(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!Xl(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=BR()}catch(e){throw e instanceof LR||e instanceof RR?(cW(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof RR?`too_old`:`not_available`,detectedVersion:e instanceof RR?e.detected:``},e instanceof RR?`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 Eve(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],zP({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}$/,Ove=yi.map(e=>e.replace(/\/$/,``));async function kve(e){let t=Bu(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(Nve(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ys(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await _s(async()=>{let t=await Ave(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await jve(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=ys(e,{gitIndexFile:L(au(),`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 Mve(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await EH(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;xs(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${Ie}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of Ove){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function Ave(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 jve(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function Mve(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function Nve(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 Pve(e,t){let n;try{n=vl(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 uu(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 Fve=[{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 Fve)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 Ive(e){if(!KC(e))throw new $9(e);let t;try{t=Kl(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Xl(t).isFile())throw new Q9(e);let n=I(t),r=uH(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:JC(R(Lve(e),t).split(kl).join(`/`)),canonicalFilePath:t}}let i=Cl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:JC(i)}}function Lve(e){return z(e,ko({absPath:Mo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function Rve(e){let t=Bl(z(au(),`ok-ephemeral-`)),n=z(t,`.ok`);return zl(n,{recursive:!0}),Ql(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Ql(z(n,`.gitignore`),`local/
|
|
3274
3274
|
`,`utf-8`),t}export{a4 as $,XS as $i,_R as $n,yP as $r,iW as $t,n9 as A,aD as Ai,aV as An,AI as Ar,iY as At,b7 as B,UC as Bi,FR as Bn,tF as Br,iK as Bt,w9 as C,LO as Ci,wV as Cn,Woe as Cr,fY as Ct,t9 as D,oD as Di,cV as Dn,MI as Dr,Jq as Dt,Q7 as E,WE as Ei,sV as En,PI as Er,Yq as Et,E7 as F,pw as Fi,iB as Fn,AF as Fr,$G as Ft,$8 as G,cC as Gi,HR as Gn,PP as Gr,lK as Gt,g7 as H,HC as Hi,rz as Hn,VP as Hr,hK as Ht,Jge as I,G as Ii,aB as In,$P as Ir,pK as It,J8 as J,rC as Ji,jR as Jn,vae as Jr,XG as Jt,e5 as K,lC as Ki,PR as Kn,NP as Kr,aK as Kt,O7 as L,fw as Li,rB as Ln,QP as Lr,dK as Lt,Z7 as M,yE as Mi,UB as Mn,aI as Mr,EK as Mt,G7 as N,bE as Ni,tB as Nn,Coe as Nr,CK as Nt,i9 as O,lD as Oi,uV as On,zoe as Or,_J as Ot,H7 as P,HE as Pi,nB as Pn,jF as Pr,vK as Pt,e4 as Q,xC as Qi,TR as Qn,aae as Qr,cW as Qt,D7 as R,GC as Ri,LR as Rn,nF as Rr,mK as Rt,I9 as S,Nu as Sa,GO as Si,GV as Sn,zI as Sr,uY as St,x9 as T,IO as Ti,hV as Tn,FI as Tr,sY as Tt,n5 as U,LC as Ui,zR as Un,WP as Ur,sK as Ut,y7 as V,BC as Vi,BR as Vn,XP as Vr,fK as Vt,r5 as W,yC as Wi,KR as Wn,zP as Wr,oK as Wt,Q2 as X,$S as Xi,OR as Xn,_ae as Xr,uW as Xt,R8 as Y,fC as Yi,NR as Yn,hae as Yr,fW as Yt,$2 as Z,oC as Zi,bR as Zn,gae as Zr,sW as Zt,mve as _,hd as _a,Tj as _i,WV as _n,_L as _r,hY as _t,Ive as a,zS as aa,sP as ai,PH as an,mR as ar,Lse as at,F9 as b,Vu as ba,YO as bi,KV as bn,VI as br,cY as bt,kve as c,OS as ca,SM as ci,MH as cn,rR as cr,M2 as ct,Tve as d,sg as da,yM as di,lH as dn,eR as dr,ZZ as dt,vC as ea,EP as ei,rW as en,pR as er,Yse as et,xve as f,ug as fa,Ij as fi,xV as fn,BL as fr,TZ as ft,hve as g,wd as ga,Aj as gi,JV as gn,UL as gr,wY as gt,wve as h,gd as ha,Mj as hi,DV as hn,HL as hr,qZ as ht,Rve as i,qS as ia,uP as ii,zH as in,uR as ir,Ise as it,r9 as j,XE as ji,ZB as jn,Roe as jr,lJ as jt,$7 as k,iD as ki,lV as kn,jI as kr,vJ as kt,W9 as l,Yre as la,xM as li,VH as ln,tR as lr,N2 as lt,Cve as m,Cd as ma,wj as mi,OV as mn,LL as mr,UZ as mt,Z9 as n,gC as na,dP as ni,AH as nn,gR as nr,G2 as nt,X9 as o,LS as oa,lP as oi,UH as on,fR as or,Rse as ot,Sve as p,lg as pa,Nj as pi,qV as pn,VL as pr,mQ as pt,Z8 as q,uC as qi,MR as qn,AP as qr,YG as qt,$9 as r,EC as ra,zie as ri,RH as rn,dR as rr,B2 as rt,Pve as s,FS as sa,cP as si,BH as sn,nR as sr,P2 as st,Q9 as t,hC as ta,Vie as ti,eW as tn,hR as tr,K2 as tt,Dve as u,cg as ua,CM as ui,uH as un,qL as ur,z0 as ut,fve as v,Wu as va,Cj as vi,zV as vn,$I as vr,lY as vt,C9 as w,MO as wi,mV as wn,NI as wr,mY as wt,P9 as x,Pu as xa,qO as xi,sH as xn,HI as xr,dY as xt,R9 as y,Uu as ya,Sj as yi,EV as yn,BI as yr,pY as yt,Ige as z,zC as zi,RR as zn,eF as zr,rK as zt};
|
|
3275
|
-
//# sourceMappingURL=src-
|
|
3275
|
+
//# sourceMappingURL=src-BqSmDSx1.mjs.map
|