@inkeep/open-knowledge 0.46.0-beta.8 → 0.46.0-beta.9
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-4DjqrOhu.mjs → acp-harness-probe-B3zP-iU3.mjs} +2 -2
- package/dist/cli.mjs +7 -7
- package/dist/constants-DJEQ5lbI.mjs +2 -0
- package/dist/git-handle-CZCF5f5x.mjs +1 -0
- package/dist/{git-handle-CUCj-M_k.mjs → git-handle-bsekfuqb.mjs} +3 -3
- package/dist/index.mjs +1 -1
- package/dist/{init-DWCsIT2Y.mjs → init-BSRAJcxJ.mjs} +3 -3
- package/dist/init-Nj3Qfja6.mjs +1 -0
- package/dist/{launch-json-removal-BCxhJz-M.mjs → launch-json-removal-Z49VHJab.mjs} +2 -2
- package/dist/{loader-84N4YMxM.mjs → loader-7F0JSi2o.mjs} +2 -2
- package/dist/loader-DEoi209o.mjs +1 -0
- package/dist/md-manager-DbwR9qMJ.mjs +2 -0
- package/dist/{open-browser-D-fJ9iwf.mjs → open-browser-DOh4nE9t.mjs} +2 -2
- package/dist/parse-worker.mjs +1 -1
- package/dist/{preview-Ce0jIM-0.mjs → preview-CI4qefY8.mjs} +2 -2
- package/dist/preview-rMognm1O.mjs +1 -0
- package/dist/public/assets/FeedbackForm-Dx8ISPUC.js +1 -0
- package/dist/public/assets/ShareBranchSwitchDialog-BOn9pwt8.js +1 -0
- package/dist/public/assets/{worktree-store-Cn9IFis3.js → auth-prompt-store-CmyRhcKh.js} +1 -1
- package/dist/public/assets/{globals-B5uVOYYT.js → globals-IzHn2MUy.js} +1 -1
- package/dist/public/assets/{index-DoyHoCFU.js → index-BW1cVj8N.js} +108 -108
- package/dist/public/assets/{uninstall-m1tFru3-.js → uninstall-BCLudTra.js} +1 -1
- package/dist/public/index.html +3 -3
- package/dist/public/uninstall.html +2 -2
- package/dist/{repair-launch-json-DKnGHC3s.mjs → repair-launch-json-Chs2wXL5.mjs} +2 -2
- package/dist/{repair-mcp-configs-BNqk430t.mjs → repair-mcp-configs-DC_Nk6wf.mjs} +2 -2
- package/dist/{repair-skills-HLaZ-M-Y.mjs → repair-skills-BW5UCBvh.mjs} +2 -2
- package/dist/repair-skills-v_TK3DOo.mjs +1 -0
- package/dist/server-lock-9cnBGhAH.mjs +1 -0
- package/dist/{server-lock-N4bxkmqA.mjs → server-lock-Cdm6cZ-8.mjs} +2 -2
- package/dist/{src-BldBF2Y_.mjs → src-2ftHD8eU.mjs} +1 -1
- package/dist/{src-B9fZz8CV.mjs → src-DrNAleIl.mjs} +2 -2
- package/dist/{src-BAuCUhtO.mjs → src-tAuEvoB8.mjs} +2 -2
- package/dist/{src-CBxmkYgG.mjs → src-zLMYDmwT.mjs} +4 -4
- package/dist/{start-CGRdHb1G.mjs → start-Bx6I5bEA.mjs} +3 -3
- package/dist/start-MnLPFpd0.mjs +1 -0
- package/dist/{write-project-skill-DZsw6Rkw.mjs → write-project-skill-xt4ohzdz.mjs} +2 -2
- package/package.json +4 -4
- package/dist/constants-GWFx-UC8.mjs +0 -2
- package/dist/git-handle-c0ljFZis.mjs +0 -1
- package/dist/init-ZV2BMIkj.mjs +0 -1
- package/dist/loader-gOaiaXCo.mjs +0 -1
- package/dist/md-manager-usiCjUg4.mjs +0 -2
- package/dist/preview-TJlA1vTS.mjs +0 -1
- package/dist/public/assets/FeedbackForm-YYOLAdPR.js +0 -1
- package/dist/public/assets/ShareBranchSwitchDialog-BT-R1a5Z.js +0 -1
- package/dist/repair-skills-COiT9pxq.mjs +0 -1
- package/dist/server-lock-DTx_HmnT.mjs +0 -1
- package/dist/start-uD8bt0wq.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,$o as s,$r as c,$t as l,A as u,Aa as d,Ai as f,An as p,Ar as m,B as h,Ba as g,Bi as _,Bn as v,Bo as y,Br as b,Bt as x,C as S,Ca as C,Ci as w,Cn as T,Co as E,Cr as ee,Cs as te,Ct as ne,D as re,Di as ie,Dn as ae,Do as oe,Dr as se,Dt as ce,E as le,Ea as ue,Ei as de,En as fe,Eo as pe,Er as me,Et as he,F as ge,Fa as _e,Fi as ve,Fn as ye,Fo as be,Fr as xe,Ft as Se,G as Ce,Ga as we,Gi as Te,Gn as Ee,Go as De,Gr as Oe,Gt as ke,H as Ae,Ha as je,Hi as Me,Hn as Ne,Ho as Pe,Hr as Fe,Ht as Ie,I as Le,Ia as Re,Ii as ze,In as Be,Io as Ve,Ir as He,It as Ue,J as We,Ja as Ge,Ji as Ke,Jn as qe,Jo as D,Jr as Je,Jt as Ye,K as Xe,Ka as Ze,Ki as Qe,Kn as $e,Ko as et,Kr as tt,Kt as nt,L as rt,La as it,Li as at,Ln as ot,Lo as st,Lr as ct,Lt as lt,M as ut,Ma as dt,Mi as ft,Mn as pt,Mo as mt,Mr as ht,Mt as gt,N as _t,Na as vt,Ni as yt,Nn as bt,Nr as eee,Nt as xt,O as St,Oa as Ct,Oi as tee,On as nee,Or as wt,Ot as Tt,P as Et,Pa as Dt,Pi as Ot,Pn as kt,Po as At,Pr as jt,Pt as Mt,Qa as Nt,Qi as Pt,Qn as ree,Qo as Ft,Qr as iee,Qt as aee,Ra as It,Ri as Lt,Rn as oee,Ro as Rt,Rr as see,Rt as zt,S as Bt,Sa as Vt,Si as Ht,Sn as Ut,So as Wt,Sr as Gt,Ss as Kt,St as qt,T as Jt,Ta as Yt,Ti as Xt,Tn as Zt,To as Qt,Tr as $t,Tt as en,U as tn,Ua as nn,Ui as rn,Un as an,Uo as on,Ur as cee,Ut as lee,V as uee,Va as dee,Vi as sn,Vn as fee,Vo as cn,Vr as ln,Vt as un,W as dn,Wa as pee,Wi as fn,Wn as mee,Wr as hee,Wt as gee,X as pn,Xa as mn,Xi as hn,Xn as _ee,Xo as gn,Xr as _n,Xt as vee,Ya as yee,Yi as vn,Yn as yn,Yo as bn,Yr as xn,Yt as bee,Za as Sn,Zi as Cn,Zn as wn,Zo as Tn,Zr as xee,Zt as See,_ as En,_a as Dn,_i as On,_n as kn,_o as An,_r as jn,_t as Mn,a as Nn,aa as Pn,ai as Fn,an as In,ar as Ln,as as Rn,at as zn,b as Bn,ba as Vn,bi as Hn,bn as Un,bo as Wn,br as Gn,bs as Kn,bt as qn,c as Jn,ca as Yn,ci as Xn,cn as Zn,cr as Qn,cs as $n,ct as er,d as tr,da as nr,di as Cee,dn as wee,do as rr,dr as Tee,ds as ir,dt as ar,ea as or,ei as Eee,en as Dee,eo as sr,er as Oee,es as cr,et as lr,f as ur,fa as kee,fi as Aee,fn as jee,fo as dr,fr as Mee,fs as fr,ft as pr,g as mr,ga as hr,gi as Nee,gn as Pee,gr as Fee,gt as gr,h as _r,ha as vr,hi as yr,hn as Iee,ho as br,hr as Lee,hs as xr,ht as Sr,i as Cr,ia as wr,ii as Tr,in as Ree,io as Er,ir as zee,is as Dr,it as Or,j as kr,ja as Ar,ji as Bee,jn as Vee,jo as jr,jr as Hee,jt as Mr,k as Uee,ka as Nr,ki as Pr,kn as Fr,ko as Ir,kr as Wee,l as Lr,la as Rr,li as zr,ln as Br,lo as Vr,lr as Hr,ls as Ur,lt as Wr,ma as Gr,mi as Kr,mn as qr,mo as Jr,mr as Yr,mt as Xr,n as Zr,na as Qr,ni as $r,nn as ei,no as ti,nr as ni,ns as ri,nt as ii,o as ai,oa as Gee,oi,on as Kee,oo as si,or as ci,os as li,ot as ui,p as di,pa as fi,pi,pn as mi,pr as hi,pt as gi,q as _i,qa as vi,qi as yi,qn as bi,qo 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,rs as Ai,rt as ji,s as Mi,sa as Ni,si as Pi,sn as Fi,sr as Ii,ss as Li,st as Ri,t as zi,ta as Bi,ti as Vi,tn as Hi,tr as Ui,ts as Wi,tt as Gi,u as Ki,ua as qi,ui as Ji,un as Yi,uo as Xi,ur as Zi,us as Qi,ut as $i,v as ea,va as ta,vi as na,vn as ra,vo as ia,vr as aa,vs as oa,vt as sa,w as ca,wa as la,wi as ua,wn as da,wo as fa,wr as pa,ws as ma,wt as ha,x as ga,xa as _a,xi as va,xn as ya,xr as ba,xs as xa,xt as Sa,y as Ca,ya as wa,yi as Ta,yn as Ea,yo as Da,yr as Oa,ys as ka,yt as Aa,z as ja,za as Ma,zi as Na,zn as Pa,zo as Fa,zr as Ia,zt as La}from"./src-BAuCUhtO.mjs";import{$ as Ra,At as za,B as Ba,C as Va,Dt as Ha,E as Ua,Et as Wa,Ft as Ga,G as Ka,H as qa,I as Ja,J as Ya,K as Xa,Mt as Za,N as Qa,Nt as $a,Ot as eo,Pt as to,Q as no,S as ro,T as qee,Tt as io,V as ao,W as oo,Y as so,Z as co,_ as lo,_t as O,at as uo,bt as fo,ct as k,dt as A,ft as po,g as mo,gt as ho,h as go,ht as j,i as _o,it as vo,jt as yo,kt as bo,l as xo,lt as So,m as Co,mt as M,n as wo,nt as To,ot as Eo,pt as Do,r as Oo,rt as ko,t as Ao,tt as N,u as jo,ut as P,v as Mo,vt as No,w as Po,wt as Fo,xt as Io,yt as Lo,z as Ro}from"./sleep-IcuyYCzq.mjs";import{c as zo,i as Bo,l as Jee,n as Vo,s as Ho}from"./esm-CItKw7Y6.mjs";import{n as Uo,t as Wo}from"./md-manager-usiCjUg4.mjs";import{A as Go,C as Ko,D as qo,E as Jo,N as Yo,O as Xo,S as Zo,T as Qo,_ as $o,a as es,b as Yee,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,t as gs,u as _s,v as vs,w as ys,x as bs,y as xs}from"./fs-traced-B-x7hAhD.mjs";import{D as Xee,E as Ss,S as Cs,T as ws,a as Ts,b as Es,l as Ds,p as Os,r as F,s as ks,x as As,y as js}from"./logger-B7Z8XO-z.mjs";import{a as Ms,i as Ns,o as Ps,r as Fs,s as Is,t as Ls}from"./git-handle-CUCj-M_k.mjs";import{S as Rs,a as zs,b as Zee,c as Bs,d as Vs,f as Hs,g as Us,h as Ws,i as Gs,l as Ks,m as qs,n as Js,r as Ys,x as Xs,y as Zs}from"./server-lock-N4bxkmqA.mjs";import{t as Qs}from"./libesm-DzwC_yFw.mjs";import{n as $s,t as ec}from"./build-DYQrG4v7.mjs";import{t as tc}from"./yazl-BafwB467.mjs";import{t as nc}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as rc,c as ic,d as ac,f as oc,h as sc,i as cc,l as lc,m as uc,n as dc,o as fc,p as pc,r as mc,s as hc,t as gc,u as _c}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as vc,B as yc,C as bc,D as xc,E as Sc,F as Cc,H as wc,I as Tc,L as Ec,M as Dc,N as Oc,O as kc,P as Ac,S as jc,T as Mc,V as Nc,_ as Pc,a as Fc,b as Ic,c as Lc,d as Rc,f as zc,g as Bc,h as Vc,i as Hc,j as Uc,k as Wc,l as Gc,m as Kc,n as qc,o as Jc,p as Yc,r as Xc,s as Zc,t as Qc,u as $c,v as el,w as tl,x as nl,y as rl,z as il}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as al,c as ol,d as sl,i as cl,l as ll,n as ul,o as dl,r as fl,s as pl,t as ml,u as hl}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as gl,r as _l,t as vl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as yl}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as bl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as xl,t as Sl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Cl,t as wl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Tl,r as El,t as Dl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ol,t as kl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Al}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as jl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Ml}from"./wrapper-BcpqREsI.mjs";import{createRequire as Nl}from"node:module";import{execFile as Pl,execFileSync as Fl,spawn as Il,spawnSync as Ll}from"node:child_process";import*as Rl from"node:path";import{basename as zl,delimiter as Bl,dirname as I,extname as Vl,isAbsolute as Hl,join as L,normalize as Ul,posix as Wl,relative as R,resolve as z,sep as B,win32 as Gl}from"node:path";import*as Kl from"node:fs";import{appendFileSync as ql,chmodSync as Jl,closeSync as Yl,constants as Xl,createReadStream as Zl,createWriteStream as Ql,existsSync as V,lstatSync as $l,mkdirSync as eu,mkdtempSync as tu,openSync as nu,readFile as ru,readFileSync as H,readSync as iu,readdirSync as au,readlinkSync as ou,realpathSync as U,renameSync as su,rmSync as cu,rmdirSync as lu,statSync as uu,unlinkSync as du,writeFileSync as fu,writeSync as pu}from"node:fs";import{arch as mu,availableParallelism as hu,homedir as gu,hostname as _u,platform as vu,tmpdir as yu}from"node:os";import{access as bu,chmod as xu,constants as Su,lstat as Cu,readFile as wu,readdir as Tu,realpath as Eu,stat as Du,writeFile as Ou}from"node:fs/promises";import{Readable as ku,Transform as Au,Writable as ju}from"node:stream";import{URLSearchParams as Mu,fileURLToPath as Nu,pathToFileURL as Pu}from"node:url";import Fu,{createHash as Iu,randomUUID as Lu,webcrypto as Ru}from"node:crypto";import zu from"crypto";import{Readable as Bu}from"stream";import{Worker as Vu}from"node:worker_threads";import{monitorEventLoopDelay as Hu,performance as Uu}from"node:perf_hooks";import{createInterface as Wu}from"node:readline";import{pipeline as Gu}from"node:stream/promises";import{setImmediate as Ku,setTimeout as qu}from"node:timers/promises";import{promisify as Ju}from"node:util";import{lookup as Yu}from"node:dns/promises";import{request as Xu}from"node:http";import{request as Zu}from"node:https";import{createBrotliDecompress as Qu,createGunzip as $u,createInflate as Qee}from"node:zlib";import{Http2ServerRequest as ed,constants as $ee}from"http2";import{AsyncLocalStorage as ete}from"node:async_hooks";import{lookup as tte}from"node:dns";import nte from"node:tls";var td=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=H(L(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Hl(t)?t:z(this.gitDir,t))}catch(e){if(!ad(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=H(L(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return ad(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]}:sd(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=H(L(t.path,`config`),`utf-8`)}catch(e){return ad(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=rte(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!od(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(`..`)||Hl(r))return{kind:`invalid`};try{let e=H(n,`utf-8`).trim(),t=ote(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!ad(e))return{kind:`unreadable`,cause:e}}let i;try{i=H(L(t.path,`packed-refs`),`utf-8`)}catch(e){return ad(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 sd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function nd(e){return id(z(e),``)}function rd(e){let t=z(e),n=z(gu());if(t===n)return{kind:`absent`};let r=id(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=id(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function id(e,t){let n=L(e,`.git`),r;try{r=uu(n)}catch(e){return ad(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new td(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=H(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=Hl(o)?o:z(e,o);try{if(!uu(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 td(`linked`,e,t,n,s)}}function rte(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=ite(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=ate(i[1]);if(a.length>0)return a}return null}function ite(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function ate(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function ad(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function od(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function ote(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?od(t[1])?{kind:`symbolic`,target:t[1]}:null:sd(e)?{kind:`oid`,oid:e}:null}function sd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function ste(e){return`git-author-${ma(e.trim().toLowerCase())}`}const cte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function cd(e){let t=rd(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 ld(e){let t=cd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ud(e){let t=cd(e);switch(t.kind){case`directory`:return z(t.path,dd(t.projectSubPath));case`linked`:if(!V(t.path))throw new fd(t.gitPath,t.path);return z(t.path,dd(t.projectSubPath));case`malformed-pointer`:throw new fd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new pd(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function dd(e){return e===``?`ok`:`ok-${lte(e)}`}function lte(e){let t=e.split(B).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=ute(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function ute(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var fd=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}},pd=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 dte(e){let t;try{t=ud(e)}catch(e){if(e instanceof fd||e instanceof pd)return null;throw e}return V(z(t,`HEAD`))?t:null}function md(e){return`refs/wip/${e}/`}function fte(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,$o as s,$r as c,$t as l,A as u,Aa as d,Ai as f,An as p,Ar as m,B as h,Ba as g,Bi as _,Bn as v,Bo as y,Br as b,Bt as x,C as S,Ca as C,Ci as w,Cn as T,Co as E,Cr as ee,Cs as te,Ct as ne,D as re,Di as ie,Dn as ae,Do as oe,Dr as se,Dt as ce,E as le,Ea as ue,Ei as de,En as fe,Eo as pe,Er as me,Et as he,F as ge,Fa as _e,Fi as ve,Fn as ye,Fo as be,Fr as xe,Ft as Se,G as Ce,Ga as we,Gi as Te,Gn as Ee,Go as De,Gr as Oe,Gt as ke,H as Ae,Ha as je,Hi as Me,Hn as Ne,Ho as Pe,Hr as Fe,Ht as Ie,I as Le,Ia as Re,Ii as ze,In as Be,Io as Ve,Ir as He,It as Ue,J as We,Ja as Ge,Ji as Ke,Jn as qe,Jo as D,Jr as Je,Jt as Ye,K as Xe,Ka as Ze,Ki as Qe,Kn as $e,Ko as et,Kr as tt,Kt as nt,L as rt,La as it,Li as at,Ln as ot,Lo as st,Lr as ct,Lt as lt,M as ut,Ma as dt,Mi as ft,Mn as pt,Mo as mt,Mr as ht,Mt as gt,N as _t,Na as vt,Ni as yt,Nn as bt,Nr as eee,Nt as xt,O as St,Oa as Ct,Oi as tee,On as nee,Or as wt,Ot as Tt,P as Et,Pa as Dt,Pi as Ot,Pn as kt,Po as At,Pr as jt,Pt as Mt,Qa as Nt,Qi as Pt,Qn as ree,Qo as Ft,Qr as iee,Qt as aee,Ra as It,Ri as Lt,Rn as oee,Ro as Rt,Rr as see,Rt as zt,S as Bt,Sa as Vt,Si as Ht,Sn as Ut,So as Wt,Sr as Gt,Ss as Kt,St as qt,T as Jt,Ta as Yt,Ti as Xt,Tn as Zt,To as Qt,Tr as $t,Tt as en,U as tn,Ua as nn,Ui as rn,Un as an,Uo as on,Ur as cee,Ut as lee,V as uee,Va as dee,Vi as sn,Vn as fee,Vo as cn,Vr as ln,Vt as un,W as dn,Wa as pee,Wi as fn,Wn as mee,Wr as hee,Wt as gee,X as pn,Xa as mn,Xi as hn,Xn as _ee,Xo as gn,Xr as _n,Xt as vee,Ya as yee,Yi as vn,Yn as yn,Yo as bn,Yr as xn,Yt as bee,Za as Sn,Zi as Cn,Zn as wn,Zo as Tn,Zr as xee,Zt as See,_ as En,_a as Dn,_i as On,_n as kn,_o as An,_r as jn,_t as Mn,a as Nn,aa as Pn,ai as Fn,an as In,ar as Ln,as as Rn,at as zn,b as Bn,ba as Vn,bi as Hn,bn as Un,bo as Wn,br as Gn,bs as Kn,bt as qn,c as Jn,ca as Yn,ci as Xn,cn as Zn,cr as Qn,cs as $n,ct as er,d as tr,da as nr,di as Cee,dn as wee,do as rr,dr as Tee,ds as ir,dt as ar,ea as or,ei as Eee,en as Dee,eo as sr,er as Oee,es as cr,et as lr,f as ur,fa as kee,fi as Aee,fn as jee,fo as dr,fr as Mee,fs as fr,ft as pr,g as mr,ga as hr,gi as Nee,gn as Pee,gr as Fee,gt as gr,h as _r,ha as vr,hi as yr,hn as Iee,ho as br,hr as Lee,hs as xr,ht as Sr,i as Cr,ia as wr,ii as Tr,in as Ree,io as Er,ir as zee,is as Dr,it as Or,j as kr,ja as Ar,ji as Bee,jn as Vee,jo as jr,jr as Hee,jt as Mr,k as Uee,ka as Nr,ki as Pr,kn as Fr,ko as Ir,kr as Wee,l as Lr,la as Rr,li as zr,ln as Br,lo as Vr,lr as Hr,ls as Ur,lt as Wr,ma as Gr,mi as Kr,mn as qr,mo as Jr,mr as Yr,mt as Xr,n as Zr,na as Qr,ni as $r,nn as ei,no as ti,nr as ni,ns as ri,nt as ii,o as ai,oa as Gee,oi,on as Kee,oo as si,or as ci,os as li,ot as ui,p as di,pa as fi,pi,pn as mi,pr as hi,pt as gi,q as _i,qa as vi,qi as yi,qn as bi,qo 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,rs as Ai,rt as ji,s as Mi,sa as Ni,si as Pi,sn as Fi,sr as Ii,ss as Li,st as Ri,t as zi,ta as Bi,ti as Vi,tn as Hi,tr as Ui,ts as Wi,tt as Gi,u as Ki,ua as qi,ui as Ji,un as Yi,uo as Xi,ur as Zi,us as Qi,ut as $i,v as ea,va as ta,vi as na,vn as ra,vo as ia,vr as aa,vs as oa,vt as sa,w as ca,wa as la,wi as ua,wn as da,wo as fa,wr as pa,ws as ma,wt as ha,x as ga,xa as _a,xi as va,xn as ya,xr as ba,xs as xa,xt as Sa,y as Ca,ya as wa,yi as Ta,yn as Ea,yo as Da,yr as Oa,ys as ka,yt as Aa,z as ja,za as Ma,zi as Na,zn as Pa,zo as Fa,zr as Ia,zt as La}from"./src-tAuEvoB8.mjs";import{$ as Ra,At as za,B as Ba,C as Va,Dt as Ha,E as Ua,Et as Wa,Ft as Ga,G as Ka,H as qa,I as Ja,J as Ya,K as Xa,Mt as Za,N as Qa,Nt as $a,Ot as eo,Pt as to,Q as no,S as ro,T as qee,Tt as io,V as ao,W as oo,Y as so,Z as co,_ as lo,_t as O,at as uo,bt as fo,ct as k,dt as A,ft as po,g as mo,gt as ho,h as go,ht as j,i as _o,it as vo,jt as yo,kt as bo,l as xo,lt as So,m as Co,mt as M,n as wo,nt as To,ot as Eo,pt as Do,r as Oo,rt as ko,t as Ao,tt as N,u as jo,ut as P,v as Mo,vt as No,w as Po,wt as Fo,xt as Io,yt as Lo,z as Ro}from"./sleep-IcuyYCzq.mjs";import{c as zo,i as Bo,l as Jee,n as Vo,s as Ho}from"./esm-CItKw7Y6.mjs";import{n as Uo,t as Wo}from"./md-manager-DbwR9qMJ.mjs";import{A as Go,C as Ko,D as qo,E as Jo,N as Yo,O as Xo,S as Zo,T as Qo,_ as $o,a as es,b as Yee,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,t as gs,u as _s,v as vs,w as ys,x as bs,y as xs}from"./fs-traced-B-x7hAhD.mjs";import{D as Xee,E as Ss,S as Cs,T as ws,a as Ts,b as Es,l as Ds,p as Os,r as F,s as ks,x as As,y as js}from"./logger-B7Z8XO-z.mjs";import{a as Ms,i as Ns,o as Ps,r as Fs,s as Is,t as Ls}from"./git-handle-bsekfuqb.mjs";import{S as Rs,a as zs,b as Zee,c as Bs,d as Vs,f as Hs,g as Us,h as Ws,i as Gs,l as Ks,m as qs,n as Js,r as Ys,x as Xs,y as Zs}from"./server-lock-Cdm6cZ-8.mjs";import{t as Qs}from"./libesm-DzwC_yFw.mjs";import{n as $s,t as ec}from"./build-DYQrG4v7.mjs";import{t as tc}from"./yazl-BafwB467.mjs";import{t as nc}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as rc,c as ic,d as ac,f as oc,h as sc,i as cc,l as lc,m as uc,n as dc,o as fc,p as pc,r as mc,s as hc,t as gc,u as _c}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as vc,B as yc,C as bc,D as xc,E as Sc,F as Cc,H as wc,I as Tc,L as Ec,M as Dc,N as Oc,O as kc,P as Ac,S as jc,T as Mc,V as Nc,_ as Pc,a as Fc,b as Ic,c as Lc,d as Rc,f as zc,g as Bc,h as Vc,i as Hc,j as Uc,k as Wc,l as Gc,m as Kc,n as qc,o as Jc,p as Yc,r as Xc,s as Zc,t as Qc,u as $c,v as el,w as tl,x as nl,y as rl,z as il}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as al,c as ol,d as sl,i as cl,l as ll,n as ul,o as dl,r as fl,s as pl,t as ml,u as hl}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as gl,r as _l,t as vl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as yl}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as bl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as xl,t as Sl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Cl,t as wl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Tl,r as El,t as Dl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ol,t as kl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Al}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as jl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Ml}from"./wrapper-BcpqREsI.mjs";import{createRequire as Nl}from"node:module";import{execFile as Pl,execFileSync as Fl,spawn as Il,spawnSync as Ll}from"node:child_process";import*as Rl from"node:path";import{basename as zl,delimiter as Bl,dirname as I,extname as Vl,isAbsolute as Hl,join as L,normalize as Ul,posix as Wl,relative as R,resolve as z,sep as B,win32 as Gl}from"node:path";import*as Kl from"node:fs";import{appendFileSync as ql,chmodSync as Jl,closeSync as Yl,constants as Xl,createReadStream as Zl,createWriteStream as Ql,existsSync as V,lstatSync as $l,mkdirSync as eu,mkdtempSync as tu,openSync as nu,readFile as ru,readFileSync as H,readSync as iu,readdirSync as au,readlinkSync as ou,realpathSync as U,renameSync as su,rmSync as cu,rmdirSync as lu,statSync as uu,unlinkSync as du,writeFileSync as fu,writeSync as pu}from"node:fs";import{arch as mu,availableParallelism as hu,homedir as gu,hostname as _u,platform as vu,tmpdir as yu}from"node:os";import{access as bu,chmod as xu,constants as Su,lstat as Cu,readFile as wu,readdir as Tu,realpath as Eu,stat as Du,writeFile as Ou}from"node:fs/promises";import{Readable as ku,Transform as Au,Writable as ju}from"node:stream";import{URLSearchParams as Mu,fileURLToPath as Nu,pathToFileURL as Pu}from"node:url";import Fu,{createHash as Iu,randomUUID as Lu,webcrypto as Ru}from"node:crypto";import zu from"crypto";import{Readable as Bu}from"stream";import{Worker as Vu}from"node:worker_threads";import{monitorEventLoopDelay as Hu,performance as Uu}from"node:perf_hooks";import{createInterface as Wu}from"node:readline";import{pipeline as Gu}from"node:stream/promises";import{setImmediate as Ku,setTimeout as qu}from"node:timers/promises";import{promisify as Ju}from"node:util";import{lookup as Yu}from"node:dns/promises";import{request as Xu}from"node:http";import{request as Zu}from"node:https";import{createBrotliDecompress as Qu,createGunzip as $u,createInflate as Qee}from"node:zlib";import{Http2ServerRequest as ed,constants as $ee}from"http2";import{AsyncLocalStorage as ete}from"node:async_hooks";import{lookup as tte}from"node:dns";import nte from"node:tls";var td=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=H(L(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Hl(t)?t:z(this.gitDir,t))}catch(e){if(!ad(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=H(L(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return ad(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]}:sd(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=H(L(t.path,`config`),`utf-8`)}catch(e){return ad(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=rte(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!od(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(`..`)||Hl(r))return{kind:`invalid`};try{let e=H(n,`utf-8`).trim(),t=ote(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!ad(e))return{kind:`unreadable`,cause:e}}let i;try{i=H(L(t.path,`packed-refs`),`utf-8`)}catch(e){return ad(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 sd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function nd(e){return id(z(e),``)}function rd(e){let t=z(e),n=z(gu());if(t===n)return{kind:`absent`};let r=id(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=id(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function id(e,t){let n=L(e,`.git`),r;try{r=uu(n)}catch(e){return ad(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new td(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=H(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=Hl(o)?o:z(e,o);try{if(!uu(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 td(`linked`,e,t,n,s)}}function rte(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=ite(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=ate(i[1]);if(a.length>0)return a}return null}function ite(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function ate(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function ad(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function od(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function ote(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?od(t[1])?{kind:`symbolic`,target:t[1]}:null:sd(e)?{kind:`oid`,oid:e}:null}function sd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function ste(e){return`git-author-${ma(e.trim().toLowerCase())}`}const cte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function cd(e){let t=rd(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 ld(e){let t=cd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ud(e){let t=cd(e);switch(t.kind){case`directory`:return z(t.path,dd(t.projectSubPath));case`linked`:if(!V(t.path))throw new fd(t.gitPath,t.path);return z(t.path,dd(t.projectSubPath));case`malformed-pointer`:throw new fd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new pd(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function dd(e){return e===``?`ok`:`ok-${lte(e)}`}function lte(e){let t=e.split(B).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=ute(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function ute(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var fd=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}},pd=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 dte(e){let t;try{t=ud(e)}catch(e){if(e instanceof fd||e instanceof pd)return null;throw e}return V(z(t,`HEAD`))?t:null}function md(e){return`refs/wip/${e}/`}function fte(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 hd=`ok-actor: `;function gd(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),`${hd}${JSON.stringify(i)}`}function _d(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=vd(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 vd(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 pte(e){if(!e)return null;for(let t of e.split(`
|
|
3
3
|
`)){let e=t.trim();if(!e.startsWith(hd))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:_d(n)}return null}function yd(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
4
4
|
`)){let e=n.trim();if(!e.startsWith(hd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=_d(r);i&&t.push(i)}return t}function bd(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 xd(e){let t=yd(e);return t.length>0?t.map(bd):fte(e)}function Sd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function Cd(e){return`reconcile: ${e}`}function wd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Td(e,t){return`park: ${e} -> ${t}`}function Ed(e,t){return`rename: ${e} -> ${t}`}function Dd(e){return`checkpoint: ${e}`}function mte(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const hte=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Od(e){return e.replace(hte,` `)}function kd(e,t){let n=Od(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=Od(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 Ad(e){return cte.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 jd(e){let t=cd(e);if(t.kind!==`linked`)return z(e);try{let n=H(L(t.path,`commondir`),`utf-8`).trim();return n===``?z(e):z(I(z(t.path,n)),t.projectSubPath)}catch{return z(e)}}function Md(e){return e.kind??`other`}function gte(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Nd=class{filePath;log;grants=null;constructor(e,t){this.filePath=L(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Md(t),i=gte(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=Md(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-Bi88qem0.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(H(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 Pd=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],_te={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Fd=`acp-agents.json`,Id=`acp-registry-cache.json`;function Ld(){let e=vu(),t=mu(),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 Rd(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 zd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Rd):null}var Bd=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=zd(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-Bi88qem0.mjs`);await e(this.localDir,{recursive:!0}),await n(L(this.localDir,Id),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=zd(await wu(L(this.localDir,Id),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Vd(e,t){let n;try{n=await wu(L(e,Fd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Fd} 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 ${Fd} entry`)}return i}const Hd={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`},Ud={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`},Wd={cancel_request:`$/cancel_request`},Gd=Symbol(`skippedItem`);function W(e,t){return e.catch(t)}function Kd(e,t){let n=e.catch(t);return O().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Ga):n.parse(e))}function qd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Jd(e,t,n){return e.superRefine((e,r)=>{let i=qd(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 Yd(e,t,n){return O().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Ga}let o=a.data,s=qd(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 Xd(e){return N(e.catch(Gd)).transform(e=>e.filter(e=>e!==Gd))}const Zd=ho([P(),j()]).nullable(),Qd=j(),$d=A({sessionId:Qd,path:j(),content:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),ef=A({sessionId:Qd,path:j(),line:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),tf=j(),nf=ho([k(`read`),k(`edit`),k(`delete`),k(`move`),k(`search`),k(`execute`),k(`think`),k(`fetch`),k(`switch_mode`),k(`other`)]),rf=ho([k(`pending`),k(`in_progress`),k(`completed`),k(`failed`)]),af=A({audience:W(Xd(ho([k(`assistant`),k(`user`)])).nullish(),()=>void 0),lastModified:W(j().nullish(),()=>void 0),priority:W(P().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),vte=A({annotations:W(af.nullish(),()=>void 0),text:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),yte=A({annotations:W(af.nullish(),()=>void 0),data:j(),mimeType:j(),uri:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),bte=A({annotations:W(af.nullish(),()=>void 0),data:j(),mimeType:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),xte=A({annotations:W(af.nullish(),()=>void 0),description:W(j().nullish(),()=>void 0),mimeType:W(j().nullish(),()=>void 0),name:j(),size:W(P().nullish(),()=>void 0),title:W(j().nullish(),()=>void 0),uri:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Ste=ho([A({mimeType:W(j().nullish(),()=>void 0),text:j(),uri:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),A({blob:j(),mimeType:W(j().nullish(),()=>void 0),uri:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)})]),Cte=A({annotations:W(af.nullish(),()=>void 0),resource:Ste,_meta:W(M(j(),O()).nullish(),()=>void 0)}),of=ho([vte.and(A({type:k(`text`)})),yte.and(A({type:k(`image`)})),bte.and(A({type:k(`audio`)})),xte.and(A({type:k(`resource_link`)})),Cte.and(A({type:k(`resource`)}))]),sf=A({content:of,_meta:W(M(j(),O()).nullish(),()=>void 0)}),cf=A({path:j(),oldText:W(j().nullish(),()=>void 0),newText:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),lf=j(),uf=A({terminalId:lf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),df=ho([sf.and(A({type:k(`content`)})),cf.and(A({type:k(`diff`)})),uf.and(A({type:k(`terminal`)}))]),ff=A({path:j(),line:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),pf=A({toolCallId:tf,kind:W(nf.nullish(),()=>void 0),status:W(rf.nullish(),()=>void 0),title:W(j().nullish(),()=>void 0),content:W(Xd(df).nullish(),()=>void 0),locations:W(Xd(ff).nullish(),()=>void 0),rawInput:W(O().optional(),()=>void 0),rawOutput:W(O().optional(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),mf=j(),hf=ho([k(`allow_once`),k(`allow_always`),k(`reject_once`),k(`reject_always`)]),gf=A({sessionId:Qd,toolCall:pf,options:N(A({optionId:mf,name:j(),kind:hf,_meta:W(M(j(),O()).nullish(),()=>void 0)})),_meta:W(M(j(),O()).nullish(),()=>void 0)}),_f=A({name:j(),value:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),vf=A({sessionId:Qd,command:j(),args:W(Xd(j()).optional(),()=>[]),env:W(Xd(_f).optional(),()=>[]),cwd:W(j().nullish(),()=>void 0),outputByteLimit:W(P().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),yf=A({sessionId:Qd,terminalId:lf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),bf=A({sessionId:Qd,terminalId:lf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),xf=A({sessionId:Qd,terminalId:lf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Sf=A({sessionId:Qd,terminalId:lf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Cf=A({sessionId:Qd,toolCallId:W(tf.nullish(),()=>void 0)}),wf=A({requestId:Zd}),Tf=k(`object`),Ef=ho([k(`email`),k(`uri`),k(`date`),k(`date-time`)]),Df=A({const:j(),title:j(),description:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Of=A({title:W(j().nullish(),()=>void 0),description:W(j().nullish(),()=>void 0),minLength:uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:j().nullish(),format:Ef.nullish(),default:W(j().nullish(),()=>void 0),enum:N(j()).nullish(),oneOf:N(Df).nullish(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),kf=A({title:W(j().nullish(),()=>void 0),description:W(j().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:W(P().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Af=A({title:W(j().nullish(),()=>void 0),description:W(j().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:W(P().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),jf=A({title:W(j().nullish(),()=>void 0),description:W(j().nullish(),()=>void 0),default:W(To().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Mf=A({enum:N(j()),_meta:W(M(j(),O()).nullish(),()=>void 0)}),wte=A({anyOf:N(Df),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Tte=Yd(ho([Mf.and(A({type:k(`string`)})),Jd(A({type:j()}),`type`,[`string`]),wte]),`type`,[`string`]),Nf=A({title:W(j().nullish(),()=>void 0),description:W(j().nullish(),()=>void 0),minItems:P().nullish(),maxItems:P().nullish(),items:Tte,default:W(Xd(j()).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Ete=Yd(ho([Of.and(A({type:k(`string`)})),kf.and(A({type:k(`number`)})),Af.and(A({type:k(`integer`)})),jf.and(A({type:k(`boolean`)})),Nf.and(A({type:k(`array`)})),Jd(A({type:j()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Dte=A({type:W(Tf.optional().default(`object`),()=>`object`),title:W(j().nullish(),()=>void 0),properties:M(j(),Ete).optional().default({}),required:N(j()).nullish(),description:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Pf=Eo(ho([Cf,wf]),A({requestedSchema:Dte})),Ff=j(),If=Eo(ho([Cf,wf]),A({elicitationId:Ff,url:No()})),Lf=Yd(Eo(ho([Pf.and(A({mode:k(`form`)})),If.and(A({mode:k(`url`)})),Jd(Eo(ho([Cf,wf]),A({mode:j()})),`mode`,[`form`,`url`])]),A({message:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Rf=j(),Ote=A({serverId:Rf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),zf=j(),Bf=A({connectionId:zf,method:j(),params:M(j(),O()).nullish(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),kte=A({connectionId:zf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Vf=O();A({id:Zd,method:j(),params:ho([$d,ef,gf,vf,yf,bf,xf,Sf,Lf,Ote,Bf,kte,Vf]).nullish()});const Hf=uo().gte(0).lte(65535),Ate=A({image:W(To().optional().default(!1),()=>!1),audio:W(To().optional().default(!1),()=>!1),embeddedContext:W(To().optional().default(!1),()=>!1),_meta:W(M(j(),O()).nullish(),()=>void 0)}),jte=A({http:W(To().optional().default(!1),()=>!1),sse:W(To().optional().default(!1),()=>!1),acp:W(To().optional().default(!1),()=>!1),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Mte=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Nte=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Pte=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Fte=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Ite=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Uf=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Wf=A({list:W(Mte.nullish(),()=>void 0),delete:W(Nte.nullish(),()=>void 0),additionalDirectories:W(Pte.nullish(),()=>void 0),fork:W(Fte.nullish(),()=>void 0),resume:W(Ite.nullish(),()=>void 0),close:W(Uf.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Gf=A({logout:W(A({_meta:W(M(j(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Kf=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),qf=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Jf=A({syncKind:ho([k(`full`),k(`incremental`)]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Yf=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Xf=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Zf=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Qf=A({document:W(A({didOpen:W(qf.nullish(),()=>void 0),didChange:W(Jf.nullish(),()=>void 0),didClose:W(Yf.nullish(),()=>void 0),didSave:W(Xf.nullish(),()=>void 0),didFocus:W(Zf.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),$f=A({maxCount:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),ep=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),tp=A({maxCount:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),np=A({maxCount:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),rp=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),ip=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),ap=A({recentFiles:W($f.nullish(),()=>void 0),relatedSnippets:W(ep.nullish(),()=>void 0),editHistory:W(tp.nullish(),()=>void 0),userActions:W(np.nullish(),()=>void 0),openFiles:W(rp.nullish(),()=>void 0),diagnostics:W(ip.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),op=A({events:W(Qf.nullish(),()=>void 0),context:W(ap.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),sp=ho([k(`utf-16`),k(`utf-32`),k(`utf-8`)]),cp=A({loadSession:W(To().optional().default(!1),()=>!1),promptCapabilities:W(Ate.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(jte.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(Wf.optional().default({}),()=>({})),auth:W(Gf.optional().default({}),()=>({})),providers:W(Kf.nullish(),()=>void 0),nes:W(op.nullish(),()=>void 0),positionEncoding:W(sp.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),lp=j(),up=A({name:j(),label:W(j().nullish(),()=>void 0),secret:W(To().optional().default(!0),()=>!0),optional:W(To().optional().default(!1),()=>!1),_meta:W(M(j(),O()).nullish(),()=>void 0)}),dp=A({id:lp,name:j(),description:W(j().nullish(),()=>void 0),vars:Kd(Xd(up),()=>[]),link:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),fp=A({id:lp,name:j(),description:W(j().nullish(),()=>void 0),args:W(Xd(j()).optional(),()=>[]),env:W(M(j(),j()).optional(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),pp=A({id:lp,name:j(),description:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),mp=ho([dp.and(A({type:k(`env_var`)})),fp.and(A({type:k(`terminal`)})),pp]),hp=A({name:j(),title:W(j().nullish(),()=>void 0),version:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),gp=A({protocolVersion:Hf,agentCapabilities:W(cp.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:W(Xd(mp).optional().default([]),()=>[]),agentInfo:W(hp.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),_p=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),vp=j(),yp=ho([k(`anthropic`),k(`openai`),k(`azure`),k(`vertex`),k(`bedrock`),j()]),bp=A({apiType:yp,baseUrl:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),xp=A({providers:N(A({providerId:vp,supported:Kd(Xd(yp),()=>[]),required:To(),current:bp.nullish(),_meta:W(M(j(),O()).nullish(),()=>void 0)})),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Sp=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Cp=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),wp=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Tp=j(),Ep=A({currentModeId:Tp,availableModes:Kd(Xd(A({id:Tp,name:j(),description:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)})),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Dp=j(),Op=ho([k(`mode`),k(`model`),k(`model_config`),k(`thought_level`),j()]),kp=j(),Ap=A({value:kp,name:j(),description:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),jp=A({group:j(),name:j(),options:Kd(Xd(Ap),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Mp=A({currentValue:kp,options:ho([N(Ap),N(jp)])}),Np=A({currentValue:To()}),Pp=Eo(ho([Mp.and(A({type:k(`select`)})),Np.and(A({type:k(`boolean`)}))]),A({id:Dp,name:j(),description:W(j().nullish(),()=>void 0),category:W(Op.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)})),Fp=A({sessionId:Qd,modes:W(Ep.nullish(),()=>void 0),configOptions:W(Xd(Pp).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Ip=A({modes:W(Ep.nullish(),()=>void 0),configOptions:W(Xd(Pp).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Lp=A({sessions:Kd(Xd(A({sessionId:Qd,cwd:j(),additionalDirectories:W(Xd(j()).optional(),()=>[]),title:W(j().nullish(),()=>void 0),updatedAt:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Rp=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),zp=A({sessionId:Qd,modes:W(Ep.nullish(),()=>void 0),configOptions:W(Xd(Pp).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Bp=A({modes:W(Ep.nullish(),()=>void 0),configOptions:W(Xd(Pp).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Vp=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Hp=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Up=A({configOptions:Kd(Xd(Pp),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Wp=A({stopReason:ho([k(`end_turn`),k(`max_tokens`),k(`max_turn_requests`),k(`refusal`),k(`cancelled`)]),usage:W(A({totalTokens:P(),inputTokens:P(),outputTokens:P(),thoughtTokens:W(P().nullish(),()=>void 0),cachedReadTokens:W(P().nullish(),()=>void 0),cachedWriteTokens:W(P().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Gp=A({sessionId:Qd,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Kp=j(),qp=A({line:uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Jp=A({start:qp,end:qp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Yp=A({range:Jp,newText:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Xp=A({id:Kp,uri:j(),edits:N(Yp),cursorPosition:W(qp.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Zp=A({id:Kp,uri:j(),position:qp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Qp=A({id:Kp,uri:j(),position:qp,newName:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),$p=A({id:Kp,uri:j(),search:j(),replace:j(),isRegex:To().nullish(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),em=A({suggestions:N(ho([Xp.and(A({kind:k(`edit`)})),Zp.and(A({kind:k(`jump`)})),Qp.and(A({kind:k(`rename`)})),$p.and(A({kind:k(`searchAndReplace`)}))])),_meta:W(M(j(),O()).nullish(),()=>void 0)}),tm=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),nm=O(),rm=O(),im=A({code:ho([k(-32700),k(-32600),k(-32601),k(-32602),k(-32603),k(-32800),k(-32e3),k(-32002),uo().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:j(),data:W(O().optional(),()=>void 0)});ho([A({id:Zd,result:ho([gp,_p,xp,Sp,Cp,wp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,em,tm,nm,rm])}),A({id:Zd,error:im})]);const am=A({content:of,messageId:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),om=A({toolCallId:tf,title:j(),kind:W(nf.optional(),()=>void 0),status:W(rf.optional(),()=>void 0),content:W(Xd(df).optional(),()=>[]),locations:W(Xd(ff).optional(),()=>[]),rawInput:W(O().optional(),()=>void 0),rawOutput:W(O().optional(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),sm=ho([k(`high`),k(`medium`),k(`low`)]),cm=ho([k(`pending`),k(`in_progress`),k(`completed`)]),lm=A({content:j(),priority:sm,status:cm,_meta:W(M(j(),O()).nullish(),()=>void 0)}),um=A({entries:Kd(Xd(lm),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),dm=j(),fm=A({planId:dm,entries:Kd(Xd(lm),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),pm=A({planId:dm,uri:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),mm=A({planId:dm,content:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),hm=A({plan:ho([fm.and(A({type:k(`items`)})),pm.and(A({type:k(`file`)})),mm.and(A({type:k(`markdown`)}))]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),gm=A({planId:dm,_meta:W(M(j(),O()).nullish(),()=>void 0)}),_m=A({hint:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),vm=A({availableCommands:Kd(Xd(A({name:j(),description:j(),input:W(_m.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)})),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),ym=A({currentModeId:Tp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),bm=A({configOptions:Kd(Xd(Pp),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),xm=A({title:W(j().nullish(),()=>void 0),updatedAt:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Sm=A({amount:P(),currency:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Cm=A({used:P(),size:P(),cost:W(Sm.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),wm=A({sessionId:Qd,update:ho([am.and(A({sessionUpdate:k(`user_message_chunk`)})),am.and(A({sessionUpdate:k(`agent_message_chunk`)})),am.and(A({sessionUpdate:k(`agent_thought_chunk`)})),om.and(A({sessionUpdate:k(`tool_call`)})),pf.and(A({sessionUpdate:k(`tool_call_update`)})),um.and(A({sessionUpdate:k(`plan`)})),hm.and(A({sessionUpdate:k(`plan_update`)})),gm.and(A({sessionUpdate:k(`plan_removed`)})),vm.and(A({sessionUpdate:k(`available_commands_update`)})),ym.and(A({sessionUpdate:k(`current_mode_update`)})),bm.and(A({sessionUpdate:k(`config_option_update`)})),xm.and(A({sessionUpdate:k(`session_info_update`)})),Cm.and(A({sessionUpdate:k(`usage_update`)}))]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Tm=A({elicitationId:Ff,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Em=A({connectionId:zf,method:j(),params:W(M(j(),O()).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Dm=O();A({method:j(),params:ho([wm,Tm,Em,Dm]).nullish()});const Om=A({readTextFile:W(To().optional().default(!1),()=>!1),writeTextFile:W(To().optional().default(!1),()=>!1),_meta:W(M(j(),O()).nullish(),()=>void 0)}),km=A({configOptions:W(A({boolean:W(A({_meta:W(M(j(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Am=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),jm=A({terminal:W(To().optional().default(!1),()=>!1),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Mm=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Nm=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Pm=A({form:W(Mm.nullish(),()=>void 0),url:W(Nm.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Fm=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Im=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Lm=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Rm=A({jump:W(Fm.nullish(),()=>void 0),rename:W(Im.nullish(),()=>void 0),searchAndReplace:W(Lm.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),zm=A({protocolVersion:Hf,clientCapabilities:W(A({fs:W(Om.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(To().optional().default(!1),()=>!1),session:W(km.nullish(),()=>void 0),plan:W(Am.nullish(),()=>void 0),auth:W(jm.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(Pm.nullish(),()=>void 0),nes:W(Rm.nullish(),()=>void 0),positionEncodings:W(Xd(sp).optional(),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:W(hp.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Bm=A({methodId:lp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Vm=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Hm=A({providerId:vp,apiType:yp,baseUrl:j(),headers:M(j(),j()).optional(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Um=A({providerId:vp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Wm=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),Gm=A({name:j(),value:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Lte=A({name:j(),url:j(),headers:N(Gm),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Rte=A({name:j(),url:j(),headers:N(Gm),_meta:W(M(j(),O()).nullish(),()=>void 0)}),zte=A({name:j(),serverId:Rf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Bte=A({name:j(),command:j(),args:N(j()),env:N(_f),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Km=ho([Lte.and(A({type:k(`http`)})),Rte.and(A({type:k(`sse`)})),zte.and(A({type:k(`acp`)})),Bte]),qm=A({cwd:j(),additionalDirectories:W(Xd(j()).optional(),()=>[]),mcpServers:Kd(Xd(Km),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Jm=A({mcpServers:Kd(Xd(Km),()=>[]),cwd:j(),additionalDirectories:W(Xd(j()).optional(),()=>[]),sessionId:Qd,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Ym=A({cwd:j().nullish(),cursor:j().nullish(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Xm=A({sessionId:Qd,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Zm=A({sessionId:Qd,cwd:j(),additionalDirectories:W(Xd(j()).optional(),()=>[]),mcpServers:W(Xd(Km).optional(),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Qm=A({sessionId:Qd,cwd:j(),additionalDirectories:W(Xd(j()).optional(),()=>[]),mcpServers:W(Xd(Km).optional(),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),$m=A({sessionId:Qd,_meta:W(M(j(),O()).nullish(),()=>void 0)}),eh=A({sessionId:Qd,modeId:Tp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),th=Eo(ho([A({value:To(),type:k(`boolean`)}),A({value:kp})]),A({sessionId:Qd,configId:Dp,_meta:W(M(j(),O()).nullish(),()=>void 0)})),nh=A({sessionId:Qd,prompt:N(of),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Vte=A({uri:j(),name:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Hte=A({name:j(),owner:j(),remoteUrl:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),rh=A({workspaceUri:W(j().nullish(),()=>void 0),workspaceFolders:N(Vte).nullish(),repository:W(Hte.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Ute=ho([k(`automatic`),k(`diagnostic`),k(`manual`)]),Wte=A({uri:j(),languageId:j(),text:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Gte=A({startLine:uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Kte=A({uri:j(),excerpts:N(Gte),_meta:W(M(j(),O()).nullish(),()=>void 0)}),qte=A({uri:j(),diff:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Jte=A({action:j(),uri:j(),position:qp,timestampMs:P(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Yte=A({uri:j(),languageId:j(),visibleRange:W(Jp.nullish(),()=>void 0),lastFocusedMs:W(P().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Xte=ho([k(`error`),k(`warning`),k(`information`),k(`hint`)]),Zte=A({uri:j(),range:Jp,severity:Xte,message:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),Qte=A({recentFiles:N(Wte).nullish(),relatedSnippets:N(Kte).nullish(),editHistory:N(qte).nullish(),userActions:N(Jte).nullish(),openFiles:N(Yte).nullish(),diagnostics:N(Zte).nullish(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),ih=A({sessionId:Qd,uri:j(),version:P(),position:qp,selection:Jp.nullish(),triggerKind:Ute,context:Qte.nullish(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),ah=A({sessionId:Qd,_meta:W(M(j(),O()).nullish(),()=>void 0)});A({id:Zd,method:j(),params:ho([zm,Bm,Vm,Hm,Um,Wm,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,Bf,Vf]).nullish()});const $te=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),ene=A({content:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),tne=A({optionId:mf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),nne=A({outcome:ho([A({outcome:k(`cancelled`)}),tne.and(A({outcome:k(`selected`)}))]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),rne=A({terminalId:lf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),ine=A({exitCode:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),ane=A({output:j(),truncated:To(),exitStatus:W(ine.nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),one=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),sne=A({exitCode:W(uo().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(j().nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)}),cne=A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),lne=ho([j(),P(),P(),To(),N(j())]),oh=A({content:M(j(),lne).nullish()});ho([A({id:Zd,result:ho([$te,ene,nne,rne,ane,one,sne,cne,Yd(Eo(ho([oh.and(A({action:k(`accept`)})),A({action:k(`decline`)}),A({action:k(`cancel`)}),Jd(A({action:j()}),`action`,[`accept`,`cancel`,`decline`])]),A({_meta:W(M(j(),O()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),A({connectionId:zf,_meta:W(M(j(),O()).nullish(),()=>void 0)}),A({_meta:W(M(j(),O()).nullish(),()=>void 0)}),rm,nm])}),A({id:Zd,error:im})]);const sh=A({sessionId:Qd,_meta:W(M(j(),O()).nullish(),()=>void 0)}),ch=A({sessionId:Qd,uri:j(),languageId:j(),version:P(),text:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),une=A({range:Jp.nullish(),text:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),lh=A({sessionId:Qd,uri:j(),version:P(),contentChanges:Kd(Xd(une),()=>[]),_meta:W(M(j(),O()).nullish(),()=>void 0)}),uh=A({sessionId:Qd,uri:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),dh=A({sessionId:Qd,uri:j(),_meta:W(M(j(),O()).nullish(),()=>void 0)}),fh=A({sessionId:Qd,uri:j(),version:P(),position:qp,visibleRange:Jp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),ph=A({sessionId:Qd,id:Kp,_meta:W(M(j(),O()).nullish(),()=>void 0)}),mh=A({sessionId:Qd,id:Kp,reason:W(ho([k(`rejected`),k(`ignored`),k(`replaced`),k(`cancelled`)]).nullish(),()=>void 0),_meta:W(M(j(),O()).nullish(),()=>void 0)});A({method:j(),params:ho([sh,ch,lh,uh,dh,fh,ph,mh,Em,Dm]).nullish()}),A({requestId:Zd,_meta:W(M(j(),O()).nullish(),()=>void 0)}),Pf.and(A({mode:k(`form`)})).and(A({message:j()})),If.and(A({mode:k(`url`)})).and(A({message:j()})),ho([Cf,wf]).and(A({message:j()})),Of.and(A({type:k(`string`)})),kf.and(A({type:k(`number`)})),Af.and(A({type:k(`integer`)})),jf.and(A({type:k(`boolean`)})),Nf.and(A({type:k(`array`)})),Mf.and(A({type:k(`string`)})),oh.and(A({action:k(`accept`)})),A({action:k(`decline`)}),A({action:k(`cancel`)});const hh=`$/cancel_request`;function gh(e){return typeof e==`object`&&!!e}function dne(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function fne(e){if(!(!gh(e)||!dne(e.requestId)))return e.requestId}const _h={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function vh(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function pne(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function mne(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 yh(e){if(e instanceof Sh)return e.toResult();if(mne(e))return Sh.invalidParams(e.format()).toResult();let t=pne(e);try{return Sh.internalError(t?JSON.parse(t):{}).toResult()}catch{return Sh.internalError({details:t}).toResult()}}function hne(e){return e instanceof Sh&&e.code===-32800?e:Sh.requestCancelled(e)}function gne(e,t){let n=_ne(e,t);return n?n.toResult():yh(e)}function _ne(e,t){if(!(!t.aborted||!vne(e)))return hne(t.reason)}function vne(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var yne=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 Sh?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?vh(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},bh=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},bne=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}},xh=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new bne(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 xne}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 bh(()=>{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 vh(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(hh,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?vh(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 _h.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(!gh(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(Sh.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(gne(n,t.responder.signal));else{let t=yh(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 yne(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&&gh(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new Sh(n,r,i))}else t.reject(Sh.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==hh)return;let t=fne(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(Sh.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?vh(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)}},xne=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)??_h.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?_h.no(r):await n(t(r.params),r.responder,i)??_h.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?_h.no(r):await n(t(r.params),i)??_h.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new xh(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},Sh=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}}},Sne=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 Cne(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Sne,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);gh(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)+`
|
|
@@ -1212,7 +1212,7 @@ tags: [lore, history]
|
|
|
1212
1212
|
`:``)+t).md;sS(x.dc.document,i,`agent`,void 0,C),XC(`mcp-write`),ee=!0}E=!0},x.origin)})}finally{Le?.touchMode(c,`idle`)}if(T){let e;switch(T.kind){case`invalid_value`:e={[T.key]:T.reason};break;case`reserved_key`:e={[T.key]:`'${T.key}' is reserved`};break;case`unknown_key`:e={[T.key]:`'${T.key}' is not a recognized key`};break;case`duplicate_target`:e={[T.key]:`'${T.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${T.expected.join(`, `)}; got: ${T.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${T.bytes} > ${T.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${T.reason}`};break;case`invalid_path`:e={[T.path.map(String).join(`.`)||`__path__`]:T.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(T)})`}}K(r,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(E&&te.length>0){if(yF(o,c,l,u,void 0,Zr({clientName:d,clientVersion:f,label:p}),b),ES(),si(v),ee){let e=await Bn(o);if(e?.kind===`failure`){Vn(r,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Hn(r,`frontmatter-patch`);return}}zn(o,`frontmatter-patch`)}Pe?.setFocus(c,{agentName:l,currentDoc:o,writeKind:`write`,ts:Date.now()}),Be?.();let ne=Mn(o),re=Nn();re===0&&nX().add(1,{"shadow.writer":`agent`,"agent.type":Qh(d)});let ie=Wn(S);pr(o,x.dc.document.getText(`source`).toString());let ae=await er();ae.add(o);let oe=nH(x.dc.document.getText(`source`).toString(),o,ae,fr);J(r,200,_,{timestamp:w,subscriberCount:ne,systemSubscriberCount:re,appliedKeys:te,...y?{summary:y}:{},...ie?{warning:ie,warnings:[ie]}:{},brokenLinks:oe},{handler:`frontmatter-patch`})}catch(e){if(e instanceof nE){K(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e,requestId:MC(n)},`[frontmatter-patch] handler failed`),K(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ti(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 Ai=q(jn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!DZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let r=Dn(n);if(dC(r)||fC(r)){K(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){J(t,200,yr,{docName:r,content:i.getText(`source`).toString(),lifecycle:Ti(i)},{handler:`document-read`});return}if(!V(eZ(g,`file`,r))){K(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){K(t,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}J(t,200,yr,{docName:r,content:e.getText(`source`).toString(),lifecycle:Ti(e)},{handler:`document-read`})}finally{await o.disconnect()}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),ji=q(jn,async(e,t)=>{try{gt&&await gt.catch(e=>{X.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{PX(g,r)}catch{K(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(i&<&&WX(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=LC(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=LX(),n=GX({contentDir:g,contentFilter:lt,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:l}=c.value;l&&X.info({handler:`document-list`,maxEntries:t,count:s},`[document-list][showAll] stream truncated at entry cap`),await i(`${JSON.stringify({type:`complete`,truncated:l,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}):X.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(i&<){let e=`showAll:${o===1?`d1:`:``}${a?`ok:`:``}${r??``}`,n=Vt.get(e);if(!n){let t=new AbortController,i=(async()=>{let e=[],n=LX(),{truncated:i}=await KX({contentDir:g,contentFilter:lt,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&&X.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;Vt.set(e,s),i.finally(()=>{Vt.get(e)===s&&Vt.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(),Vt.get(e)===i&&Vt.delete(e)))};t.on(`close`,c);try{let{documents:e,truncated:n}=await i.promise;if(s)return;J(t,200,Kr,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(s)return;K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,c)}return}let s=x(),c=C(),l=te?.()??new Map,u=[];for(let[e,t]of l)r&&!e.startsWith(`${r}/`)&&e!==r||u.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let d=[];try{let e=tn(s);Wt?.signature!==e&&(Wt={signature:e,assets:lM({contentDir:g,fileIndex:s,readMarkdown:e=>{try{return H(e,`utf-8`)}catch{return null}},isExcluded:lt?e=>lt.isPathIgnored(e):void 0})}),d=Wt?.assets??[]}catch(e){Wt=null,X.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let f=new Set;for(let e of d)r&&!e.path.startsWith(`${r}/`)&&e.path!==r||(f.add(e.path),u.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=EC(e);u.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=Ej(R(g,t.canonicalPath));u.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}/`))&&!f.has(e)){let n=FX(e);u.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}/`))||f.has(n))continue;let i=Ej(R(g,t.canonicalPath)),a=FX(n);u.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}}let p=oe?.()??new Map;if(p.size>0){let e=e=>!r||e===r||e.startsWith(`${r}/`),t=new Map;for(let[e,n]of p){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,r]of t){let t=l.get(n),i=t?Ej(R(g,t.canonicalPath)):n;for(let a of r)e(a)&&u.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 l)n(e,n=>{u.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:Ej(R(g,t.canonicalPath))})});for(let[e,t]of c)n(e,n=>{let r=Ej(R(g,t.canonicalPath));if(t.kind===`markdown`)u.push({kind:`document`,docName:n,docExt:EC(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=FX(n);u.push({kind:`file`,docName:n,path:n,docExt:`.${i}`,assetExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r})}})}u.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),J(t,200,Kr,{documents:u},{handler:`document-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Mi=q(jn,async(e,t)=>{if(!ke){K(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){K(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!DZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}J(t,200,Aee,{docName:n,backlinks:(await ke.getBacklinks(n)).map(e=>({source:e.source,anchor:e.anchor,title:dn(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){lr(t,e,{handler:`backlinks`,failureTitle:`Failed to read backlinks.`})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Fi=q(jn,async(e,t)=>{try{let e=jd(D??g),n=kO({projectDir:e}),r=new Set(nV(g).map(e=>e.name)),i=new Set(rV(nc).map(e=>e.name));J(t,200,Uee,{...n,skills:n.skills.filter(t=>ca(t.provenance,e)&&!(t.provenance.scope===`project`?r.has(t.name):i.has(t.name)))},{handler:`skills-installed`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to enumerate installed skills.`,{handler:`skills-installed`,cause:e})}},{handler:`skills-installed`,method:`GET`,skipBodyParse:!0}),Ri=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`q`)?.trim()??``;if(n.length<2){K(t,400,`urn:ok:error:invalid-request`,`Search query must be at least 2 characters.`,{handler:`skills-search`});return}try{let e=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(n)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(e.ok){J(t,200,u,{results:oO(await e.json()),backend:`skills.sh`,degraded:!1},{handler:`skills-search`});return}X.warn({status:e.status},`skills.sh search unavailable — falling back to GitHub topic search`)}catch(e){X.warn({err:e},`skills.sh search failed — falling back to GitHub topic search`)}try{let e=encodeURIComponent(`${n} topic:agent-skills`),r=await fetch(`https://api.github.com/search/repositories?q=${e}&per_page=30`,{signal:AbortSignal.timeout(8e3),headers:{Accept:`application/vnd.github+json`}});if(!r.ok){X.warn({status:r.status},`GitHub skill search fallback returned non-ok`),K(t,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,detail:`GitHub fallback returned ${r.status}.`});return}J(t,200,u,{results:Ooe(await r.json()),backend:`github-fallback`,degraded:!0},{handler:`skills-search`})}catch(e){K(t,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,cause:e})}},{handler:`skills-search`,method:`GET`,skipBodyParse:!0}),zi=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=Number(n.searchParams.get(`limit`)),i=Number.isFinite(r)&&r>0?Math.min(Math.floor(r),60):24;try{let e=await YJ(i);J(t,200,u,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-popular`})}catch(e){K(t,502,`urn:ok:error:internal-server-error`,`Popular skills are temporarily unavailable.`,{handler:`skills-popular`,cause:e})}},{handler:`skills-popular`,method:`GET`,skipBodyParse:!0}),Bi=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`source`)?.trim()??``,i=n.searchParams.get(`name`)?.trim()??``;if(!r||!i){K(t,400,`urn:ok:error:invalid-request`,`source and name are required.`,{handler:`skills-detail`});return}let a=ga(r,i);if(!a){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized skill source.`,{handler:`skills-detail`});return}let{skillsUrl:o,sourceKind:s,sourceUrl:c}=a,l={},u=!1;try{let e=await fetch(o,{signal:AbortSignal.timeout(8e3)});e.ok&&(u=!0,l=Doe(await e.text()))}catch(e){X.warn({err:e,skillsUrl:o},`skills.sh detail fetch failed — degrading to repo link`)}J(t,200,Jt,{title:l.title??i,description:l.description??``,image:l.image??null,skillsUrl:u?o:null,sourceKind:s,sourceUrl:c},{handler:`skills-detail`})},{handler:`skills-detail`,method:`GET`,skipBodyParse:!0}),Vi=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`source`)?.trim()??``,i=n.searchParams.get(`name`)?.trim()??``;if(!r){K(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-preview`});return}let a=null;try{a=await lO(r,i||void 0)}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not resolve source.`,{handler:`skills-preview`,cause:e});return}throw e}let o=a?.spec??qD(r);if(!o){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized preview source.`,{handler:`skills-preview`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(ZY(t,o,`skills-preview`))return;let s;try{let e=await YD(o);s=e.cleanup;let n=aO(e.dir);if(n.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-preview`});return}let a=n[0];if(i){let e=n.find(e=>e.name===i)??n.find(e=>nO(e.dir)?.name===i);if(!e){K(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skills-preview`,detail:`"${i}" not among: ${n.map(e=>e.name).join(`, `)}.`});return}a=e}let c=rO(a.dir);if(c){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle is too large.`,{handler:`skills-preview`,detail:c});return}let l=iO(a.dir);if(!l){K(t,404,`urn:ok:error:not-found`,`SKILL.md unreadable in source.`,{handler:`skills-preview`});return}let u=EO(r),d=Yoe(e.dir);J(t,200,re,{name:l.name,description:l.description,skillMd:l.skillMd,files:l.files.map(e=>({relPath:e.relPath,content:e.content})),plugin:u??void 0,pluginBundle:d??void 0},{handler:`skills-preview`})}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-preview`,cause:e});return}K(t,502,`urn:ok:error:internal-server-error`,`Preview is unavailable.`,{handler:`skills-preview`,cause:e})}finally{s?.()}},{handler:`skills-preview`,method:`GET`,skipBodyParse:!0}),Gi=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!n){K(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-discover`});return}let r=cO(n);if(r){try{J(t,200,le,{skills:await hoe(`https://${r.hostname}`)},{handler:`skills-discover`})}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}throw e}return}let i=qD(n);if(!i){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized source.`,{handler:`skills-discover`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if(ZY(t,i,`skills-discover`))return;let a;try{let e=await YD(i);a=e.cleanup,J(t,200,le,{skills:aO(e.dir).map(e=>{let t=nO(e.dir);return{name:t?.name??e.name,description:t?.description??null}})},{handler:`skills-discover`})}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}K(t,502,`urn:ok:error:internal-server-error`,`Discovery is unavailable.`,{handler:`skills-discover`,cause:e})}finally{a?.()}},{handler:`skills-discover`,method:`GET`,skipBodyParse:!0}),Ki=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`ref`)?.trim()??``,i=n.searchParams.get(`from`)?.trim()??``,a=n.searchParams.get(`scope`)?.trim()===`global`?`global`:`project`;if(!r||!nt.test(r)||r.length>64){K(t,400,`urn:ok:error:invalid-request`,`A valid ref is required.`,{handler:`skills-resolve-ref`});return}try{let e=e=>J(t,200,St,e,{handler:`skills-resolve-ref`});for(let t of[a,a===`project`?`global`:`project`]){let n=ic(t,r);if(n!==null){e({kind:`local`,scope:t,name:r,dir:R(t===`project`?g:nc,n).split(B).join(`/`)});return}}let n=a===`project`?D:nc,o=i&&n?Jc(L(n,...XD)).skills[i]:void 0;if(o?.source){let t=(await lO(o.source,r))?.spec??qD(o.source),n=t&&!(t.kind===`git`&&!mG(t.url));if(t&&n){let n;try{let i=await YD(t);if(n=i.cleanup,aO(i.dir).map(e=>nO(e.dir)?.name??e.name).includes(r)){e({kind:`import`,source:o.source,ref:r,via:`source`});return}}catch(e){X.debug({err:e,ref:r,from:i,source:o.source},`resolve-ref: source rung unreachable, falling through to publisher`)}finally{n?.()}}}if(o?.publisher)try{let t=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(r)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(t.ok){let n=oO(await t.json()).filter(e=>e.name===r&&e.publisher===o.publisher);if(n.length===1){let t=n[0];if(t){e({kind:`import`,source:t.source,ref:r,via:`publisher`});return}}}}catch(e){X.debug({err:e,ref:r,publisher:o.publisher},`resolve-ref: skills.sh unavailable, no publisher resolution`)}e({kind:`none`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Could not resolve the reference.`,{handler:`skills-resolve-ref`,cause:e instanceof Error?e:Error(String(e))})}},{handler:`skills-resolve-ref`,method:`GET`,skipBodyParse:!0}),$i=q(jn,async(e,t)=>{if(!ke){K(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){K(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let r=n.split(`,`).map(e=>e.trim()).filter(e=>e&&DZ(e));J(t,200,Cee,{counts:await ke.getBacklinkCounts(r)},{handler:`backlink-counts`})}catch(e){lr(t,e,{handler:`backlink-counts`,failureTitle:`Failed to read backlink counts.`})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),ta=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`prefix`),i=n.searchParams.get(`docNames`);if(r===null&&i===null){K(t,400,`urn:ok:error:invalid-request`,`Missing docNames or prefix parameter.`,{handler:`comment-counts`});return}let a={};if(r!==null){let e=r.trim();if(e!==``&&!DZ(e)){K(t,400,`urn:ok:error:invalid-request`,`Invalid prefix parameter.`,{handler:`comment-counts`});return}a=Object.fromEntries(await un.countThreads({prefix:e}))}else{let e=(i??``).split(`,`).map(e=>e.trim()).filter(e=>e!==``&&DZ(e));a=Object.fromEntries(await un.countThreads({docNames:e}))}J(t,200,pi,{counts:a},{handler:`comment-counts`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read comment counts.`,{handler:`comment-counts`,cause:e})}},{handler:`comment-counts`,method:`GET`,skipBodyParse:!0}),na=q(jn,async(e,t)=>{if(!ke){K(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){K(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!DZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=await er();J(t,200,Nee,{docName:n,forwardLinks:(await ke.getForwardLinkEntries(n)).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:fn(e.target,r),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){lr(t,e,{handler:`forward-links`,failureTitle:`Failed to read forward links.`})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),ia=q(jn,async(e,t)=>{if(!ke){K(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&&!DZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){K(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){K(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:a,links:o}=await ke.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=await ke.getLinkGraph());let s=await er();J(t,200,On,{nodes:a.map(e=>{if(e.kind===`doc`){let t=bn(e.docName,s);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:fn(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){lr(t,e,{handler:`link-graph`,failureTitle:`Failed to read link graph.`})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),oa=q(jn,async(e,t)=>{if(!ke){K(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(!CH(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}J(t,200,c,{orphans:(await ke.getOrphans([...x().keys()],n)).map(e=>({docName:e,title:dn(e)}))},{handler:`orphans`})}catch(e){lr(t,e,{handler:`orphans`,failureTitle:`Failed to read orphan pages.`})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),sa=q(jn,async(e,t)=>{if(!ke){K(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=await er();J(t,200,iee,{hubs:(await ke.getHubs(i)).map(e=>({docName:e.docName,title:fn(e.docName,a),count:e.count}))},{handler:`hubs`})}catch(e){lr(t,e,{handler:`hubs`,failureTitle:`Failed to read hub pages.`})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),la=q(jn,async(e,t)=>{if(!ke){K(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||!DZ(e))){K(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>Dn(e)))]:void 0;J(t,200,xee,{deadLinks:(await ke.getDeadLinks(await er(),r)).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:dn(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){lr(t,e,{handler:`dead-links`,failureTitle:`Failed to read dead links.`})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),ua=q(tee,async(n,r,i)=>{try{let{find:n,replace:o,offset:c}=i,l=QX(i.docName,r,`agent-patch`);if(l===null)return;let u=Dn(l),{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:h,label:_}=Xr(i);if(aX(n)){iX().add(1,{result:`rejected`}),K(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(dC(u)||fC(u)){K(r,400,`urn:ok:error:reserved-doc-name`,`'${u}' is a reserved document name.`,{handler:`agent-patch`});return}let v=pj(i.summary),y=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),b=VH(t,a,u,g,e.resolveEmbed,Xe?.()),x=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:u}:void 0,S;{let{frontmatter:e,body:t}=rr(y.dc.document.getText(`source`).toString()),r=Xi(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);S=await KT(y.dc.document,rr(e).body,`patch`,x)}}let C=new Date().toISOString(),w=!1,T=!1,E=!1,ee,te;try{let e=tr(m),t=Jn[e]??Lr(p??d);if(Le?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),te=dj(y.dc.document.getText(`source`),d,y.origin,p,m),y.dc.document.transact(()=>{let{frontmatter:e,body:t}=rr(y.dc.document.getText(`source`).toString()),r=Xi(e,t),i=c==null?r.indexOf(n):r.slice(c,c+n.length)===n?c:-1;if(i===-1){c==null?w=!0:T=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":u,findLength:n.length,replaceLength:o.length,hadOffset:c!=null})),uie();return}if(i<e.length){E=!0;return}let{body:a}=rr(r.slice(0,i)+o+r.slice(i+n.length)),s=XT(y.dc.document);ee=YT(y.dc.document,a,`patch`,x,S,qT(y));let l=ir(s,XT(y.dc.document))??void 0;y.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Patched (${f}): ${n.slice(0,50)}`,...l===void 0?{}:{changedBlocks:l}})},y.origin),ee!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":u,position:`patch`,intendedBytes:ee.intendedBytes,actualBytes:ee.actualBytes,byteDelta:ee.byteDelta,"agent.id":d,"agent.client_name":m})),!w&&!T&&!E){let{stored:e}=ii(v);yF(u,d,f,p,void 0,Zr({clientName:m,clientVersion:h,label:_}),e),ES(),si(v),gX(`agent-patch`,ee)}}finally{te?.(),Le?.touchMode(d,`idle`)}if(T){K(r,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(w){K(r,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(E){iX().add(1,{result:`rejected`}),K(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 ne=await Bn(u);if(ne?.kind===`failure`){Vn(r,ne.failure,`agent-patch`);return}if(ne?.kind===`divergence`){Hn(r,`agent-patch`);return}zn(u,`agent-patch`),Pe?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`edit`,ts:Date.now()}),Be?.();let re=Mn(u),ie=Nn();ie===0&&nX().add(1,{"shadow.writer":`agent`,"agent.type":Qh(m)});let{response:ae}=ii(v),oe=y.dc.document.getText(`source`).toString();pr(u,oe);let se=await yR(oe,u),ce=await er();ce.add(u);let le=nH(oe,u,ce,fr),ue=Wn(b),de=ee===void 0?void 0:WC(ee),fe=[...de?[de]:[],...ue?[ue]:[],...se??[],...await Cu(y.dc.document.getText(`source`).toString(),u)];J(r,200,Pr,{timestamp:C,subscriberCount:re,systemSubscriberCount:ie,...ae?{summary:ae}:{},...de?{warning:de}:ue?{warning:ue}:{},...fe.length>0?{warnings:fe}:{},brokenLinks:le},{handler:`agent-patch`})}catch(e){if(e instanceof BC){VC(r,e,`agent-patch`);return}if(e instanceof GC){qC(r,e,`agent-patch`);return}if(e instanceof nE){K(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e,requestId:MC(n)},`[agent-patch] handler failed`),K(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),fa=q(f,async(t,n,r)=>{try{let t=QX(r.docName,n,`agent-undo`);if(t===null)return;let i=Dn(t),{agentId:a,agentName:o,colorSeed:c,clientName:l,clientVersion:u,label:d}=Xr(r);if(dC(i)||fC(i)){K(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)){K(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=tr(l),n=Jn[t]??Lr(c??a);Le?.setPresence(a,{displayName:o,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),g=noe(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,m),g&&yF(i,f,o,c,void 0,Zr({clientName:l,clientVersion:u,label:d}))}finally{Le?.touchMode(a,`idle`)}if(g){let e=await Bn(i);if(e?.kind===`failure`){Vn(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Hn(n,`agent-undo`);return}Rn(i,`agent-undo`)}Pe?.setFocus(f,{agentName:f,currentDoc:i,writeKind:`undo`,ts:Date.now()}),J(n,200,Bee,{docName:i,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof BC){VC(n,e,`agent-undo`);return}X.error({err:e,requestId:MC(t)},`[agent-undo] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),ma=q(jn,async(e,t)=>{try{let n=Yh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){K(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}J(t,200,me,tT(s,n),{handler:`agent-activity`})}catch(n){X.error({err:n,requestId:MC(e)},`[agent-activity] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),ha=q(jn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=Yh(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),a=n.searchParams.get(`keptCount`);if(r===null){K(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){K(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!DZ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let o=Dn(i);if(dC(o)||fC(o)){K(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))){K(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){K(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){K(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){K(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}=Qw(u.undoStack,c,d,o);J(t,200,se,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){X.error({err:n,requestId:MC(e)},`[agent-burst-diff] handler failed`),K(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}),_a=q(jn,async(e,t)=>{try{await _e?.(),J(t,200,xe,{},{handler:`test-flush-git`})}catch(n){X.error({err:n,requestId:MC(e)},`[test-flush-git] flush failed`),K(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}),va=q(jn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=Dn(n.searchParams.get(`docName`)??`test-doc`),i;try{i=Oj(r,g)}catch(e){X.error({err:e,docName:r},`[test-reset] safeContentPath rejected docName`),K(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(mt??a.unloadDocument.bind(a))(c),fu(i,``,`utf-8`),await ke?.testOnly?.resetDocumentForTest(r),n.searchParams.get(`reset-okignore`)!==`false`)try{let e=z(g,`.okignore`),t=a.documents.get(et);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},oN)}V(e)&&fu(e,``,`utf-8`),lt&&await lt.rebuildIgnorePatterns()}catch(e){X.warn({err:e},`[test-reset] okignore reset partial failure`)}Me?.(`files`),J(t,200,see,{},{handler:`test-reset`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),xa=q(jn,async(e,t)=>{try{if(!ke?.testOnly){K(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await ke.testOnly.rescanBacklinksForTest(),J(t,200,He,{},{handler:`test-rescan-backlinks`})}catch(e){K(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}),Ca=q(jn,async(e,t)=>{try{if(!ce){K(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await ce(),Me?.(`files`),J(t,200,ct,{},{handler:`test-rescan-files`})}catch(e){K(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}),wa=q(Pi,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=Xr(n),o=ge?.current;if(!o){K(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){K(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=Ce?.()??`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 US(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[$S],l=!0}let d=De??`.`,f=pj(typeof n.summary==`string`?n.summary:void 0),p=await cC(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 Iq(o,vq(o.gitDir))}catch(e){X.warn({err:e},`[rename-log] post-saveVersion GC failed`)}J(t,200,Xn,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(n){X.error({err:n,requestId:MC(e)},`[save-version] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),Ta=q(jn,async(e,t)=>{let n=ge?.current;if(!n){K(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}try{let e=performance.now();await _e?.();let t=performance.now()-e;t>1e3&&X.warn({durationMs:Math.round(t)},`[history] pre-read commit flush slow`)}catch(e){X.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`)??Ce?.()??`main`;if(!i&&a===null){K(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)){K(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=Ls(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}=Ht.run(u,()=>YY(n,e.folderRel,De??`.`,{branch:o,limit:s,offset:l}));f&&AY(`folder`),J(t,200,Tr,{...await d},{handler:`history`});return}let s=De??`.`,c=SX(i,s);if(`error`in c){K(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}=Ht.run(_,()=>JY(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&AY(`doc`);let a=await e,c=Date.now()-v;F(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),J(t,200,Tr,{...a},{handler:`history`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Da(e,t,n){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=ge?.current;if(!r){K(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=De??`.`,o=SX(i,a);if(`error`in o){K(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=HS(r),c=Ce?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await Vq(r,i,n,c,vq(r.gitDir),e=>CX(e,a),Sq());if(e===null){K(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`);J(t,200,Fn,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let ka=q(Gt,async(t,n,r)=>{let i=pM(r,Ze);if(i.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=a.documents.get(r.docName);if(o&&RC(o)){VC(n,new BC({file:DC(r.docName)}),`rollback`);return}let s=ge?.current;if(!s){K(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=r,u=De??`.`,d=SX(c,u);if(`error`in d){K(n,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=HS(s),p=Date.now();try{let t=vq(s.gitDir),r=Sq(),o=await Vq(s,c,l,Ce?.()??`main`,t,e=>CX(e,u),r);if(o===null){K(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 rC(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=a.documents.get(c);if(!h){K(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 Sw(d,g),v;h.transact(()=>{cS(h,d,g,_),v=UC(h.getText(`source`).toString(),d,`rollback`)},yX),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}:{}})),gX(`rollback`,v);let y;switch(i.kind){case`agent`:{let e=l.slice(0,8),t=i.summary.kind===`value`,n=t?i.summary:pj(`Restored to ${e}`),r=ii(n);y=t||!r.response?r.response:ai(r.response),yF(c,i.writerId,i.displayName,i.colorSeed,wd(c,l),i.actor,r.stored),ES(),si(n,!t);break}case`principal`:{let e=ii(i.summary);y=e.response,yF(c,i.writerId,i.displayName,i.colorSeed,wd(c,l),i.actor,e.stored),si(i.summary,!1);break}case`anonymous`:X.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)}`)}sX().add(1,{kind:`rollback`,attribution_kind:i.kind});let b=await Bn(c);if(b?.kind===`failure`){Vn(n,b.failure,`rollback`);return}if(b?.kind===`divergence`){Hn(n,`rollback`);return}Rn(c,`rollback`);let x=Date.now()-p;F(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),i.kind===`agent`&&Pe?.setFocus(i.writerId,{agentName:i.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:WC(v);J(n,200,ee,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){K(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Fa=q(jn,async(e,t)=>{try{J(t,200,ht,FS(),{handler:`metrics-reconciliation`})}catch(n){X.error({err:n,requestId:MC(e)},`[metrics-reconciliation] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:n})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),La=q(jn,async(e,t)=>{try{J(t,200,Hee,d(),{handler:`metrics-parse-health`})}catch(n){X.error({err:n,requestId:MC(e)},`[metrics-parse-health] handler failed`),K(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}),Ra=q(jn,async(e,n)=>{try{gt&&await gt.catch(e=>{X.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=Te?.(),i=mH();J(n,200,Re,{serverInstanceId:y,currentBranch:e,...r===void 0?{}:{currentDiskAckSVs:r},...i===void 0?{}:{boot:i}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),za=A({agents:N(A({id:j(),name:j(),version:j(),description:j().optional(),license:j().optional(),iconUrl:j().optional(),website:j().optional(),source:no([`registry`,`custom`]),supported:To(),featured:To(),harness:A({cli:no([`claude`,`codex`,`cursor`,`opencode`,`pi`]),availability:no([`present`,`not-found`,`unknown`])}).optional()})),stale:To(),maxThreads:P()}),Va=q(jn,async(e,t)=>{if(rt===void 0){K(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=Ld(),{agents:n,stale:r}=await rt.getCatalog(),i=await it?.()??[],a=await st();J(t,200,za,{agents:[...n.map(t=>{let n=aj[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:Pd.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){K(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function Ha(e,t){if(!mj(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=Ze?.()??null;if(!n){K(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}J(t,200,Dt,n,{handler:`principal`})}async function Wa(e,t){if(!mj(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=Le?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);J(t,200,m,{presence:r},{handler:`metrics-agent-presence`})}catch(n){X.error({err:n,requestId:MC(e)},`[metrics-agent-presence] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:n})}}async function Ga(e,t){if(!mj(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-effects`});return}if(e.method!==`GET`){K(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(dC(t)||fC(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`])),J(t,200,Wee,{effects:e},{handler:`metrics-agent-effects`})}catch(e){X.error({err:e,"doc.name":n},`[metrics-agent-effects] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-effects`,cause:e})}}async function Ka(e,t){if(!mj(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-watcher-recent`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-watcher-recent`,extraHeaders:{Allow:`GET`}});return}try{J(t,200,eee,{decisions:oU().map(e=>({ts:e.ts,decision:e.decision,kind:e.kind,"doc.name":e.path,pathRole:e.pathRole}))},{handler:`metrics-watcher-recent`})}catch(n){X.error({err:n,requestId:MC(e)},`[metrics-watcher-recent] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-watcher-recent`,cause:n})}}async function Ja(e,t){if(!mj(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=wF.read();J(t,200,Ji,{entries:n,count:n.length,detection:Mse(n[0])},{handler:`embed-detect`})}async function Ya(e,t){if(!mj(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=z(g),r=n,a=!0;try{r=U(n)}catch(e){let r=Zs(e);if(r===`ENOENT`)X.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),a=!1;else{X.warn({path:n,err:e},`[workspace] realpath failed for contentDir`),K(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}J(t,200,zr,{contentDir:r,pathSeparator:B,symlinkResolved:a},{handler:`workspace`})}let Xa=q(jn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){K(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let r=uM(n),i=Vl(n).slice(1).toLowerCase();if(!r||!Qa.has(i)){K(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let a=U(g),o=z(a,n),s;try{s=U(o)}catch{K(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!kj(s,a)){K(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let c;try{c=uu(s)}catch{K(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!c.isFile()){K(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let l=cM(a,s);if(l!==n.split(`\\`).join(`/`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(lt?.isPathIgnored(l)){K(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let u=qa.has(i),d={"Content-Type":r,"Content-Length":String(c.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":Ro.has(i)||u?`inline`:`attachment`,"Cache-Control":`no-store`};i===`svg`?d[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:u&&(d[`Content-Security-Policy`]=ao),t.writeHead(200,d);try{await Gu(Zl(s),t)}catch(e){X.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){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Za=1048576,$a=q(jn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){K(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let r=U(g),i=z(r,n),a;try{a=U(i)}catch(e){K(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!kj(a,r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let o;try{o=uu(a)}catch(e){K(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!o.isFile()){K(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(cM(r,a)!==n.split(`\\`).join(`/`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(o.size>Za){K(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Za}-byte text-viewer cap.`,{handler:`asset-text`});return}let s=(await wu(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){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),eo=q(jn,async(e,t)=>{try{if(!ge?.current){J(t,200,oi,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=z(ge.current.gitDir,`rescue`);if(V(r))try{let t=au(r).filter(e=>yC(e));for(let i of t){let t=z(r,i),a=uu(t);if(e-a.mtimeMs>864e5){try{du(t)}catch(e){X.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:xC(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){X.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=Ce?.()??`main`,t=await aC(ge.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){X.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}J(t,200,oi,n,{handler:`rescue-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),to=q(Tee,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let r=n.path;if(!yC(r)){K(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(`\\`)){K(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let i=z(g),a=z(i,r);if(!Dj(a,i)){K(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let o=xC(r);if(dC(o)||fC(o)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`});return}if(JX(r)||ri(o)){K(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=``,l;if(s.length>0){if(!/^[A-Za-z0-9_-]+$/.test(s)){K(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=cP(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(`, `);K(t,400,`urn:ok:error:invalid-request`,`Template "${s}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let u=z(i,o.path),d;try{d=H(u,`utf-8`)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=En(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;c=cF(f,{date:uF(),user:p}),l=o.scope}eu(I(a),{recursive:!0});try{fu(a,c,{encoding:`utf-8`,flag:`wx`})}catch(e){if(aZ(e)){K(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let u=xC(r);switch(_t?.delete(u),lt&<.incrementMdDir(I(u)),ZH(a,$H(c)),e.kind){case`agent`:case`principal`:yF(u,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:u,content:c}),await or(u,c,`create-page`),Me?.(`files`),l!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:s,templateScope:l,docName:u})),J(t,200,Mee,{docName:u},{handler:`create-page`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),ro=q(Hr,async(e,t,n)=>{try{if(pM(n,Ze).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!qX(e)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(JX(e)){K(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(lt?.isDirExcluded(e)){K(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let r=eZ(g,`folder`,e);if(V(r)){K(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}ls(r,{recursive:!0}),Yt(e),Me?.(`files`),J(t,200,Zi,{path:e},{handler:`create-folder`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),io=q(Lee,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(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`?xC(i):i;if(!qX(i)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(JX(i)||r===`file`&&(dC(o)||fC(o))||r===`folder`&&YX(i)){K(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}r===`file`&&gZ(g,i);let s=eZ(g,r,i);if(!V(s)){if(r===`file`){let e=eZ(g,`folder`,i);if(V(e)&&uu(e).isDirectory()){K(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}}K(t,404,`urn:ok:error:doc-not-found`,`${r} does not exist.`,{handler:`duplicate-path`});return}let c=uu(s);if(r===`file`&&!c.isFile()||r===`folder`&&!c.isDirectory()){K(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}let l=r===`file`?[uZ(g,i)]:Vr(eZ(g,`folder`,i)),u=Ue?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of l){let n=e,r=a.documents.get(n),i=DC(n),o=r!==void 0&&RC(r),s=d.has(i);if(o||s){VC(t,new BC({file:i}),`duplicate-path`);return}}let f,p=[];if(r===`file`){let e=Vl(s);if(f=fZ(g,o).docName,dC(f)||fC(f)||lt?.isExcluded(`${f}${e}`)){K(t,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let n=dZ(g,f,e),r=H(s,`utf-8`),i=I(n),a=V(i);try{ls(i,{recursive:!0}),vs(n,r,{encoding:`utf-8`,flag:`wx`})}catch(e){if(aZ(e)){K(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{us(i)}catch(e){let t=Zs(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&X.warn({destinationDir:i,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let c=!1;try{TC(f,e),_t?.delete(f),lt&&(lt.incrementMdDir(I(f)),c=!0),ZH(n,$H(r)),w?.({kind:`create`,path:n,docName:f,content:r}),p=[f]}catch(e){try{ps(n,{force:!0})}catch(e){X.warn({destinationPath:n,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw kC(f),lt&&c&<.decrementMdDir(I(f)),w?.({kind:`delete`,path:n,docName:f}),e}await or(f,r,`duplicate-path-file`)}else{if(f=pZ(g,i).folderPath,lt?.isDirExcluded(f)){K(t,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=eZ(g,`folder`,f),n=[];try{fs(s,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(aZ(e)){K(t,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}let r=[];try{for(let e of hZ(g,f))Yt(e);let e=mZ(g,f);p=e.map(e=>e.docName);for(let t of e){let e={docName:t.docName,fullPath:t.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};n.push(e);let i=Vl(t.fullPath);TC(xC(t.docName),i),e.extensionRegistered=!0,_t?.delete(t.docName),lt&&(lt.incrementMdDir(I(t.docName)),e.dirCountIncremented=!0),ZH(t.fullPath,$H(t.content)),e.fileIndexRegistered=!0,w?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),r.push({kind:`upsert`,documentName:t.docName,markdown:t.content})}}catch(t){for(let e of n.reverse()){if(e.fileIndexRegistered)try{w?.({kind:`delete`,path:e.fullPath,docName:e.docName})}catch(t){X.warn({docName:e.docName,err:t},`[duplicate-path] failed to roll back copied file-index row`)}e.dirCountIncremented&<?.decrementMdDir(I(e.docName)),e.extensionRegistered&&kC(xC(e.docName))}Qt(f);try{ps(e,{recursive:!0,force:!0})}catch(t){X.warn({destinationPath:e,err:t},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}await ar(r,`duplicate-path-folder`)}switch(e.kind){case`agent`:case`principal`:for(let t of p)yF(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)}`)}Me?.(`files`),J(t,200,Fee,{kind:r,path:f,duplicatedDocNames:p},{handler:`duplicate-path`})}catch(e){if(e instanceof iZ){K(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=oZ(e);if(n){K(t,n.status,n.type,n.title,{handler:`duplicate-path`,cause:e});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),oo=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){K(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!DZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=cn(n);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!V(r)){K(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}J(t,200,aa,{docName:n,headings:EZ(H(r,`utf-8`))},{handler:`page-headings`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),so=q(Gn,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(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(!qX(i)||!qX(o)){K(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(r===`file`&&(dC(i)||dC(o)||fC(i)||fC(o))){K(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(JX(i)||JX(o)){K(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(i===o){J(t,200,ba,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let s=r===`asset`&&yC(i)&&yC(o)?`file`:r;if(s===`asset`){let n;try{n=yC(i)&&!yC(o)?await qr(i,o):await Wr(i,o)}catch(e){if(e instanceof BC){VC(t,e,`rename-path`);return}let{status:n,type:r,error:i}=vr(e);K(t,n,r,i,{handler:`rename-path`,cause:e});return}n.renamedAssets.length>0&&rn();let r;if(n.renamedAssets.length>0&&n.rewrittenDocs.length>0){let t=`Renamed asset ${i} → ${o}`;r=li(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{X.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(sX().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Se)try{await Se()}catch(e){X.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}J(t,200,ba,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}s===`file`&&gZ(g,i);let c=s===`file`?[uZ(g,i)]:Vr(eZ(g,`folder`,i)),l=Ue?.(),u=new Set(l?l.getConflicts().map(e=>e.file):[]);for(let e of c){let n=e,r=a.documents.get(n),i=DC(n),o=r!==void 0&&RC(r),s=u.has(i);if(o||s){VC(t,new BC({file:i}),`rename-path`);return}}if(lt){let e=yC(i)?Vl(i):EC(i);if(s===`file`?lt.isExcluded(yC(o)?o:`${o}${e}`):lt.isDirExcluded(o)){K(t,400,`urn:ok:error:invalid-request`,`Destination ${s===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let d=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,f;try{f=await Jr(i,o,s,d?{actor:d}:{})}catch(e){if(e instanceof BI){K(t,409,`urn:ok:error:doc-already-exists`,_r(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(f.renamed.length===0&&f.renamedAssets.length===0){J(t,200,ba,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}f.renamedAssets.length>0&&rn();let p,m=f.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(m.length>0&&(p=li(e,`Renamed ${i} → ${o}`,m.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Ed(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{X.debug({kind:r,fromPath:i,toPath:o,affectedDocs:f.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),sX().add(1,{kind:`rename-${s}`,attribution_kind:e.kind}),Se)try{await Se()}catch(e){X.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}J(t,200,ba,{renamed:f.renamed,renamedAssets:f.renamedAssets,rewrittenDocs:f.rewrittenDocs,...p?{summary:p}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=vr(e);K(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),co=q(hi,async(e,t,n)=>{try{Xr(n);let{kind:e,path:r}=n;if(!qX(r)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let i=e===`asset`?Ir(r):{path:r,ambiguous:!1};if(i.ambiguous){K(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`&&yC(o)?`file`:e;if(s===`file`&&gZ(g,o),JX(o)){K(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let c=s===`asset`?eZ(g,`folder`,o):eZ(g,s,o);if(!V(c)){K(t,404,`urn:ok:error:doc-not-found`,`${s} does not exist.`,{handler:`delete-path`});return}let l=uu(c);if(s===`file`&&!l.isFile()||s===`asset`&&!l.isFile()||s===`folder`&&!l.isDirectory()){K(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${s}.`,{handler:`delete-path`});return}let u=s===`asset`?[]:s===`file`?[uZ(g,o)]:Vr(eZ(g,`folder`,o)),d=Ue?.(),f=new Set(d?d.getConflicts().map(e=>e.file):[]);for(let e of u){let n=e,r=a.documents.get(n),i=DC(n),o=r!==void 0&&RC(r),s=f.has(i);if(o||s){VC(t,new BC({file:i}),`delete-path`);return}}if(await br(u,`deleted-upstream`),_t)for(let e of u)dC(e)||fC(e)||(_t.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));s===`file`||s===`asset`?is(c):(ps(c,{recursive:!0,force:!1}),Qt(o)),rn();for(let e of u)w?.({kind:`delete`,path:z(g,DC(e)),docName:e});await ur(u,`delete-path`),Me?.(`files`),J(t,200,Yr,{deletedDocNames:u},{handler:`delete-path`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),lo=q(pa,async(e,t,n)=>Qo(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":ds(n.path),"ok.cleanup.path.role":gs(n.path)}},async()=>{try{if(pM(n,Ze).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:r}=n;if(!qX(r)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&yC(r)?`file`:e,a=xC(r);i===`file`&&gZ(g,r);let o=i===`folder`&&YX(r);if(i===`file`&&(dC(a)||fC(a))||o||JX(r)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(i===`asset`){rn(),Me?.(`files`),J(t,200,$t,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let s=x(),c=i===`file`?s.has(a)?[a]:[]:XX(s,i,r);if(rn(),c.length===0){J(t,200,$t,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await br(c,`deleted-upstream`),_t)for(let e of c)dC(e)||fC(e)||(_t.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(g,DC(e)),docName:e});i===`folder`&&Qt(r),await ur(c,`trash-cleanup`),Me?.(`files`),J(t,200,$t,{deletedDocNames:c},{handler:`trash-cleanup`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),O=q(jn,async(e,t)=>{try{let e=x(),n=[];for(let[t,r]of e){let e=EC(t),i,a;if(r.title!==void 0)i=r.title,a=r.icon;else{i=t;try{let n=H(z(g,`${t}${e}`),`utf-8`);i=ER(n,t),a=DR(n)}catch(e){X.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)),J(t,200,Oa,{pages:n},{handler:`pages`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),uo=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){K(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!DZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(dC(n)||fC(n)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${n}' is a reserved document name.`,{handler:`suggest-links`});return}J(t,200,Eee,await SY({hocuspocus:a,fileIndex:x(),docName:n}),{handler:`suggest-links`})}catch(e){if(e instanceof tY){K(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}K(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 fo(e,t){if(e.method!==`POST`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let n;try{n=await NX(e,D??g)}catch(e){if(e instanceof _V){K(t,vV(e.reason),e.reason,bV(e.reason),{handler:`upload-asset`,cause:e});return}K(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,l=()=>{if(V(i))try{du(i)}catch{}},u=yM(Ma,{parentDocName:s,placement:c||void 0},t,{handler:`upload-asset`});if(!u.ok){l();return}let{parentDocName:d,placement:f}=u.value,{agentId:p,agentName:m}=Xr(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(o===0){l(),K(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(d.includes(`\0`)||d.includes(`..`)||d.startsWith(`/`)){l(),K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let h=z(g),_;try{_=f===`parent-dir`?`./`:S?.()??`./`}catch(e){l(),X.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),K(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!qee(_)){l(),K(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let v=OX(d,Ua(_),h);if(!kj(v,h)){l(),K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{$X(v,h)}catch(e){if(l(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}X.error({err:e,destDir:v},`[upload] failed to validate destination directory`),K(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{eu(v,{recursive:!0})}catch(e){if(!aZ(e)){l();let n=yV(e);K(t,vV(n),n,bV(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=U(v),n;try{n=U(h)}catch{n=h}if(!kj(e,n)){l(),K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(Zs(e)!==`ENOENT`){l(),K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let y=kX(i,4100),b=await ZA(y),x=b?.mime,C=b?.ext;if(!x){let e=y.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(x=`image/svg+xml`,C=`svg`)}{let n=await MX(v,a,o);if(n){l();let r=Ej(R(g,z(v,n)));X.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:p,agentName:m,dedup:!0,mime:x??null,size:o,destPath:r,httpStatus:200},`[upload] dedup hit`),J(t,200,It,{src:n,path:r,deduped:!0},{handler:`upload-asset`});return}}let w;if(!r||r===`upload`||wX.test(r)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=r?Vl(r).slice(1):``,n=C??t??``;w=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else w=DX(r);try{let n=TV(i,v,w),r=Ej(R(g,z(v,n)));X.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:p,agentName:m,dedup:!1,mime:x??null,size:o,destPath:r,httpStatus:200},`[upload] write ok`),J(t,200,It,{src:n,path:r,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof _V?n.reason:`urn:ok:error:storage-error`;X.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:MC(e),agentId:p,agentName:m,filename:w,size:o,reason:r,httpStatus:vV(r),err:n},`[upload] write failed`),K(t,vV(r),r,bV(r),{handler:`upload-asset`,cause:n})}}let k=`/api/local-op/clone`,po=`/api/local-op/ok-init`,mo=600*1e3,ho={stdio:[`ignore`,`ignore`,`pipe`]},go={stdio:[`ignore`,`pipe`,`pipe`]},_o={stdio:`ignore`},vo=`local-op-clone`,yo=q(vt,bo,{handler:vo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:vo})});async function bo(e,t,n){let{url:r,dir:i,branch:a}=n;if(!mG(r)){K(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:vo,cause:Error(`url=${r}`)});return}if(!vG(i)){K(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:vo,cause:Error(`dir=${i}`)});return}if(!Bt.tryAcquire(k)){K(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:vo,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=LC(t,vo),s=null,c=oK({cliArgs:Ke,url:r,dir:i,branch:a,timeoutMs:mo,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&X.warn({stderr:lz(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=jG(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(lz(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 xo(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}):X.error({err:e,handler:vo},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Bt.release(k)}})(),t.on(`close`,()=>{c.cancel()})}async function xo(e,t){let n=z(hG(e)),r=iN(n),i=mV(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=Ke,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=Il(a,s(e),ZF({...ho,cwd:n,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),i=[];t.stderr?.on(`data`,t=>{i.push(t),X.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,X.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 qu(500);let t=mV(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=Gs(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=Gs(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 So=`local-op-ok-init`,Co=q(xn,async(e,t,n)=>{let{projectPath:r}=n;if(!Hl(r)){K(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:So,cause:Error(`projectPath=${r}`)});return}let i;try{i=U(r)}catch(e){J(t,200,_n,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:So});return}if(!vG(i)){K(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:So,cause:Error(`projectPath=${r}`)});return}let a=cd(i).kind;if(a!==`directory`&&a!==`linked`){X.warn({project:zl(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${zl(i)} result=not-a-git-worktree kind=${a}`),J(t,200,_n,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:So});return}if(PU(i)){X.warn({project:zl(i),result:`already-initialized`},`[ok-init] action=init project=${zl(i)} result=already-initialized`),J(t,200,_n,{ok:!0,projectPath:i},{handler:So});return}if(!Bt.tryAcquire(po)){K(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:So,extraHeaders:{"Retry-After":`2`}});return}try{await Ns(async()=>{dW(i)}),X.warn({project:zl(i),result:`success`},`[ok-init] action=init project=${zl(i)} result=success`),J(t,200,_n,{ok:!0,projectPath:i},{handler:So})}catch(e){let n=e instanceof Error?e.message:String(e);X.warn({project:zl(i),result:`failed`,reason:n},`[ok-init] action=init project=${zl(i)} result=failed reason=${n}`),J(t,200,_n,{ok:!1,reason:`init-failed`,message:n},{handler:So})}finally{Bt.release(po)}},{handler:So,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:So})}),M=`/api/local-op/auth/login`,Eo=`/api/local-op/auth/status`,Do=`/api/local-op/auth/repos`,Oo=`/api/local-op/auth/signout`,ko=`/api/local-op/auth/pat`,Ao=`/api/local-op/auth/gh-login`,jo=qe??15e3,Mo=960*1e3,No=()=>GR(D??g),Po={current:null},Fo={current:null};function Io(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!Bt.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})),K(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=LC(t,n),l=e=>{if(!(t.writableEnded||t.destroyed))try{t.write(e)}catch{}},u=setInterval(()=>{l(`${JSON.stringify({type:`ping`})}\n`)},jo);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}vX(e,Ue),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,Bt.release(r))})}let Lo=`local-op-auth-login`,Vo=q(ln,Uo,{handler:Lo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Lo})});async function Uo(e,t,n){let r=n.host??No();Io({res:t,handler:Lo,guardKey:M,inFlight:Po,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>TG({cliArgs:Ke,host:r,timeoutMs:Mo,onEvent:e})})}let Wo=`local-op-auth-gh-login`,Go=q(ln,async(e,t,n)=>{let r=n.host??No(),i=await mK();if(i===null){K(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:Wo});return}Io({res:t,handler:Wo,guardKey:Ao,inFlight:Fo,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>_K({host:r,ghPath:i,timeoutMs:Mo,onEvent:e})})},{handler:Wo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Wo})}),Ko=`local-op-auth-cancel`,qo=q(Ia,$U(async(e,t,n)=>{let r=n.channel===`gh-login`?{inFlight:Fo,guardKey:Ao}:{inFlight:Po,guardKey:M},i=r.inFlight.current;i&&(i.cancel(),r.inFlight.current=null,Bt.release(r.guardKey)),J(t,200,b,{},{handler:Ko})},{handler:Ko,title:`Failed to cancel the sign-in.`}),{handler:Ko,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ko})}),Yo=`local-op-auth-status`,Xo=q(ln,async(e,t,n)=>{let r=n.host??No();if(!Bt.tryAcquire(Eo)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Yo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=Ke,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=Il(e,i,ZF({...go,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(`
|
|
1213
1213
|
`).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 mK()!==null;o===null?J(t,200,Oe,{authenticated:!1,ghAvailable:s},{handler:Yo}):J(t,200,Oe,{...o,ghAvailable:s},{handler:Yo})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Yo,cause:e})}finally{Bt.release(Eo)}},{handler:Yo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Yo})}),Zo=`local-op-auth-pat`,$o=q(Fe,async(e,t,n)=>{let r=n.host??No();if(!Bt.tryAcquire(ko)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:Zo,extraHeaders:{"Retry-After":`5`}});return}try{let e=await EG({cliArgs:Ke,host:r,token:n.token});e.ok?(_X(Ue),J(t,200,cee,{host:e.host,login:e.login},{handler:Zo})):K(t,400,`urn:ok:error:auth-failed`,e.error,{handler:Zo})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:Zo,cause:e})}finally{Bt.release(ko)}},{handler:Zo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zo})}),es=`local-op-auth-repos`,ts=q(ln,rs,{handler:es,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:es})});async function rs(e,t,n){let r=n.host??No();if(!Bt.tryAcquire(Do)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:es,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=LC(t,es),[a,...o]=Ke,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=Il(a,s,ZF({...go,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},mo);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
|
|
1214
1214
|
`);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{X.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Bt.release(Do))}),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()),Bt.release(Do))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),Bt.release(Do))})}let os=`local-op-auth-signout`,ss=q(ln,async(e,t,n)=>{let r=n.host??No();if(!Bt.tryAcquire(Oo)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:os,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=Ke,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=Il(e,i,ZF({..._o,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,b,{},{handler:os})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:os,cause:e})}finally{Bt.release(Oo)}},{handler:os,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:os})}),cs=`/api/local-op/auth/set-identity`,ms=`local-op-auth-set-identity`,hs=q(hee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!D){K(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:ms});return}if(!Bt.tryAcquire(cs)){K(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ms,extraHeaders:{"Retry-After":`5`}});return}try{QU(D,r,i),Ue?.()?.refreshIdentity().catch(()=>{}),J(t,200,b,{},{handler:ms})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ms,cause:e})}finally{Bt.release(cs)}},{handler:ms,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ms})});async function _s(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=Ue?.();if(!e){J(t,200,ci,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),J(t,200,ci,e.getStatus(),{handler:`sync-status`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let ys=q(Ii,async(e,t,n)=>{let r=Ue?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;J(t,202,Qn,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?Ue?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function bs(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=Ue?.();J(t,200,ki,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let xs=q(zee,async(e,t,n)=>{let r=Ue?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),J(t,200,Ln,{},{handler:`sync-resolve-conflict`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?Ue?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Ts(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!D){K(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){K(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let o=xC(i),s=a.documents.get(o)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=Ue?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){K(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=Ms({baseDir:D,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=xC(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=xt?xt(o):null;t!==null&&(c=t,l=!0)}else{lV(L(D,i),D);try{c=H(L(D,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;J(t,200,ni,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),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=xC(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=xt?xt(e):null;t!==null&&!xX(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else X.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}J(t,200,ni,{file:i,base:o,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Ds(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=cJ(a);if(a!==null&&a!==``&&o===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,Ui,{plan:await wJ({projectDir:g,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof Xq){K(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof Zq){K(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Os=q(ree,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){K(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,s=cJ(a);if(typeof a==`string`&&a.length>0&&s===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,o,{result:await yJ(i,{projectDir:g,packId:s})},{handler:`seed-apply`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function ks(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}J(t,200,Oee,{packs:uJ()},{handler:`seed-packs`})}}let js=q(_ee,async(e,t,n)=>{if(n.out!==void 0&&!vG(n.out)){K(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{J(t,200,wn,await iB({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function Ps(e,t){if(r(e,t,{handler:`installed-agents`}))try{await mce(e,t,sn.probeAll)}catch(n){t.headersSent||(X.error({err:n,requestId:MC(e)},`[installed-agents] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let Fs=q(jn,async(e,t)=>{if(!ke){K(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{J(t,200,oee,{tags:await ke.getAllTags()},{handler:`tags-list`})}catch(e){lr(t,e,{handler:`tags-list`,failureTitle:`Failed to read tags.`})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Is(e,t,n){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!ke){K(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{K(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){K(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=(await ke.getDocsForTagWithMatches(r)).map(({docName:e,matchingTags:t})=>({docName:e,title:dn(e),matchingTags:t,snippet:null}));J(t,200,ot,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){lr(t,e,{handler:`tags-for-name`,failureTitle:`Failed to read tag membership.`})}}function Ls(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return K(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=z(g),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${B}`)?(K(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let Rs=/^[A-Za-z0-9_-]+$/;function zs(e,t,n=`template`){return!e||!Rs.test(e)?(K(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Bs(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}${B}`))continue;let o=z(a,`.ok`,`templates`,`${n}.md`);if(V(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Vs(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 Hs=eW({GET:q(jn,async(e,t)=>{try{let n=Ls(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await IP(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(V(i))try{let e=(0,rj.parse)(await wu(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);X.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}J(t,200,Ie,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:q(lee,async(e,t,n)=>{try{if(Pt){K(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Ls(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=HP({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(di(e,ui(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await gi(`folder-config-put`))}J(t,200,gee,{applied:i},{handler:`folder-config-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function Us(e,t,n,r){if(!t)return!1;let i=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=a.documents.get(i);return o&&RC(o)?(VC(r,new BC({file:`${i}.md`}),n),!0):!1}function Ws(e,t,n){let r=a.documents.get(e);return r&&RC(r)?(VC(n,new BC({file:`${e}.md`}),t),!0):!1}let Ks=q(jn,$U(async(e,t)=>{let n=lP(z(g));J(t,200,bi,{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}),qs=e=>{let{body:t}=rr(e);return{frontmatter:We(e)??{},body:t}},Js=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!zs(r,t,`template-get`))return;let i=Ls(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Bs(o,a,r);if(!s){K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=ea(await wu(c,`utf-8`)),f=d.identity,p=d.starterContent;J(t,200,v,{template:{name:r,folder:l,scope:u,path:R(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Ys=q(Ee,async(e,t,n)=>{try{if(Pt){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!zs(r,t,`template-put`))return;let i=Ls(n.folder,t,`folder`,`template-put`);if(!i||Us(i.folderRel,r,`template-put`,t))return;let a=fF({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Vs(n.frontmatter)});if(!a.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!V(o),l=R(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=xc(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=Xr(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{sS(h.dc.document,a.content,`agent`)},h.origin);let g=await Bn(u);if(g?.kind===`failure`){Vn(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){Hn(t,`template-put`);return}di(e,ui(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await gi(`template-put`),J(t,200,$e,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Xs=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!zs(r,t,`template-delete`))return;let i=Ls(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=ac(n,Ze);if(a.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Us(i.folderRel,r,`template-delete`,t))return;await br([xc(i.folderRel,r)],`deleted-upstream`);let o=vse({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(di(a,ui(`template`,i.folderRel,r),`template-delete: ${o.path}`),await gi(`template-delete`)),J(t,200,Pa,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Qs=eW({GET:Js,PUT:Ys,POST:q(an,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!zs(n.fromName,t,`template-move`)||!zs(n.toName,t,`template-move`))return;let r=Ls(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Ls(n.toFolder,t,`folder`,`template-move`);if(!i||Us(r.folderRel,n.fromName,`template-move`,t))return;await br([xc(r.folderRel,n.fromName)],`renamed`);let a=await yse({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await wZ(D,e,t);return n||CZ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Bs(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){K(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){K(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}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=En(H(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=_se({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Vs(n.frontmatter)});t.ok||(o=t.error)}}if(di(e,ui(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await gi(`template-move`),Me?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}J(t,200,mee,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:Xs},{handler:`template`}),$s=q(fee,async(e,t,n)=>{try{if(Pt){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!DZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=Dn(r);if(dC(i)||fC(i)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let o=eZ(g,`file`,i);if(!V(o)){K(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=Ue?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=c!==void 0&&RC(c),a=n.has(r);if(i||a){VC(t,new BC({file:r}),`template-import`);return}}let l=``;if(c)l=c.getText(`source`).toString();else{let e=await a.openDirectConnection(i);try{let n=e.document;if(!n){K(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}l=n.getText(`source`).toString()}finally{await e.disconnect()}}let u=n.name;if(!u){let{basename:e}=tZ(r);u=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),u=u.replace(/^[-_]+|[-_]+$/g,``),u||=`imported-template`}if(!zs(u,t,`template-import`))return;let d=Ls(n.targetFolder,t,`folder`,`template-import`);if(!d||Us(d.folderRel,u,`template-import`,t))return;let{frontmatter:f,body:p}=rr(l),m=dr(f),h={};try{m.trim()&&(h=(0,rj.parse)(m))}catch{}let _=n.title||h?.title||ER(l,u),v=h?.description||``,y=Array.isArray(h?.tags)?h.tags:[],b={...h};delete b.template,delete b.title;let x=``;Object.keys(b).length>0&&(x=`${(0,rj.stringify)(b).trim()}\n`),x=x?`---\n${x}---\n${p}`:p;let S=fF({name:u,body:x,frontmatter:{title:_,description:v,tags:y}});if(!S.ok){K(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(d.resolvedContentDir,d.folderRel,`.ok`,`templates`,`${u}.md`),T=!V(C),E=R(d.resolvedContentDir,C).split(/[\\/]/).filter(Boolean).join(`/`),ee=xc(d.folderRel,u),{agentId:te,agentName:ne,colorSeed:re,clientName:ie}=Xr(n),ae=await s.getSession(ee,te,{displayName:ne,colorSeed:re,clientName:ie});ae.dc.document.transact(()=>{sS(ae.dc.document,S.content,`agent`)},ae.origin);let oe=await Bn(ee);if(oe?.kind===`failure`){Vn(t,oe.failure,`template-import`);return}if(oe?.kind===`divergence`){Hn(t,`template-import`);return}di(e,ui(`template`,d.folderRel,u),`template-import: ${E}`),n.deleteSource&&(await br([i],`deleted-upstream`),_t&&_t.setDeleted(i),is(o),w?.({kind:`delete`,path:o,docName:i})),await gi(`template-import`),Me?.(`files`),J(t,200,Ne,{path:E,created:T,warnings:S.warnings},{handler:`template-import`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function ec(e,t,n){return!e||e.length>64||!nt.test(e)?(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function tc(e,t,n){let r=ae.safeParse(e??`project`);return r.success?r.data:(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let nc=Qe??gu();function rc(e){return z(e===`global`?nc:g,`.ok`,`skills`)}function ic(e,t,n){let r=z(rc(e),t);if(e===`global`){if(n!==void 0){let e=rV(nc).find(e=>e.name===t&&e.hosts.includes(n));return e?z(nc,e.dir):null}let e=aV(nc,t);return e===null?V(L(r,`SKILL.md`))?r:null:e}let i=nV(g).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?z(g,i.dir):n===void 0&&V(L(r,`SKILL.md`))?r:null}function ac(e,t){let n=e.searchParams;return pM({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},t)}function oc(e){return(e===`.ok`||e.startsWith(`.ok/`))&&e!==`.ok/skills`}function sc(e,t){let n=e===`project`?D:nc;if(!n)return`symlink`;try{return Jc(L(n,...XD)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function cc(e){let t=e===`project`?D:nc;return t?L(t,...XD):null}function lc(e,t,n,r={}){let i=cc(e);return i?QJ(i,e=>{let i=e.skills[t];if(!i)return e;let a={...e.skills};return delete a[t],a[n]={...i,...r},{...e,skills:a}}):Promise.resolve()}async function uc(e,t,n){let r=cc(e),i=cc(t);if(!r||!i)return!1;let a=XJ(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await QJ(i,e=>({...e,skills:{...e.skills,[n]:o}})),await QJ(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function dc(e,t,n){let r=cc(e);return r?QJ(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function fc(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];K(e,r,i,t.error,{handler:n,detail:t.code})}function pc(e,t,n){let r=e===`project`?D:nc;return(r?zJ(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function mc(e){let t=ic(`project`,e);return t?R(g,t).split(B).join(`/`):`${gn}/${e}`}let hc=mz.project;function gc(e,t,n){let r=[],i=null,a=[...Rt.map(e=>({id:e,root:be[e]??``})),{id:`agents`,root:`.agents/skills`}];for(let{id:o,root:s}of a){if(!s)continue;let a=z(e,...s.split(`/`),t);V(z(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=z(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:R(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function _c(e){let t=Xoe(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function vc(e,t){if(!gz(t))return null;let n=gc(e,t);if(!n)return null;let r=iO(n.dir)?.contentHash??``,i;try{i=uu(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:An,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function yc(e,t,n){let r=gc(e,t);if(!r)return null;let i;try{let{frontmatter:e}=qs(H(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=vc(e,t);return{name:t,...i===void 0?{}:{description:i},scope:n,path:r.relPath,absolutePath:r.skillMd,installed:r.hosts.length>0,hosts:r.hosts,managed:!0,...a?{origin:_c(a)}:{}}}function bc(e,t,n){return gz(e)?(K(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function xc(e,t){return`${Ft}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Sc(e){return e===`navigation`||e===`relevance`?e:void 0}function Cc(e,t){return R(t===`global`?nc:g,e).split(/[\\/]/).filter(Boolean).join(`/`)}function wc(e){return e===`global`?nc:D}async function Tc(e,t,n){let r=await EI(e,t);if(!V(z(rc(n),t,`SKILL.md`))){let i=(n===`project`?nV(g):rV(nc)).find(e=>e.name===t);if(i){let a=n===`project`?g:nc,o=z(a,i.dir),s=z(a,`.agents`,`skills`),c=L(s,t);if(V(s)&&!V(L(c,`SKILL.md`))){let e=!1;try{e=U(o)===U(c)}catch{e=!1}e||fs(o,c,{recursive:!0,dereference:!0})}return wB({canonicalAbs:V(L(c,`SKILL.md`))?c:o,canonicalHash:i.contentHash,name:t,cwd:e,targets:[...Rt],roots:pB(n)}),r!==null}}return TB(t,e,Rt,pB(n)),r!==null}function Ec(e,t){let n=[];if(!V(e))return{skills:n,truncated:!1};let r;try{r=au(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()||!nt.test(a.name))continue;if(n.length>=500){i=!0;break}let r=z(e,a.name,`SKILL.md`);if(!V(r))continue;let o;try{let{frontmatter:e}=qs(H(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Cc(r,t),absolutePath:r})}return{skills:n,truncated:i}}let Dc=q(jn,$U(async(e,t)=>{let n=rc(`project`),r=Ec(n,`project`),i=Ec(rc(`global`),`global`),a=[...Rt],o=Xz(nc).map(e=>e.editorId),s=D?CI(D).skills:{},c=CI(nc).skills,l=D?QD(V(L(D,...XD))?H(L(D,...XD),`utf-8`):``)??null:null,u=_c,d=(e,t,r)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=r?l?.skills[e.name]:void 0,o=a?u(a):void 0,s=a?.localHash!==void 0&&Yc(n,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),f=D?BJ(D):{},p=(e,t,n)=>{let r=[];for(let i of t??[]){let t=z(e,i.path);if(n!==void 0&&t===z(n))continue;let a=!1;try{a=$l(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(U(t)===U(n))continue}catch{}r.push(i.path)}}return{drift:r}},m=D?GB(g,`project`):{},h=XB(m,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=YB(`project`),y=YB(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=D?nV(g).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?l?.skills[e.name]??vc(g,e.name):void 0,r=n?u(n):void 0,i=n?.localHash!==void 0&&e.contentHash!==n.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:z(g,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:a,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(m).length>0?{hostAliases:m}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let n=b(t?f[e.name]:void 0,h).filter(e=>!_(e.path,v));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=p(D,b(t?f[e.name]:void 0,h),z(g,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...pc(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...gz(e.name)?{managed:!0}:{}}}):[],C=BJ(nc),w=Jc(L(nc,...XD)),T=GB(nc,`global`),E=XB(T,`global`),ee=new Set(rV(nc).map(e=>e.name));i.skills=i.skills.filter(e=>!ee.has(e.name));let te=new Set,ne=rV(nc).map(e=>{let t=!te.has(e.name);te.add(e.name);let n=t?C[e.name]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:z(nc,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:o,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(T).length>0?{hostAliases:T}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=p(nc,b(n,E),z(nc,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=b(n,E).filter(e=>!_(e.path,y));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...pc(`global`,e.name,e)===`link`?{linkMode:!0}:{},...gz(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??vc(nc,e.name);return n?{origin:u(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),re=new Set(S.map(e=>e.name)),ie=D&&!r.skills.some(e=>e.name===hc)&&!re.has(hc)?yc(D,hc,`project`):null,ae=new Set(ne.map(e=>e.name)),oe=yz.map(e=>mz[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!ae.has(e)).map(e=>yc(nc,e,`global`)).filter(e=>e!==null),se=new Set(S.map(e=>e.name));J(t,200,ye,{skills:[...d(r,s,!0).filter(e=>!se.has(e.name)),...S,...d(i,c,!1),...ne,...ie?[ie]:[],...oe],truncated:r.truncated||i.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Oc=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ec(r,t,`skill-get`))return;let i=tc(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(gz(r)){let e=i===`global`?nc:D,a=e?gc(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=qs(await wu(a.skillMd,`utf-8`));J(t,200,Zn,{skill:{name:r,scope:i,path:a.relPath,frontmatter:{name:typeof e.name==`string`?e.name:r,description:typeof e.description==`string`?e.description:``},body:n,files:DB(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=ic(i,r,a);if(o===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:a===void 0?`Skill "${r}" not found in ${i} scope.`:`No skill "${r}" (${i}) in ${a}.`});return}let s=z(o,`SKILL.md`),{frontmatter:c,body:l}=qs(await wu(s,`utf-8`));J(t,200,Zn,{skill:{name:r,scope:i,path:Cc(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:DB(o)}},{handler:`skill-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function kc(e,t){if(!(!ke||gC(e))){if(lt)try{await lt.rebuildIgnorePatterns()}catch{}await or(e,t,`skill-put`)}}let Ac=q(Ea,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!ec(n.name,t,`skill-put`)||bc(n.name,t,`skill-put`))return;let r=YP({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?g:nc,a=ic(n.scope,n.name);if(a===null){let a=ZB(i,n.scope),o=XP({skillsRoot:z(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:o.error.code,cause:Error(o.error.message)});return}n.scope===`project`&&(di(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await gi(`skill-put`)),await kc(n.scope===`project`?`${a}/${n.name}/SKILL`:Qi(`global`,n.name),r.content),Me?.(`files`),J(t,200,Un,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=R(i,a).split(B).join(`/`),c=`${o}/SKILL.md`,l=n.scope===`project`?`${o}/SKILL`:Qi(n.scope,n.name);if(Ws(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=Xr(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{sS(m.dc.document,r.content,`agent`)},m.origin);let h=await Bn(l);if(h?.kind===`failure`){Vn(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){Hn(t,`skill-put`);return}n.scope===`project`&&(di(e,ui(`skill`,``,n.name),`skill-edit: ${c}`),await gi(`skill-put`)),await kc(l,r.content),Me?.(`files`),J(t,200,Un,{path:c,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function jc(e,t){let n=e===`project`?g:nc,r=ic(e,t);return{root:r===null?rc(e):I(r),dirRel:r===null?`.ok/skills/${t}`:R(n,r).split(B).join(`/`),realDir:r}}function Mc(e,t){let n=e===`project`?g:nc,r=(e===`project`?nV(g):rV(nc)).find(e=>e.name===t);r&&wB({canonicalAbs:z(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>yn(e)),roots:pB(e)})}let Nc=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ec(r,t,`skill-delete`))return;let i=tc(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=jc(i,r),s=ac(n,Ze);if(s.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await br(i===`project`?[...new Set([`${o}/SKILL`,Qi(i,r)])]:[Qi(i,r)],`deleted-upstream`),Mc(i,r);let c=tF({skillsRoot:a,name:r}),l=rc(i);if(c.ok&&l!==a&&V(z(l,r,`SKILL.md`))){let e=tF({skillsRoot:l,name:r});e.ok||X.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(di(s,o,`skill-delete: ${o}`),await gi(`skill-delete`)),Me?.(`files`));let u=wc(i);u&&await Tc(u,r,i),J(t,200,vee,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Pc=q(Iee,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!ec(n.fromName,t,`skill-move`)||!ec(n.toName,t,`skill-move`)||bc(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=jc(n.scope,n.fromName);if(ic(n.scope,n.toName)!==null){K(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=wc(n.scope),o=a?CI(a).skills[n.fromName]:void 0,s=n.scope===`project`?g:nc,c=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.fromName),l=c?I(c.dir):null,u=l===null?[]:Object.entries(GB(s,n.scope)).filter(([,e])=>e===l).map(([e])=>e),d=[...new Set([...o?aB(o.hosts):[],...c?aB(c.hosts):[],...aB(u)])];await br(n.scope===`project`?[...new Set([`${i}/SKILL`,Qi(n.scope,n.fromName)])]:[Qi(n.scope,n.fromName)],`renamed`),Mc(n.scope,n.fromName);let f=await dse({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await wZ(D,e,t);return n||CZ(e,t),n}});if(!f.ok){if(f.error.code===`SKILL_NOT_FOUND`){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:f.error.message});return}if(f.error.code===`SKILL_EXISTS`){K(t,409,`urn:ok:error:doc-already-exists`,f.error.message,{handler:`skill-move`,detail:f.error.code});return}let e=f.error.code===`MOVE_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:f.error.code,cause:Error(f.error.message)});return}let p=null,m=z(r,n.toName,`SKILL.md`),h=``,_=``;try{let e=qs(H(m,`utf-8`));h=e.body,typeof e.frontmatter.description==`string`&&(_=e.frontmatter.description)}catch{}let v=typeof n.body==`string`?n.body:h,y=n.frontmatter===void 0?_:n.frontmatter.description,b=XP({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(p=b.error);let x=[];if(!p)try{x=cV({base:n.scope===`project`?g:nc,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){F(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}if(n.scope===`project`&&!p)try{await lt?.rebuildIgnorePatterns(),await Uc(r,n.fromName,n.toName),await Wc(x,n.toName)}catch(e){F(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let S=Cc(z(r,n.fromName),n.scope),C=Cc(z(r,n.toName),n.scope);n.scope===`project`&&(di(e,ui(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await gi(`skill-move`));let w=Yc(r,n.toName),T=n.scope===`project`?await Xc(Zc(e),C):void 0;if(await lc(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await EI(a,n.fromName),TB(n.fromName,a,d,pB(n.scope));let e=z(r,n.toName);if(d.length>0){let t=yB(e,n.toName,a,d,sc(n.scope,n.toName),pB(n.scope));await TI(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??uB(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(Me?.(`files`),p){let e=p.code===`WRITE_ERROR`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:p.code,cause:Error(p.message)});return}J(t,200,ra,{from:S,to:C,committed:f.committed},{handler:`skill-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),Fc=q(l,async(e,t,n)=>{let{name:r,home:i}=n;if(!ec(r,t,`skill-edit-external`))return;let a;try{a=U(i)}catch{K(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!uu(a).isDirectory()||!V(z(a,`SKILL.md`))){K(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}UH(r,a),J(t,200,Dee,{docName:Wi(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),Ic=q(Pee,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move-scope`});return}let{name:r,fromScope:i,toScope:a}=n;if(!ec(r,t,`skill-move-scope`))return;if(i===a){K(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!D){K(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:s,realDir:c}=jc(i,r),l=z(o,r),u=(()=>{try{return U(l)}catch{return l}})(),d=a===`project`?g:nc,f=z(d,ZB(d,a)),p=z(f,r);if(c===null||!V(l)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(z(c)===z(p)||V(p)&&U(c)===U(p)){K(t,409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{handler:`skill-move-scope`,detail:`SAME_STORAGE`});return}if(ic(a,r)!==null||V(p)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let m=wc(i),h=wc(a),_=m?CI(m).skills[r]:void 0,v=i===`project`?g:nc,y=(i===`project`?nV(g):rV(nc)).find(e=>e.name===r),b=y?I(y.dir):null,x=b===null?[]:Object.entries(GB(v,i)).filter(([,e])=>e===b).map(([e])=>e),S=[...new Set([..._?aB(_.hosts):[],...y?aB(y.hosts):[],...aB(x)])];await br([...new Set([...i===`project`?[`${s}/SKILL`]:[],Qi(i,r),Qi(a,r)])],`renamed`),ls(f,{recursive:!0}),fs(u,p,{recursive:!0,dereference:!0}),Mc(i,r);let C=tF({skillsRoot:o,name:r});if(C.ok&&u!==l){let e=R((()=>{try{return U(v)}catch{return v}})(),u);e!==``&&!e.startsWith(`..`)&&!Hl(e)&&ps(u,{recursive:!0,force:!0})}if(!C.ok){tF({skillsRoot:f,name:r}),K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:C.error.code,cause:Error(C.error.message)});return}let w=await uc(i,a,r);if(m&&await Tc(m,r,i),h&&S.length>0){let e=yB(p,r,h,S,sc(a,n.name),pB(a));await TI(h,r,{..._,scope:a,hosts:e,scripts:_?.scripts??uB(p,r).hasScripts,installedAt:_?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(di(e,i===`project`?s:R(g,p).split(B).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await gi(`skill-move-scope`)),w){let t=Yc(f,r),n=a===`project`?await Xc(Zc(e),R(g,p).split(B).join(`/`)):void 0;await dc(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!V(L(p,`SKILL.md`))){K(t,500,`urn:ok:error:internal-server-error`,`The move did not leave a readable skill at the destination; nothing was reported as moved.`,{handler:`skill-move-scope`,detail:R(d,p).split(B).join(`/`)});return}Me?.(`files`),J(t,200,kn,{scope:a,path:R(d,p).split(B).join(`/`)},{handler:`skill-move-scope`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),Lc=q(See,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!ec(n.name,t,`skill-duplicate`)||!ec(n.toName,t,`skill-duplicate`)||bc(n.toName,t,`skill-duplicate`))return;let r=ic(n.scope,n.name);if(r===null||!V(L(r,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?g:nc,a=z(i,ZB(i,n.scope)),o=z(a,n.toName);if(ic(n.scope,n.toName)!==null||V(o)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let s=iO(r);if(!s){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}ls(a,{recursive:!0}),fs(r,o,{recursive:!0,dereference:!0});let{fenced:c,body:l}=qn(s.skillMd),u=Aa(c,{name:n.toName});if(!u.ok){tF({skillsRoot:a,name:n.toName}),K(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:u.error.kind});return}try{vs(L(o,`SKILL.md`),`${u.nextFenced}${l}`)}catch(e){throw tF({skillsRoot:a,name:n.toName}),e}if(n.scope===`project`){let t=R(g,o).split(B).join(`/`);di(e,ui(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await gi(`skill-duplicate`)}Me?.(`files`),J(t,200,aee,{name:n.toName},{handler:`skill-duplicate`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),Rc=eW({GET:Oc,PUT:Ac,POST:Pc,DELETE:Nc},{handler:`skill`});function zc(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<1||t.some(e=>e===`..`)||t.length===1&&t[0].toLowerCase()===`skill.md`?null:t[0]===`references`&&t.length>=2?`reference`:t[0]===`scripts`&&t.length>=2?`script`:`file`}function Bc(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Vc(e,t){let n=t.replace(/\.md$/i,``);return`${$n(e).replace(/\/SKILL$/,``)}/${n}`}function Hc(e,t){let n=z(e,t,`references`);if(!V(n))return[];let r=[],i=(e,t)=>{for(let n of au(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(z(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function Uc(e,t,n){if(!ke){F(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=H(n,`utf-8`)}catch(i){F(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=R(g,e).split(B).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),z(e,n,`SKILL.md`));for(let r of Hc(e,n))i(o(t,r),o(n,r),z(e,n,r));await ke.recordDirectMutations(r)}async function Wc(e,t){if(!ke||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await ke.recordDirectMutations(n)}let Gc=eW({GET:q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ec(r,t,`skill-file-get`))return;let i=tc(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=gz(r)?i===`global`?nc:D:void 0,s=n.searchParams.get(`host`)??void 0,c=o?gc(o,r,s):null;if(a===``||a.includes(`\0`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:zc(a))??`reference`,u=s,d=o?c?.dir??null:ic(i,r,u);if(d===null&&u!==void 0){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${r}" (${i}) in ${u}.`});return}let f=d??z(rc(i),r),p=z(f,a);if(p!==f&&!p.startsWith(`${f}${B}`)){K(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let m=p,h=a;if(!V(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?on.map(t=>`${e[1]}${t}`).find(e=>e!==a&&V(z(f,e))):void 0;if(n===void 0){K(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}h=n,m=z(f,n)}let g=await wu(m);if(g.includes(0)){K(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}J(t,200,ei,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Di,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!ec(n.name,t,`skill-file-put`)||bc(n.name,t,`skill-file-put`))return;let r=zc(n.path);if(r===null){K(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){K(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=ic(n.scope,n.name);if(i===null||!V(L(i,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=R(n.scope===`project`?g:nc,i).split(B).join(`/`),o=n.path.replace(/\\/g,`/`),c=Bc(n.scope,r,o),l;if(c){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(Ws(e,`skill-file-put`,t))return;if(l=!V(z(i,o)),l&&QP(i)>=50){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:c,colorSeed:u,clientName:d}=Xr(n),f=await s.getSession(e,r,{displayName:c,colorSeed:u,clientName:d});f.dc.document.transact(()=>{sS(f.dc.document,n.content,`agent`)},f.origin);let p=await Bn(e);if(p?.kind===`failure`){Vn(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){Hn(t,`skill-file-put`);return}}else{let e=$P({skillsRoot:I(i),name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;K(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}l=e.created}n.scope===`project`&&(di(e,ui(`skill`,``,n.name),`${l?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),await gi(`skill-file-put`)),Me?.(`files`),J(t,200,Ree,{path:o,created:l,kind:r,content:c},{handler:`skill-file-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!ec(i,t,`skill-file-delete`)||bc(i,t,`skill-file-delete`))return;let a=tc(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=zc(o);if(s===null){K(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 c=ac(n,Ze);if(c.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let l=ic(a,i),u=l===null?rc(a):I(l);if(Bc(a,s,o)){let e=o.replace(/\.md$/i,``);await br([l===null?Vc(i,o):`${R(g,l).split(B).join(`/`)}/${e}`],`deleted-upstream`)}let d=eF({skillsRoot:u,name:i,relPath:o});if(!d.ok){let e=d.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:d.error.code,cause:Error(d.error.message)});return}d.existed&&a===`project`&&(di(c,ui(`skill`,``,i),`skill-file-delete: ${l===null?`${i}/${o}`:`${R(g,l).split(B).join(`/`)}/${o}`}`),await gi(`skill-file-delete`)),d.existed&&Me?.(`files`),J(t,200,Hi,{path:o,existed:d.existed,kind:s},{handler:`skill-file-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),Kc=q(In,async(e,t,n)=>{try{if(!ec(n.name,t,`skill-file-rename`)||bc(n.name,t,`skill-file-rename`))return;let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let r=n.from.replace(/\\/g,`/`),i=n.to.replace(/\\/g,`/`),a=zc(r),o=zc(i);if(a===null||o===null){K(t,400,`urn:ok:error:invalid-request`,`Both paths must live under references/ or scripts/ inside the skill.`,{handler:`skill-file-rename`,detail:a===null?r:i});return}let s=ic(n.scope,n.name);if(s===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let c=I(s),l=Bc(n.scope,a,r),u=Bc(n.scope,o,i),d=R(g,s).split(B).join(`/`),f=l?`${d}/${r.replace(/\.md$/i,``)}`:null,p=u?`${d}/${i.replace(/\.md$/i,``)}`:null;if(f!==null&&Ws(f,`skill-file-rename`,t))return;f!==null&&await br([f],`deleted-upstream`);let m=use({skillsRoot:c,name:n.name,relPath:r,toRelPath:i});if(!m.ok){let e=m.error.code===`RENAME_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,m.error.message,{handler:`skill-file-rename`,detail:m.error.code});return}if(ke){let e=[];if(f!==null&&p!==null)try{e.push({kind:`rename`,oldDocumentName:f,newDocumentName:p,markdown:H(z(c,n.name,i),`utf-8`)})}catch{e.push({kind:`delete`,documentName:f})}else if(f!==null)e.push({kind:`delete`,documentName:f});else if(p!==null)try{e.push({kind:`upsert`,documentName:p,markdown:H(z(c,n.name,i),`utf-8`)})}catch{}await ar(e,`skill-file-rename`)}n.scope===`project`&&(di(e,ui(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await gi(`skill-file-rename`)),Me?.(`files`),J(t,200,Kee,{from:r,to:i,...f===null?{}:{fromDocName:f},...p===null?{}:{toDocName:p}},{handler:`skill-file-rename`})}catch(e){X.error({err:e},`[skill-file-rename] failed`),t.headersSent||K(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function qc(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let Jc=XJ;function Yc(e,t){return iO(z(e,t))?.contentHash}async function Xc(e,t){let n=ge?.current;if(!(!n||!e))try{let r=HS(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
|
|
1215
|
-
`).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await gi(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Zc=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Qc(e){try{let t=wc(e.scope);if(!t)return;let n=fB(t);if(n.length===0)return;let r=yB(z(e.skillsRoot,e.name),e.name,t,n,`copy`,pB(e.scope));if(r.length===0)return;await TI(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function $c(e,t){if(t.ok){J(e,200,Yi,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}async function el(e){let{acquiredDir:t,scope:n,sourceLabel:r,ref:i,publisher:a,upstreamSkill:o,actor:s}=e;if(!D)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`No project root resolved.`,detail:`NO_PROJECT_ROOT`};let c=rO(t);if(c)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:c};let l=iO(t);if(!l)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let u=$Y(l);if(u)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:u};let d=L(n===`project`?D:nc,...XD),f=Jc(d),p=n===`project`?g:nc,m=ZB(p,n),h=z(p,m),_=Soe(f,l.contentHash);if(_&&ic(n,_)!==null)return{ok:!0,body:{name:_,path:`${_}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:r,ref:i,contentHash:l.contentHash,publisher:a},warnings:[]}};let v=DX(l.name),y=e=>ic(n,e)!==null||V(z(h,e,`SKILL.md`)),b=y(v),x=v;if(b){x=`${v}-imported`;let e=2;for(;y(x);)x=`${v}-imported-${e}`,e+=1}let S=qs(l.skillMd).body,C=XP({skillsRoot:h,name:x,body:S,frontmatter:{name:x,description:l.description}});if(!C.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write imported skill.`,detail:C.error.code,cause:Error(C.error.message)};let w=[...C.warnings];for(let e of l.files){let t=$P({skillsRoot:h,name:x,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:QY});if(!t.ok){let n=tF({skillsRoot:h,name:x});return{ok:!1,status:n.ok?400:500,urn:n.ok?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,title:`Failed to write the complete imported skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(n.ok?t.error.message:`${t.error.message}; rollback: ${n.error.message}`)}}}n===`project`&&(di(s,`${m}/${x}/SKILL`,`skill-import: ${r} -> ${m}/${x}/SKILL.md`),await gi(`skill-import`));let T=Yc(h,x),E=EO(r),ee=n===`project`?await Xc(Zc(s),`${m}/${x}`):void 0;if(await QJ(d,e=>$D(e,x,{source:r,...E?{pluginProvider:E.provider}:{},ref:i,contentHash:l.contentHash,files:l.files.map(e=>e.relPath),...T===void 0?{}:{localHash:T},...ee===void 0?{}:{baselineRef:ee},publisher:a,importedAt:new Date().toISOString(),...o===void 0?{}:{skill:o}})),e.skipProjection!==!0)try{let e=fB(p);if(e.length>0){let t=z(h,x),r=pB(n),i=e.filter(e=>{let n=mB(p,e,x,r);return n!==null&&n!==t&&V(n)}),a=i.filter(e=>{let t=mB(p,e,x,r);try{return t!==null&&$l(t).isSymbolicLink()}catch{return!1}});xB({canonicalAbs:t,canonicalHash:iO(t)?.contentHash??``,canonicalRootRel:m,name:x,cwd:p,targets:e,mode:pc(n,x,{hosts:[`<source>`,...i],linkedHosts:a}),roots:pB(n)})}}catch(e){F(`skill-import`).warn({err:e,skill:x},`post-import editor fan-out failed (import kept)`)}return Me?.(`files`),{ok:!0,body:{name:x,path:`${m}/${x}/SKILL.md`,created:C.created,alreadyImported:!1,...b?{collisionRenamedFrom:l.name}:{},provenance:{source:r,ref:i,contentHash:l.contentHash,publisher:a},warnings:w}}}let tl=q(Br,async(e,t,n)=>{let r=()=>{};try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l;{let e=n.source;try{let i=await lO(e,n.skill),u=i?.source??e,d=n.skill??i?.skill,f=i?.spec??qD(u);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(ZY(t,f,`skill-import`))return;let p=await YD(f);r=p.cleanup,s=p.ref;let m=aO(p.dir);if(m.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let h=m[0];if(d){let e=m.find(e=>e.name===d)??m.find(e=>nO(e.dir)?.name===d);if(!e){K(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${d}" not among: ${m.map(e=>e.name).join(`, `)}.`});return}h=e}else if(m.length>1){K(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:m.map(e=>e.name).join(`, `)});return}a=h.dir,l=h.name,o=e,c=i?.publisher??qc(u)}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}$c(t,await el({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),nl=q(bt,async(e,t,n)=>{let r=()=>{};try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l;try{let e=await lO(i,n.skills[0]),u=e?.source??i,d=e?.spec??qD(u);if(!d){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(ZY(t,d,`skills-import-bulk`))return;if(l=e?.publisher??qc(u),d.kind===`well-known`)a=d,o=await GD(d.origin);else{let e=await YD(d);r=e.cleanup,c=e.ref,s=aO(e.dir)}}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let u=[];for(let t of new Set(n.skills)){let r,d,f=()=>{};if(a!==null)try{let e=await YD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,d=t}catch(e){u.push({requested:t,status:e instanceof zD?`not-found`:`failed`,warnings:[],...e instanceof zD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>iO(e.dir)?.name===t);if(!e){u.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,d=e.name}try{let a=await el({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:d,actor:e,skipProjection:n.install===!1});if(!a.ok){F(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}u.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){F(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}J(t,200,kt,{results:u,imported:u.filter(e=>e.status===`imported`).length,alreadyImported:u.filter(e=>e.status===`already-imported`).length,failed:u.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),rl=8*1024*1024,il=32*1024*1024;function al(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=z(e,n);return r!==e&&!r.startsWith(e+B)?null:r}function ol(e){return new Promise((t,n)=>{let r;try{r=(0,HO.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:rl}})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>il){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function sl(e,t){return new Promise((n,r)=>{(0,ij.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=al(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){ls(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>rl){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>il){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{ls(I(n),{recursive:!0}),vs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function cl(e,t){let n=tu(L(yu(),`ok-skill-upload-`)),r=()=>{try{ps(n,{recursive:!0,force:!0})}catch{}};try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=tc(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=pM({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},Ze);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await ol(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await sl(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=al(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}ls(I(r),{recursive:!0}),vs(r,e.data)}let u=aO(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];$c(t,await el({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let ll=q(wee,async(e,t,n)=>{try{let e=rc(n.scope);if(!ec(n.name,t,`skill-install`))return;if(n.scope===`project`&&!D){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=wc(n.scope),i=z(e,n.name),a=n.scope===`project`?g:nc,o=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name),s=o?z(a,o.dir):i;if(!V(s)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Bn(n.scope===`project`?`${R(a,s).split(B).join(`/`)}/SKILL`:Qi(n.scope,n.name));let c=uB(s,n.name);if(!c.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){let e=[];if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let r=n.scope===`project`?be:Ve,i=n.fork.editor===`agents`?`.agents/skills`:r[n.fork.editor]??null;if(i===null){K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:n.fork.editor});return}let s=z(a,i,n.name),c=z(a,o.dir),l=iO(s);if(l===null||s===c){K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return}if(l.contentHash===o.contentHash){K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return}let u=new Date().toISOString().replace(/[:.]/g,`-`),d=(e,t)=>{try{let r=z(nc,`.ok`,`edit-backups`,`forks`,`${n.name}-${t}-${u}`);ls(z(r,`..`),{recursive:!0}),fs(e,r,{recursive:!0})}catch(e){X.warn({name:n.name,err:e},`[skill-fork] stash failed`)}};if(n.fork.action===`align`)d(s,n.fork.editor),ps(s,{recursive:!0,force:!0}),xB({canonicalAbs:c,canonicalHash:o.contentHash,canonicalRootRel:I(o.dir),name:n.name,cwd:a,targets:[n.fork.editor].filter(yn),roots:pB(n.scope)});else if(n.fork.action===`make-source`){let e=o.hosts.filter(yn);d(c,`source`),wB({canonicalAbs:c,canonicalHash:o.contentHash,name:n.name,cwd:a,targets:e,roots:pB(n.scope)}),ps(c,{recursive:!0,force:!0});let t=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name);t&&xB({canonicalAbs:z(a,t.dir),canonicalHash:t.contentHash,canonicalRootRel:I(t.dir),name:n.name,cwd:a,targets:e,roots:pB(n.scope)})}else{let r=n.fork.toName;if(!nt.test(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:r});return}if((n.scope===`project`?nV(g):rV(nc)).some(e=>e.name===r)){K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:r});return}let o=z(a,i,r);ns(s,o);let c=z(o,`SKILL.md`);try{let{fenced:t,body:n}=qn(H(c,`utf-8`)),i=Aa(t,{name:r});i.ok?vs(c,`${i.nextFenced}${n}`):(X.warn({name:r,reason:i.error.kind},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md still declares the old name — edit the frontmatter to match.`))}catch(t){X.warn({name:r,err:t},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md could not be updated — edit the frontmatter to match.`)}}Me?.(`files`),J(t,200,mi,{name:n.name,hosts:o.hosts.filter(yn),scripts:!1,warnings:e,warningCodes:e.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let l=n.setSource??n.source,u=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),d=n.targets,f=[],p=[];if(n.add!==void 0||n.remove!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=e=>e.replace(/\\/g,`/`).replace(/^~\//,``),r=o.hosts[0];if(r!==void 0&&(n.remove??[]).some(t=>e(t)===r)){K(t,400,`urn:ok:error:invalid-request`,`"${r}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`});return}let i=new Set(o.hosts.filter(e=>yn(e)));for(let t of n.add??[])yn(t)?i.add(t):f.push(e(t));let s=GB(a,n.scope),c=[],l=[];for(let e of n.add??[])if(yn(e)&&s[e]!==void 0&&!V(z(a,s[e],n.name,`SKILL.md`))){let t=e===`agents`?`.agents/skills`:(n.scope===`project`?be:Ve)[e]??null;t!==null&&l.push(t)}for(let t of n.remove??[])if(yn(t)){if(!i.has(t)&&s[t]!==void 0&&V(z(a,s[t],n.name,`SKILL.md`))){let e=t===`agents`?`.agents/skills`:(n.scope===`project`?be:Ve)[t]??null;e!==null&&c.push(e)}i.delete(t)}else p.push(e(t));for(let{subRoot:e,exclude:r}of[...l.map(e=>({subRoot:e,exclude:void 0})),...c.map(e=>({subRoot:e,exclude:[n.name]}))]){let n=PJ({base:a,folderRel:e,...r===void 0?{}:{exclude:r}});if(n.ok&&await IJ(a,e,{expect:`own`}),!n.ok){K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e} following its pool (${n.reason}).`,{handler:`skill-install`,detail:n.reason});return}}d=[...i]}if(l&&!o){let e=l,i=SB({canonicalAbs:s,canonicalHash:iO(s)?.contentHash??``,name:n.name,cwd:a,newTarget:e,roots:pB(n.scope)});if(!i.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:i.reason});return}await EI(r,n.name),await FJ(a,n.name,e),Me?.(`files`);let o=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name);J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:R(a,i.newAbs).split(B).join(`/`)},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?D:nc;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.place.dir.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),i=z(e,r),a=`${r}/${n.name}`,l=AB(e,a),u=z(e),d=oc(r);if(r===``||l===null||!l.startsWith(u+B)||d){K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}if(l===z(s)){J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:a},{handler:`skill-install`});return}if(V(l)){K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}ls(i,{recursive:!0}),n.place.mode===`link`?as(R(i,z(s)),l,`dir`):fs(s,l,{recursive:!0,dereference:!0});let f=a;await HJ(e,n.name,{path:f,mode:n.place.mode,...n.place.mode===`copy`?{hash:iO(s)?.contentHash}:{}}),Me?.(`files`),J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:f},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?D:nc;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.unplace.path.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``);if(!BJ(e)[n.name]?.find(e=>e.path===r)){K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r});return}let i=AB(e,r);if(i===null){K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}let a=iO(s)?.contentHash??``;switch(bB(i,z(s),a)){case`different`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r});return;case`absent`:break;default:ps(i,{recursive:!0,force:!0})}await VJ(e,n.name,r),Me?.(`files`),J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?D:nc,l=pB(n.scope),u=yn(e)?e===`agents`?`.agents/skills`:l[e]:e.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),d=u===null||u===``?null:AB(a??r,`${u}/${n.name}`);if(u===null||u===``||d===null){K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return}let f=z(s),p=o.contentHash,m=bB(d,f,p);if(m===`canonical-dir`){K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return}if(m===`different`){K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return}if(m===`absent`){K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return}let h=i===`link`&&m===`link-to-canonical`||i===`copy`&&m===`same-copy`;if(h&&await HJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}}),!h){let e=I(d);ps(d,{recursive:!0,force:!0}),ls(e,{recursive:!0}),i===`link`?as(R(e,f),d,`dir`):fs(f,d,{recursive:!0,dereference:!0}),await HJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}})}Me?.(`files`),J(t,200,mi,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let m=n.scope===`global`?d?Rt.filter(e=>d?.some(t=>t===e)):[...Rt]:d===void 0?fB(r):Rt.filter(e=>d?.some(t=>t===e)),h=[],_=[];if(m.length===0&&d===void 0&&(h.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),c.hasScripts&&(h.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),c.warnings.length>0&&(h.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=d?.includes(`agents`)===!0?[...m,`agents`]:[...m],v=n.scope===`project`?D:nc,y=u===void 0?pc(n.scope,n.name,o):u?`link`:`copy`;if(l){let e=o.hosts[0],i=l,u=yn(i),d;if(!u){let e=i.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),a=oc(e),o=z(r,e,n.name);if(e===``||a||!o.startsWith(z(r)+B)){K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:i});return}d=o}let f;if(e!==void 0&&i!==e){let e=R(a,z(s)).split(B).join(`/`),c=SB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:u?i:`agents`,...d===void 0?{}:{destDirAbs:d},leaveLinkBehind:!0,roots:pB(n.scope)});if(!c.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}f=R(a,c.newAbs).split(B).join(`/`),await HJ(v??r,n.name,{path:e,mode:`link`});for(let e of BJ(v??r)[n.name]??[]){let t=z(v??r,e.path);if(t===c.newAbs)continue;try{if(!$l(t).isSymbolicLink())continue}catch{continue}let n=null;try{n=U(t)}catch{n=null}(n===null||n===z(s))&&(ps(t,{recursive:!0,force:!0}),as(R(I(t),c.newAbs),t,`dir`))}await HJ(v??r,n.name,{path:f,mode:`copy`}),await FJ(v??r,n.name,i)}Me?.(`files`);let p=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name);J(t,200,mi,{name:n.name,hosts:p?[...p.hosts]:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[],...f===void 0?{}:{sourceMovedTo:f}},{handler:`skill-install`});return}let b=o.hosts.filter(e=>yn(e)),x=o.hosts[0],S;if(d!==void 0&&x!==void 0&&!x.includes(`/`)&&i.length>0&&!i.includes(x)){let e=i[0],c=SB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:e,roots:pB(n.scope)});if(!c.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}s=c.newAbs,S=R(a,c.newAbs).split(B).join(`/`),await HJ(v??r,n.name,{path:S,mode:`copy`}),await FJ(v??r,n.name,e)}let C=S?S.split(`/`).slice(0,-1).join(`/`):e;wB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,targets:d===void 0?[]:b.filter(e=>!i.includes(e)),roots:pB(n.scope)});let w=xB({canonicalAbs:s,canonicalHash:o.contentHash,canonicalRootRel:C,name:n.name,cwd:r,targets:i,mode:y,convertLinks:u===!1,roots:pB(n.scope)});for(let e of w.conflicted)h.push(`A different skill named "${n.name}" already exists in the ${e} skills folder — left untouched.`),_.push(`name-conflict`);if(u!==void 0&&v&&f.length>0){let e=new Set(f.map(e=>`${e}/${n.name}`));for(let t of(BJ(v)[n.name]??[]).filter(t=>e.has(t.path))){let e=z(v,t.path);if(e===z(s))continue;let r=bB(e,z(s),o.contentHash);u===!0&&r===`same-copy`?(ps(e,{recursive:!0,force:!0}),as(R(I(e),z(s)),e,`dir`),await HJ(v,n.name,{path:t.path,mode:`link`})):u===!1&&r===`link-to-canonical`&&(ps(e,{recursive:!0,force:!0}),fs(z(s),e,{recursive:!0,dereference:!0}),await HJ(v,n.name,{path:t.path,mode:`copy`,hash:o.contentHash}))}}for(let t of w.hosts){let i=t===`agents`?`.agents/skills`:be[t];if(i===null||i===e)continue;let a=z(r,i,n.name),s=!1;try{s=$l(a).isSymbolicLink()}catch{continue}if(s){y===`link`&&await HJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`link`});continue}let c=V(L(a,`SKILL.md`))?iO(a)?.contentHash:void 0;c!==void 0&&c===o.contentHash&&await HJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`copy`,hash:c})}if((f.length>0||p.length>0)&&v){let e=z(s);for(let t of f){let r=oc(t),i=z(v,t),a=AB(v,`${t}/${n.name}`);if(t===``||r||a===null||a===e){h.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=bB(a,e,o.contentHash);if(s===`different`){h.push(`A different "${n.name}" already exists at ${t} — left untouched.`),_.push(`name-conflict`);continue}s===`absent`&&(ls(i,{recursive:!0}),y===`link`?as(R(i,e),a,`dir`):fs(e,a,{recursive:!0,dereference:!0})),await HJ(v,n.name,{path:`${t}/${n.name}`,mode:y,...y===`copy`?{hash:o.contentHash}:{}})}for(let t of p){let r=`${t}/${n.name}`,i=BJ(v)[n.name]?.find(e=>e.path===r),a=AB(v,r);if(a===null){h.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=bB(a,e,o.contentHash);if(s===`different`){h.push(`The copy at ${r} has been hand-edited (a fork) — refused, never deleted. Remove it manually if you mean it.`),_.push(`place-fork-refused`);continue}s!==`absent`&&s!==`canonical-dir`&&ps(a,{recursive:!0,force:!0}),i&&await VJ(v,n.name,r)}}let T=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name),E=T?[...T.hosts]:w.hosts;Me?.(`files`),J(t,200,mi,{name:n.name,hosts:E,scripts:c.hasScripts,warnings:h,warningCodes:_,...S===void 0?{}:{sourceMovedTo:S}},{handler:`skill-install`});return}let v=aB(CI(r).skills[n.name]?.hosts??[]).filter(e=>!m.includes(e));v.length>0&&TB(n.name,r,v,pB(n.scope));let y=L(r,...XD),b=V(y)?H(y,`utf-8`):null,x=b===null?null:QD(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=u===void 0?S?`copy`:`symlink`:u?`symlink`:`copy`,w=yB(s,n.name,r,m,C,pB(n.scope));w.length===0?await EI(r,n.name):await TI(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),Me?.(`files`),J(t,200,mi,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:h,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ul=q(Vee,async(e,t,n)=>{try{if(!ec(n.name,t,`skill-uninstall`))return;let e=wc(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await Tc(e,n.name,n.scope);Me?.(`files`),J(t,200,pt,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),dl=eW({GET:q(jn,async(e,t)=>{try{let e=fB(D??``),n=(e,t)=>{let n=LJ(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,nee,{targets:e,configured:!1,folders:[...D?kJ(g,JB(g,`project`)).map(e=>({...e,scope:`project`,...n(g,e)})):[],...kJ(nc,JB(nc,`global`)).map(e=>({...e,scope:`global`,...n(nc,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Fr,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?g:nc;if(e.scope===`project`&&!D){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await RJ(r,i.join(`/`)),Me?.(`files`),J(t,200,p,{targets:fB(D??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(JB(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?NJ({base:r,folderRel:e.root,targetRootRel:a}):PJ({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await IJ(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),Me?.(`files`),J(t,200,p,{targets:fB(D??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),fl=q(T,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!ec(n.name,t,`skill-restore`)||bc(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=ge?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await KJ({shadow:r,contentDir:g,contentRoot:De??`.`,name:n.name,version:n.version,skillDirRel:mc(n.name)});if(!i.ok){fc(t,i,`skill-restore`);return}let a=[],o=uB(z(g,mc(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),di(e,ui(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await gi(`skill-restore`),Me?.(`files`),J(t,200,da,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),pl=q(ya,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!ec(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?nc:g,{root:a,dirRel:o,realDir:s}=jc(n.scope,n.name),c=!o.startsWith(`${gn}/`);if(s===null||!V(z(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let l=L(n.scope===`global`?nc:D,...XD),u=Jc(l).skills[n.name];if(!u){let e=xoe(n.name,iO(z(a,n.name))?.contentHash??``,new Date().toISOString())??vc(i,n.name);e&&(u=e)}if(!u){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await QJ(l,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??u,autoUpdate:n.setAutoUpdate}}})),J(t,200,Ut,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let d,f=null,p=!1;try{let e=await lO(u.source,u.skill??n.name),i=e?.source??Zoe(u.source,u.pluginProvider),a=e?.skill??u.skill,o=e?.spec??qD(i);if(!o){K(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:u.source});return}if(ZY(t,o,`skill-reimport`))return;let s=await YD(o);r=s.cleanup,d=s.ref;let c=aO(s.dir),l=(a?c.find(e=>e.name===a):void 0)??c.find(e=>e.name===n.name)??c.find(e=>iO(e.dir)?.name===n.name)??(c.length===1?c[0]:void 0);if(!l){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:c.map(e=>e.name).join(`, `)});return}let p=rO(l.dir);if(p){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:p});return}f=iO(l.dir)}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!f){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let m=$Y(f);if(m){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:m});return}p=f.files.some(e=>e.relPath.startsWith(`scripts/`));let h=iO(z(a,n.name)),_=new Set(f.files.map(e=>e.relPath)),v=new Set((h?.files??[]).map(e=>e.relPath)),y=(u.files??(u.localHash!==void 0&&h?.contentHash===u.localHash?h.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(f.contentHash===u.contentHash&&y.length===0){J(t,200,Ut,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let b=qs(f.skillMd).body;if(n.dryRun){let e=iO(z(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&D)try{let e=Ms({baseDir:D,timeout:{block:15e3}}),t=R(D,z(a,n.name)).split(B).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}J(t,200,Ut,{name:n.name,updated:!0,source:u.source,localBody:qs(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await br(e,`deleted-upstream`)}let x=XP({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:f.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of f.files){let r=$P({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:QY});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=eF({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(di(e,ui(`skill`,``,n.name),`skill-reimport: ${u.source} -> ${o}`),await gi(`skill-reimport`));let C=Yc(a,n.name),w=n.scope===`project`?await Xc(Zc(e),o):void 0;await QJ(l,e=>$D(e,n.name,{...e.skills[n.name]??u,contentHash:f.contentHash,files:f.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:d,importedAt:new Date().toISOString()})),!c&&n.scope===`project`&&await Qc({skillsRoot:a,name:n.name,scope:`project`,hasScripts:p,handler:`skill-reimport`}),Me?.(`files`),J(t,200,Ut,{name:n.name,updated:!0,source:u.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),ml=q(Zt,async(e,t,n)=>{try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!ec(n.name,t,`skill-revert`)||bc(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=L(D,...XD),i=Jc(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=ge?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await KJ({shadow:a,contentDir:g,contentRoot:De??`.`,name:n.name,version:i.baselineRef,skillDirRel:mc(n.name)});if(!o.ok){fc(t,o,`skill-revert`);return}di(e,ui(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await gi(`skill-revert`);let s=z(g,mc(n.name),`..`),c=Yc(s,n.name);await QJ(r,e=>$D(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===rc(`project`)&&await Qc({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),Me?.(`files`),J(t,200,fe,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function hl(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])=>h({kind:`folder`,path:e,modifiedTs:t}))}function gl(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 _l(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function vl(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 yl(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function bl(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function xl(e,t,n,r){let i=r.documents.filter(e=>!Oi(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!wt?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};wt.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await wt.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Tt?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=wt.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function Sl(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`?gl(e.document.content,t):void 0}}async function Cl(e){let t=performance.now();if(Ml())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await Nl(),i=await xl(e.query,e.intent,e.semanticParam,n),a=uee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>Sl(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},Hse({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 wl(){let e=[],t=new Set;for(let n of nV(g)){let r=z(g,n.dir,`SKILL.md`);try{let i=uu(r);e.push({name:n.name,absolutePath:r,docPath:`${n.dir}/SKILL`,mtimeMs:i.mtimeMs,size:i.size}),t.add(n.name)}catch{}}let n=rc(`project`);if(!V(n))return e;let r;try{r=au(n,{withFileTypes:!0})}catch{return e}for(let i of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!i.isDirectory()||!nt.test(i.name)||t.has(i.name))continue;let r=z(n,i.name,`SKILL.md`);try{let t=uu(r);e.push({name:i.name,absolutePath:r,docPath:`${gn}/${i.name}/SKILL`,mtimeMs:t.mtimeMs,size:t.size})}catch{}}return e}function Tl(){let e=[];for(let t of wl()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=qs(H(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(h({kind:`page`,path:t.docPath,title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function El(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Dl=new Map;async function Ol(){let e=[],t=[],n=new Set;for(let[r,i]of C()){if(dC(r)||fC(r)||Li(r)?.kind===`skill`||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(h({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=El(i),o=Dl.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await wu(i.canonicalPath,`utf-8`)}catch(e){l=!0,X.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=ER(s,r)}catch(e){X.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=h({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Dl.set(r,{key:a,doc:u}),e.push(u)}for(let e of Dl.keys())n.has(e)||Dl.delete(e);let r=zX(),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`),pX().add(1)),{documents:[...e,...Tl(),...i,...hl([...e,...i])],truncated:a}}function kl(){return wl().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Al(){return E?`gen:${E()}|skills${kl()}`:`${[...C()].filter(([e])=>!dC(e)&&!fC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${El(t)}`).join(``)}|skills${kl()}`}let jl=gt===void 0;gt?.then(()=>{jl=!0},e=>{jl=!0,X.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Ml(){return!jl}async function Nl(){let e=`${g}${D??``}`,t=Al(),n=TZ.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 Ol();if(!e)return hX().add(1,{mode:`cold`}),{corpus:ja(t),truncated:n};let a=Ae(e,t);if(a.rebuilt){hX().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 hX().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}})();TZ.set(e,{fingerprint:t,pending:a});try{let n=await a;return TZ.get(e)?.pending===a&&TZ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw TZ.get(e)?.pending===a&&TZ.delete(e),t}}function Pl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Nl().catch(e=>{X.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}Pl();let Fl=eW({GET:q(jn,$U(async(e,t)=>{let n=Zee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=_l(n.get(`intent`)),o=Sc(n.get(`ranking`)),s=vl(n.get(`scope`)??n.get(`scopes`)),c=yl(n.get(`semantic`)),l=bl(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,Ye,await Cl({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Ci,$U(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=_l(n.intent),a=Sc(n.ranking),o=vl(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=yl(n.semantic),l=bl(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,Ye,await Cl({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`}),Ll=q(jn,$U(async(e,t)=>{J(t,200,jee,{...await Kz(gu())},{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 Rl(e,t){if(r(e,t,{handler:`handoff`}))try{await xce(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:sn.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:MC(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Bl(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await aI(e,t,{contentDir:g,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:MC(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Ul=q(pee,async(e,t,n)=>{try{if(!D){FR(`no-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`no-remote`},{handler:jR});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!MR(e,n.kind)){FR(`invalid-path`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`invalid-path`},{handler:jR});return}let r=BR(D);if(r===null){if(WR(D).kind===`no-remote`){FR(`no-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`no-remote`},{handler:jR});return}FR(`detached-head`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`detached-head`},{handler:jR});return}let i=WR(D);if(i.kind===`no-remote`){FR(`no-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`no-remote`},{handler:jR});return}if(i.kind===`non-github`){FR(`non-github-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`non-github-remote`},{handler:jR});return}if(!JR(D,r)){FR(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,we,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:jR});return}let a=_Z(D,g);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=NR(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=PR(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Wh(s)}`,l=await LR(D,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);FR(`ok`,{branchExists:!0,kind:n.kind,freshness:l}),J(t,200,we,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:l},{handler:jR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:jR,cause:e})}},{handler:jR,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jR})}),Wl=q(jn,async(e,t)=>{try{if(!D){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:zU});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(!ti(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:zU});return}if(!LU(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:zU});return}J(t,200,dee,await RU(D,r,i,a),{handler:zU})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zU,cause:e})}},{handler:zU,method:`GET`,skipBodyParse:!0}),Gl=q(Sn,async(e,t,n)=>{try{if(!D){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:uz});return}if(!LU(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:uz});return}let e=_Z(D,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;J(t,200,Nt,await pz(D,n.branch,r,n.kind),{handler:uz})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:uz,cause:e})}},{handler:uz,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:uz})}),Kl=q(je,async(e,t,n)=>{if(pM(n,Ze).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:WU});return}if(!D){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:WU});return}try{J(t,200,nn,await Ns(()=>KU(D,n.branch,{fastForward:n.fastForward===!0})),{handler:WU})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:WU,cause:e})}},{handler:WU,method:`POST`});async function ql(e){let[t,...n]=Ke,r=[...n,...e];return await new Promise((e,n)=>{let i=Il(t,r,ZF({...go,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},QR),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 ${QR}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=lz(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Jl=q(jn,async(e,t)=>{if(!Bt.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:YR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ql([`share`,`owners`,`--json`]),n=nz(tz(e));cz(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,Ge,n,{handler:YR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:YR,cause:e})}finally{Bt.release(`/api/share/publish/owners`)}},{handler:YR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:YR})}),Yl=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!ez(r)||!$R(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:XR});return}if(!Bt.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:XR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ql([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=iz(tz(e));cz(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,vi,n,{handler:XR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:XR,cause:e})}finally{Bt.release(`/api/share/publish/name-check`)}},{handler:XR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:XR})}),Xl=q(yee,async(e,t,n)=>{if(!D){cz(`publish-create`,`no-project`),J(t,200,mn,{ok:!1,error:`no-project`},{handler:ZR});return}if(!ez(n.owner)||!$R(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:ZR});return}if(!Bt.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:ZR,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,D,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await ql(e),i=sz(tz(r));cz(`publish-create`,i.ok?`ok`:i.error),i.ok&&Ue?.()?.refreshRemote().catch(()=>{}),J(t,200,mn,i,{handler:ZR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:ZR,cause:e})}finally{Bt.release(`/api/share/publish`)}},{handler:ZR,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ZR})}),Ql=q(Xt,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,de,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),nu=D?iN(D):null;async function ru(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:fM(e.headers),previewUrl:null,port:nu?Gs(nu)?.port??0:0,singleFile:Pt};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,dt,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let iu=`local-op-embeddings-set-key`,ou=`local-op-embeddings-clear-key`,su=`/api/local-op/embeddings`;function cu(){let e=At?.();return{projectDir:D??g,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let lu=q(Si,async(e,t,n)=>{if(!Bt.tryAcquire(su)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:iu,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=cu();await new GF(Et).setForProject(e,r,n.key),wt?.reloadCredential(),J(t,200,tt,{keyPresent:!0},{handler:iu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:iu,cause:e})}finally{Bt.release(su)}},{handler:iu,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:iu})}),pu=q(jn,async(e,t)=>{if(!Bt.tryAcquire(su)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:ou,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=cu();await new GF(Et).clearForProject(e,n),wt?.reloadCredential(),J(t,200,tt,{keyPresent:!1},{handler:ou,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:ou,cause:e})}finally{Bt.release(su)}},{handler:ou,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ou})}),mu=`local-op-embeddings-test`,hu=`/api/local-op/embeddings/test`,_u=q(jn,async(e,t)=>{if(!Bt.tryAcquire(hu)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:mu,extraHeaders:{"Retry-After":`5`}});return}try{let e=At?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await RF(new GF(Et),D??g,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Zse({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,Je,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:mu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:mu,cause:e})}finally{Bt.release(hu)}},{handler:mu,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:mu})}),vu=q(jn,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(wt){let t=wt.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=At?.()?.baseUrl??`https://api.openai.com/v1`,o=await RF(new GF(Et),D??g,a),s=o.apiKey!==null,c=!s&&o.keyless,l=s?o.source:null,u=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,d=0;for(let[e]of x())!dC(e)&&!fC(e)&&!Oi(e)&&(d+=1);J(t,200,bee,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:l,keyHint:u,ready:n,capable:r,embedded:i,total:d},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),bu=0;function xu(){bu+=1,Me?.(`lint-config`)}let Su=()=>`${bu} ${t.getActiveBranch()}`;async function Cu(e,t){let n=jt?.()??hr;try{let r=await vn(e,$L(g,n,{docName:t,projectDir:D??g,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Mt?.()??`warning`;if(ke&&a!==`off`&&!gC(t)){await sr(t,e,`lint-validation`);let r=fR({projectDir:D??g,contentDir:g,baseConfig:n,derivedDocumentIndex:ke,linksValidation:a,admittedDocNames:er,docFilePathFor:e=>cZ(g,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:cZ(g,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 X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Tu(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=nR({projectDir:D??g,contentDir:g});return TL(t.schemas,n)}let Eu=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!DZ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=jt?.()??hr,i=[],a=XL(g,n??void 0,e=>i.push(e)),o=QL(D??g,ZL(r,a),e=>i.push(e));n===null&&i.push(...Tu(o)),J(t,200,Yn,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Du=q(kee,async(e,t,n)=>{let r;try{r=dR(z(g),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}xu();try{let e=jt?.()??hr,n=[],r=XL(g,void 0,e=>n.push(e)),i=QL(D??g,ZL(e,r),e=>n.push(e));n.push(...Tu(i)),J(t,200,Yn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Ou=q(Pn,async(e,t,n)=>{let r;try{let e=z(D??g),t=n.parentPath??[];r=n.delete?Ile(e,n.file):n.field!==void 0&&n.removeField?Ple(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Fle(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Mle(e,n.file,n.field,n.constraint,t):Nle(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Me?.(`files`),xu();try{let e=jt?.()??hr,n=[],r=XL(g,void 0,e=>n.push(e)),i=QL(D??g,ZL(e,r),e=>n.push(e));n.push(...Tu(i)),J(t,200,Yn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),ku=q(jn,async(e,t)=>{try{let e=z(D??g),{schemas:n,truncated:r}=sle(e),i=new Set(n),a=!1;if(lt!==void 0){let t=GX({contentDir:g,contentFilter:lt,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&&Qr(a)){let t=R(e,z(g,a));!t.startsWith(`..`)&&!Hl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,Gee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Au=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},ju=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!DZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=cZ(g,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=jt?.()??hr,a=[],o=await tR({projectDir:D??g,contentDir:g,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Au});J(t,200,Rr,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof KI){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Mu=new xL,Nu=OJ();function Pu(e,t,n){let r=`${n} ${Su()} ${t??``}`;return Nu.run(r,()=>Ble(e,{targetPath:t})).promise}function Fu(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Iu=q(jn,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&&!qX(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=jt?.()??hr;J(t,200,Ni,await rR({projectDir:D??g,contentDir:g,baseConfig:i,targetPath:r,liveSourceFor:Au,cache:Mu,auditGeneration:Su}),{handler:`lint-audit`})}catch(e){if(e instanceof eR){Fu(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),Ru=q(jn,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&&!qX(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!qX(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=cZ(g,o)??`${o}.md`}let s=jt?.()??hr,c=await Pu(fR({projectDir:D??g,contentDir:g,baseConfig:s,liveSourceFor:Au,derivedDocumentIndex:ke??null,linksValidation:Mt?.(),admittedDocNames:er,docFilePathFor:e=>cZ(g,e),cache:Mu,auditGeneration:Su}),i,xL.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){J(t,200,fi,zle(c),{handler:`audit`});return}J(t,200,Gr,c,{handler:`audit`})}catch(e){if(e instanceof eR){Fu(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),zu=q(qi,async(t,n,r)=>{try{let t=QX(r.docName,n,`lint-fix`);if(t===null)return;let i=Dn(t),a=pM(r,Ze);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,l=a.kind===`anonymous`?o:a.colorSeed,u=a.kind===`agent`?a.clientName:void 0;if(dC(i)||fC(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let d=cZ(g,i);if(d===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}$X(z(g,d),g);let f=jt?.()??hr,{stored:p}=ii(a.summary),m=await s.getSession(i,o,{displayName:c,colorSeed:l,clientName:u}),h=m.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Ole({projectDir:D??g,contentDir:g,baseConfig:f,docRelPath:d,source:h}),b=v,x;if(y!==h){try{let t=tr(u),n=Jn[t]??Lr(l??o);Le?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),m.dc.document.transact(()=>{YT(m.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,qT(m))},m.origin),a.kind!==`anonymous`&&yF(i,o,c,l,void 0,a.kind===`agent`?Zr({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,p)}finally{Le?.touchMode(o,`idle`)}let t=await Bn(i);if(t?.kind===`failure`){Vn(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Hn(n,`lint-fix`);return}zn(i,`lint-fix`);try{b=await vn(m.dc.document.getText(`source`).toString(),_,d)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,nr,{file:d,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 KI){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof BC){VC(n,e,`lint-fix`);return}if(e instanceof GC){qC(n,e,`lint-fix`);return}if(e instanceof nE){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Bu=`link-preview`,Vu=new sG({cacheDir:Pt?null:z(D??g,`.ok`,`local`,`link-previews`)}),Hu=null,Uu=()=>(Hu??=Vu.init(),Hu),Wu=Lt??QW;async function Ku(e){let t=await Wu(e);return t.ok?{ok:!0,metadata:await rG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Wu})}:{ok:!1,reason:t.reason}}let Ju=()=>{try{return zt?.()===!0}catch{return!1}},Yu=q($r,async(e,t,n)=>{try{if(!Ju()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,Ei,{ok:!1,reason:`disabled`},{handler:Bu});return}await Uu();let e=!1,r=await Vu.load(n.url,()=>(e=!0,Ku(n.url)));Vu.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,Ei,i,{handler:Bu})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Bu,cause:e})}},{handler:Bu,method:`POST`,preBodyGate:(e,t)=>{let n=uG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Bu}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Bu}),!1)}}),Xu=KM({service:un,getPrincipal:Ze,onChanged:()=>Me?.(`comments`)}),Zu={"/api/config":ru,"/api/comments":eW({GET:Xu.list,POST:Xu.create},{handler:`comments`}),"/api/comment":eW({GET:Xu.read,POST:Xu.mutate,DELETE:Xu.remove},{handler:`comment`}),"/api/asset":Xa,"/api/asset-text":$a,"/api/document":Ai,"/api/documents":ji,"/api/backlinks":Mi,"/api/backlink-counts":$i,"/api/comment-counts":ta,"/api/link-preview":Yu,"/api/forward-links":na,"/api/link-graph":ia,"/api/dead-links":la,"/api/orphans":oa,"/api/hubs":sa,"/api/tags":Fs,"/api/pages":O,"/api/folder-config":Hs,"/api/template":Qs,"/api/template/import":$s,"/api/templates":Ks,"/api/skill":Rc,"/api/skill-file":Gc,"/api/skill-file/rename":Kc,"/api/skills":Dc,"/api/skills/installed":Fi,"/api/skills/search":Ri,"/api/skills/popular":zi,"/api/skills/detail":Bi,"/api/skills/preview":Vi,"/api/skills/discover":Gi,"/api/skills/resolve-ref":Ki,"/api/skill/import":tl,"/api/skills/import-bulk":nl,"/api/skill/edit-external":Fc,"/api/skill/duplicate":Lc,"/api/skill/move-scope":Ic,"/api/skill-upload":cl,"/api/skill/install":ll,"/api/skill/uninstall":ul,"/api/skill/restore":fl,"/api/skill/reimport":pl,"/api/skill/revert":ml,"/api/skill-targets":dl,"/api/search":Fl,"/api/semantic-status":vu,"/api/lint/config":Eu,"/api/lint/markdownlint-config":Du,"/api/lint/frontmatter-schema":Ou,"/api/lint/frontmatter-schemas":ku,"/api/lint":ju,"/api/lint/audit":Iu,"/api/lint/fix":zu,"/api/audit":Ru,"/api/suggest-links":uo,"/api/page-headings":oo,"/api/create-page":to,"/api/create-folder":ro,"/api/duplicate-path":io,"/api/rename-path":so,"/api/delete-path":co,"/api/trash/cleanup":lo,"/api/upload":fo,"/api/agent-write":_i,"/api/agent-write-md":yi,"/api/agent-write-batch":xi,"/api/frontmatter-patch":wi,"/api/agent-patch":ua,"/api/agent-undo":fa,"/api/agent-activity":ma,"/api/agent-burst-diff":ha,"/api/save-version":wa,"/api/history":Ta,"/api/rollback":ka,"/api/metrics/reconciliation":Fa,"/api/metrics/parse-health":La,"/api/metrics/agent-presence":Wa,"/api/metrics/agent-effects":Ga,"/api/metrics/watcher-recent":Ka,"/api/__embed-detect":Ja,"/api/server-info":Ra,"/api/acp/catalog":Va,"/api/share/construct-url":Ul,"/api/share/target-status":Gl,"/api/git/branch-info":Wl,"/api/git/checkout":Kl,"/api/share/publish/owners":Jl,"/api/share/publish/name-check":Yl,"/api/share/publish":Xl,"/api/principal":Ha,"/api/rescue":eo,"/api/workspace":Ya,"/api/sync/status":_s,"/api/sync/trigger":ys,"/api/sync/conflicts":bs,"/api/sync/conflict-content":Ts,"/api/sync/resolve-conflict":xs,"/api/local-op/clone":yo,"/api/local-op/ok-init":Co,"/api/local-op/auth/login":Vo,"/api/local-op/auth/status":Xo,"/api/local-op/auth/pat":$o,"/api/local-op/auth/gh-login":Go,"/api/local-op/auth/cancel":qo,"/api/local-op/auth/repos":ts,"/api/local-op/auth/signout":ss,"/api/local-op/auth/set-identity":hs,"/api/local-op/embeddings/set-key":lu,"/api/local-op/embeddings/clear-key":pu,"/api/local-op/embeddings/test":_u,"/api/installed-agents":Ps,"/api/spawn-cursor":Bl,"/api/handoff":Rl,"/api/install-skill":js,"/api/skill/install-state":Ll,"/api/seed/plan":Ds,"/api/seed/apply":Os,"/api/seed/packs":ks,"/api/client-logs":Ql};pe&&(Zu[`/api/test-reset`]=va,Zu[`/api/test-flush-git`]=_a,Zu[`/api/test-rescan-backlinks`]=xa,Zu[`/api/test-rescan-files`]=Ca);let Qu=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),$u=[`/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};Ose({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`:Zu[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?Oae(e):void 0;if(c!==void 0&&(kae(e,c),typeof t.setHeader==`function`&&t.setHeader(AC,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,X.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&&!Tj(r,n)){K(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, ${AC}, ${xr.protocol}, ${xr.runtime}, ${xr.kind}`),t.setHeader(`Access-Control-Expose-Headers`,AC)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Qu.has(r)||$u.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!mj(n)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Pt&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!mj(n)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=Bo.extract(Ho.active(),e.headers),u=Yee(),d=Date.now();await Ho.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:Jee.SERVER,attributes:{[Es]:o,[Cs]:s,[ws]:r,[Ss]:`http`,[Xee]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=Zu[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 Da(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await Is(e,t,n))}a||K(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(As,s),s>=500&&n.setStatus({code:zo.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:zo.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&K(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;eX().record(e,{[Es]:o,[Cs]:s,[As]:t.statusCode})}}))}}}function AZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function jZ(e){let t;try{t=au(e.contentDir,{withFileTypes:!0})}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&bC(n.name,Qa)&&e.basenameIndex.add(n.name)}async function MZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Tu(i,{withFileTypes:!0})}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=Ej(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Cu(a)}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Eu(a)}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Dj(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Du(i)}catch(t){let n=AZ(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()&&bC(a,Ba)&&!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()&&bC(a,Ba)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const NZ=A({principalId:j().optional(),tabSessionId:j().optional(),expectedServerInstanceId:j().optional(),expectedBranch:j().optional(),expectedDocLineageEpoch:j().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:j().optional(),clientKind:j().optional()}).loose(),PZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function FZ(e){return PZ.includes(e)}function IZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function LZ(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!FZ(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 RZ=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=IZ(e,this.payload)}};function zZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=NZ.safeParse(t);return n.success?n.data:void 0}var BZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const VZ=F(`conflict-storage`);var HZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(iN(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!V(this.storePath)){this.conflicts=[];return}try{let e=H(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){VZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){VZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);V(e)||eu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return fu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return VZ.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-c0ljFZis.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(!Dj(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);lV(r,t),vs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),VZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await gS(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){VZ.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}),VZ.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(!Dj(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(lV(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-c0ljFZis.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);lV(a,i),vs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);vs(a,n,`utf-8`);break;case`delete`:V(a)&&is(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function UZ(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 WZ(e,t){let n=iN(e);try{eu(n,{recursive:!0}),fu(L(n,pn),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Ds(e);eu(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`};fu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const GZ=new Map;let KZ=!1;function qZ(e,t){try{let n=UZ(e,t);for(let e of GZ.keys())WZ(e,n)}catch{}}function JZ(e){GZ.set(e,(GZ.get(e)??0)+1),KZ||(KZ=!0,process.on(`uncaughtExceptionMonitor`,qZ));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=GZ.get(e)??0;n<=1?GZ.delete(e):GZ.set(e,n-1)}}}function YZ(e){let t=e.scheduler??Gi,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 XZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ZZ(e){if(!V(e))return{};let t;try{t=(0,rj.parse)(H(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(!XZ(t))return{};let n=t.telemetry;if(!XZ(n))return{};let r=n.localSink;return XZ(r)?r:{}}function QZ(e){return typeof e==`boolean`?e:void 0}function $Z(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function eQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function tQ(e){if(XZ(e))return $Z(e.maxBytes)}function nQ(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=ZZ(Xo(`project`,e.projectDir)),n=ZZ(Xo(`project-local`,e.projectDir));if((QZ(n.enabled)??QZ(t.enabled)??!0)===!1)return null;let r=tQ(n.spans)??tQ(t.spans)??52428800,i=tQ(n.logs)??tQ(t.logs)??26214400,a=eQ(n.attributeDenylist)??eQ(t.attributeDenylist)??ro;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var rQ;(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})(rQ||={});var iQ;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(iQ||={});const aQ=rQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),oQ=e=>{switch(typeof e){case`undefined`:return aQ.undefined;case`string`:return aQ.string;case`number`:return Number.isNaN(e)?aQ.nan:aQ.number;case`boolean`:return aQ.boolean;case`function`:return aQ.function;case`bigint`:return aQ.bigint;case`symbol`:return aQ.symbol;case`object`:return Array.isArray(e)?aQ.array:e===null?aQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?aQ.promise:typeof Map<`u`&&e instanceof Map?aQ.map:typeof Set<`u`&&e instanceof Set?aQ.set:typeof Date<`u`&&e instanceof Date?aQ.date:aQ.object;default:return aQ.unknown}},Z=rQ.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 sQ=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,rQ.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()}};sQ.create=e=>new sQ(e);const cQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===aQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,rQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${rQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${rQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${rQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:rQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,rQ.assertNever(e)}return{message:n}};let lQ=cQ;function uQ(){return lQ}const dQ=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 fQ(e,t){let n=uQ(),r=dQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===cQ?void 0:cQ].filter(e=>!!e)});e.common.issues.push(r)}var pQ=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 mQ;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 mQ;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 mQ=Object.freeze({status:`aborted`}),hQ=e=>({status:`dirty`,value:e}),gQ=e=>({status:`valid`,value:e}),_Q=e=>e.status===`aborted`,vQ=e=>e.status===`dirty`,yQ=e=>e.status===`valid`,bQ=e=>typeof Promise<`u`&&e instanceof Promise;var xQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(xQ||={});var SQ=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 CQ=(e,t)=>{if(yQ(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 sQ(e.common.issues);return this._error=t,this._error}}};function wQ(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 TQ=class{get description(){return this._def.description}_getType(e){return oQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:oQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new pQ,ctx:{common:e.parent.common,data:e.data,parsedType:oQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(bQ(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:oQ(e)};return CQ(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:oQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yQ(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=>yQ(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:oQ(e)},r=this._parse({data:e,path:n.path,parent:n});return CQ(n,await(bQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new D$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return O$.create(this,this._def)}nullable(){return k$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return c$.create(this)}promise(){return E$.create(this,this._def)}or(e){return d$.create([this,e],this._def)}and(e){return h$.create(this,e,this._def)}transform(e){return new D$({...wQ(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new A$({...wQ(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new N$({typeName:Q.ZodBranded,type:this,...wQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new j$({...wQ(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return P$.create(this,e)}readonly(){return F$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const EQ=/^c[^\s-]{8,}$/i,DQ=/^[0-9a-z]+$/,OQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kQ=/^[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,AQ=/^[a-z0-9_-]{21}$/i,jQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,MQ=/^[-+]?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)?)??$/,NQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let PQ;const FQ=/^(?:(?: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])$/,IQ=/^(?:(?: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])$/,LQ=/^(([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]))$/,RQ=/^(([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])$/,zQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BQ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,VQ=`((\\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])))`,HQ=RegExp(`^${VQ}$`);function UQ(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 WQ(e){return RegExp(`^${UQ(e)}$`)}function GQ(e){let t=`${VQ}T${UQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function KQ(e,t){return!!((t===`v4`||!t)&&FQ.test(e)||(t===`v6`||!t)&&LQ.test(e))}function qQ(e,t){if(!jQ.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 JQ(e,t){return!!((t===`v4`||!t)&&IQ.test(e)||(t===`v6`||!t)&&RQ.test(e))}var YQ=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==aQ.string){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.string,received:t.parsedType}),mQ}let t=new pQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)NQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)PQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),PQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)kQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)AQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)EQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)DQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)OQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),fQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?GQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?HQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?WQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?MQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?KQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?qQ(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?JQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?zQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?BQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):rQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Z.invalid_string,...xQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...xQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...xQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...xQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...xQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...xQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...xQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...xQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...xQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...xQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...xQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...xQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...xQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...xQ.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,...xQ.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,...xQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...xQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...xQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...xQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...xQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...xQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...xQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...xQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...xQ.errToObj(t)})}nonempty(e){return this.min(1,xQ.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}};YQ.create=e=>new YQ({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...wQ(e)});function XQ(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 ZQ=class e extends TQ{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)!==aQ.number){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.number,received:t.parsedType}),mQ}let t,n=new pQ;for(let r of this._def.checks)r.kind===`int`?rQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?XQ(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):rQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:xQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:xQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:xQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:xQ.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`&&rQ.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)}};ZQ.create=e=>new ZQ({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...wQ(e)});var QQ=class e extends TQ{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)!==aQ.bigint)return this._getInvalidInput(e);let t,n=new pQ;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),fQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):rQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.bigint,received:t.parsedType}),mQ}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.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:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.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}};QQ.create=e=>new QQ({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...wQ(e)});var $Q=class extends TQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==aQ.boolean){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.boolean,received:t.parsedType}),mQ}return gQ(e.data)}};$Q.create=e=>new $Q({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...wQ(e)});var e$=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==aQ.date){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.date,received:t.parsedType}),mQ}if(Number.isNaN(e.data.getTime()))return fQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),mQ;let t=new pQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):rQ.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:xQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:xQ.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)}};e$.create=e=>new e$({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...wQ(e)});var t$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.symbol){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.symbol,received:t.parsedType}),mQ}return gQ(e.data)}};t$.create=e=>new t$({typeName:Q.ZodSymbol,...wQ(e)});var n$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.undefined,received:t.parsedType}),mQ}return gQ(e.data)}};n$.create=e=>new n$({typeName:Q.ZodUndefined,...wQ(e)});var r$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.null){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.null,received:t.parsedType}),mQ}return gQ(e.data)}};r$.create=e=>new r$({typeName:Q.ZodNull,...wQ(e)});var i$=class extends TQ{constructor(){super(...arguments),this._any=!0}_parse(e){return gQ(e.data)}};i$.create=e=>new i$({typeName:Q.ZodAny,...wQ(e)});var a$=class extends TQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gQ(e.data)}};a$.create=e=>new a$({typeName:Q.ZodUnknown,...wQ(e)});var o$=class extends TQ{_parse(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.never,received:t.parsedType}),mQ}};o$.create=e=>new o$({typeName:Q.ZodNever,...wQ(e)});var s$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.void,received:t.parsedType}),mQ}return gQ(e.data)}};s$.create=e=>new s$({typeName:Q.ZodVoid,...wQ(e)});var c$=class e extends TQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==aQ.array)return fQ(t,{code:Z.invalid_type,expected:aQ.array,received:t.parsedType}),mQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(fQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(fQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(fQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new SQ(t,e,t.path,n)))).then(e=>pQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new SQ(t,e,t.path,n)));return pQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:xQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:xQ.toString(n)}})}nonempty(e){return this.min(1,e)}};c$.create=(e,t)=>new c$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...wQ(t)});function l$(e){if(e instanceof u$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=O$.create(l$(r))}return new u$({...e._def,shape:()=>t})}else if(e instanceof c$)return new c$({...e._def,type:l$(e.element)});else if(e instanceof O$)return O$.create(l$(e.unwrap()));else if(e instanceof k$)return k$.create(l$(e.unwrap()));else if(e instanceof g$)return g$.create(e.items.map(e=>l$(e)));else return e}var u$=class e extends TQ{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=rQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==aQ.object){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.object,received:t.parsedType}),mQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof o$&&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 SQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof o$){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&&(fQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new SQ(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=>pQ.mergeObjectSync(t,e)):pQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return xQ.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:xQ.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of rQ.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 rQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return l$(this)}partial(t){let n={};for(let e of rQ.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 rQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof O$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return C$(rQ.objectKeys(this.shape))}};u$.create=(e,t)=>new u$({shape:()=>e,unknownKeys:`strip`,catchall:o$.create(),typeName:Q.ZodObject,...wQ(t)}),u$.strictCreate=(e,t)=>new u$({shape:()=>e,unknownKeys:`strict`,catchall:o$.create(),typeName:Q.ZodObject,...wQ(t)}),u$.lazycreate=(e,t)=>new u$({shape:e,unknownKeys:`strip`,catchall:o$.create(),typeName:Q.ZodObject,...wQ(t)});var d$=class extends TQ{_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 sQ(e.ctx.common.issues));return fQ(t,{code:Z.invalid_union,unionErrors:n}),mQ}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 sQ(e));return fQ(t,{code:Z.invalid_union,unionErrors:i}),mQ}}get options(){return this._def.options}};d$.create=(e,t)=>new d$({options:e,typeName:Q.ZodUnion,...wQ(t)});const f$=e=>e instanceof x$?f$(e.schema):e instanceof D$?f$(e.innerType()):e instanceof S$?[e.value]:e instanceof w$?e.options:e instanceof T$?rQ.objectValues(e.enum):e instanceof A$?f$(e._def.innerType):e instanceof n$?[void 0]:e instanceof r$?[null]:e instanceof O$?[void 0,...f$(e.unwrap())]:e instanceof k$?[null,...f$(e.unwrap())]:e instanceof N$||e instanceof F$?f$(e.unwrap()):e instanceof j$?f$(e._def.innerType):[];var p$=class e extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==aQ.object)return fQ(t,{code:Z.invalid_type,expected:aQ.object,received:t.parsedType}),mQ;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}):(fQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),mQ)}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=f$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...wQ(r)})}};function m$(e,t){let n=oQ(e),r=oQ(t);if(e===t)return{valid:!0,data:e};if(n===aQ.object&&r===aQ.object){let n=rQ.objectKeys(t),r=rQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=m$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===aQ.array&&r===aQ.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=m$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===aQ.date&&r===aQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var h$=class extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(_Q(e)||_Q(r))return mQ;let i=m$(e.value,r.value);return i.valid?((vQ(e)||vQ(r))&&t.dirty(),{status:t.value,value:i.data}):(fQ(n,{code:Z.invalid_intersection_types}),mQ)};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}))}};h$.create=(e,t,n)=>new h$({left:e,right:t,typeName:Q.ZodIntersection,...wQ(n)});var g$=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==aQ.array)return fQ(n,{code:Z.invalid_type,expected:aQ.array,received:n.parsedType}),mQ;if(n.data.length<this._def.items.length)return fQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),mQ;!this._def.rest&&n.data.length>this._def.items.length&&(fQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new SQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>pQ.mergeArray(t,e)):pQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};g$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new g$({items:e,typeName:Q.ZodTuple,rest:null,...wQ(t)})};var _$=class e extends TQ{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!==aQ.object)return fQ(n,{code:Z.invalid_type,expected:aQ.object,received:n.parsedType}),mQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new SQ(n,e,n.path,e)),value:a._parse(new SQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?pQ.mergeObjectAsync(t,r):pQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof TQ?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...wQ(r)}):new e({keyType:YQ.create(),valueType:t,typeName:Q.ZodRecord,...wQ(n)})}},v$=class extends TQ{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!==aQ.map)return fQ(n,{code:Z.invalid_type,expected:aQ.map,received:n.parsedType}),mQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new SQ(n,e,n.path,[a,`key`])),value:i._parse(new SQ(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 mQ;(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 mQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};v$.create=(e,t,n)=>new v$({valueType:t,keyType:e,typeName:Q.ZodMap,...wQ(n)});var y$=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==aQ.set)return fQ(n,{code:Z.invalid_type,expected:aQ.set,received:n.parsedType}),mQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(fQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(fQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return mQ;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 SQ(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:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:xQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y$.create=(e,t)=>new y$({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...wQ(t)});var b$=class e extends TQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==aQ.function)return fQ(t,{code:Z.invalid_type,expected:aQ.function,received:t.parsedType}),mQ;function n(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),cQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),cQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof E$){let e=this;return gQ(async function(...t){let o=new sQ([]),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 gQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new sQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new sQ([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:g$.create(t).rest(a$.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||g$.create([]).rest(a$.create()),returns:n||a$.create(),typeName:Q.ZodFunction,...wQ(r)})}},x$=class extends TQ{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})}};x$.create=(e,t)=>new x$({getter:e,typeName:Q.ZodLazy,...wQ(t)});var S$=class extends TQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return fQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),mQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};S$.create=(e,t)=>new S$({value:e,typeName:Q.ZodLiteral,...wQ(t)});function C$(e,t){return new w$({values:e,typeName:Q.ZodEnum,...wQ(t)})}var w$=class e extends TQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{expected:rQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),mQ}return gQ(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})}};w$.create=C$;var T$=class extends TQ{_parse(e){let t=rQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==aQ.string&&n.parsedType!==aQ.number){let e=rQ.objectValues(t);return fQ(n,{expected:rQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(rQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=rQ.objectValues(t);return fQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),mQ}return gQ(e.data)}get enum(){return this._def.values}};T$.create=(e,t)=>new T$({values:e,typeName:Q.ZodNativeEnum,...wQ(t)});var E$=class extends TQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==aQ.promise&&t.common.async===!1?(fQ(t,{code:Z.invalid_type,expected:aQ.promise,received:t.parsedType}),mQ):gQ((t.parsedType===aQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};E$.create=(e,t)=>new E$({type:e,typeName:Q.ZodPromise,...wQ(t)});var D$=class extends TQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{fQ(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 mQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(r.value):r});{if(t.value===`aborted`)return mQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(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`?mQ:(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`?mQ:(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(!yQ(e))return mQ;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=>yQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):mQ);rQ.assertNever(r)}};D$.create=(e,t,n)=>new D$({schema:e,typeName:Q.ZodEffects,effect:t,...wQ(n)}),D$.createWithPreprocess=(e,t,n)=>new D$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...wQ(n)});var O$=class extends TQ{_parse(e){return this._getType(e)===aQ.undefined?gQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};O$.create=(e,t)=>new O$({innerType:e,typeName:Q.ZodOptional,...wQ(t)});var k$=class extends TQ{_parse(e){return this._getType(e)===aQ.null?gQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k$.create=(e,t)=>new k$({innerType:e,typeName:Q.ZodNullable,...wQ(t)});var A$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===aQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};A$.create=(e,t)=>new A$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...wQ(t)});var j$=class extends TQ{_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 bQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new sQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new sQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};j$.create=(e,t)=>new j$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...wQ(t)});var M$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.nan){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.nan,received:t.parsedType}),mQ}return{status:`valid`,value:e.data}}};M$.create=e=>new M$({typeName:Q.ZodNaN,...wQ(e)});var N$=class extends TQ{_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}},P$=class e extends TQ{_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`?mQ:e.status===`dirty`?(t.dirty(),hQ(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`?mQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},F$=class extends TQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(yQ(e)&&(e.value=Object.freeze(e.value)),e);return bQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};F$.create=(e,t)=>new F$({innerType:e,typeName:Q.ZodReadonly,...wQ(t)}),u$.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),YQ.create,ZQ.create,M$.create,QQ.create,$Q.create,e$.create,t$.create,n$.create,r$.create,i$.create,a$.create,o$.create,s$.create,c$.create;const I$=u$.create;u$.strictCreate,d$.create,p$.create,h$.create,g$.create,_$.create,v$.create,y$.create,b$.create,x$.create,S$.create,w$.create,T$.create,E$.create,D$.create,O$.create,k$.create,D$.createWithPreprocess,P$.create;const L$=to(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);io.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Wa(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>eo(e,t,n),e.parseAsync=async(t,n)=>Ha(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>bo(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)=>yo(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),R$=to(`ZodMiniObject`,(e,t)=>{Fo.init(e,t),L$.init(e,t),Za(e,`shape`,()=>t.shape)});function z$(e,t){return new R$({type:`object`,shape:e??{},...$a(t)})}function B$(e){return!!e._zod}function V$(e){let t=Object.values(e);if(t.length===0)return z$({});let n=t.every(B$),r=t.every(e=>!B$(e));if(n)return z$(e);if(r)return I$(e);throw Error(`Mixed Zod versions detected in object shape.`)}function H$(e,t){return B$(e)?eo(e,t):e.safeParse(t)}async function U$(e,t){return B$(e)?await bo(e,t):await e.safeParseAsync(t)}function W$(e){if(!e)return;let t;if(t=B$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function G$(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 V$(e)}}if(B$(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 K$(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 q$(e){return e.description}function J$(e){if(B$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Y$(e){if(B$(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 X$=`2025-11-25`,Z$=[X$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Q$=`io.modelcontextprotocol/related-task`,$$=ko(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),e1=ho([j(),P().int()]),t1=j();So({ttl:P().optional(),pollInterval:P().optional()});const n1=A({ttl:P().optional()}),r1=A({taskId:j()}),i1=So({progressToken:e1.optional(),[Q$]:r1.optional()}),a1=A({_meta:i1.optional()}),o1=a1.extend({task:n1.optional()}),s1=e=>o1.safeParse(e).success,c1=A({method:j(),params:a1.loose().optional()}),l1=A({_meta:i1.optional()}),u1=A({method:j(),params:l1.loose().optional()}),d1=So({_meta:i1.optional()}),f1=ho([j(),P().int()]),p1=A({jsonrpc:k(`2.0`),id:f1,...c1.shape}).strict(),m1=e=>p1.safeParse(e).success,h1=A({jsonrpc:k(`2.0`),...u1.shape}).strict(),Gle=e=>h1.safeParse(e).success,g1=A({jsonrpc:k(`2.0`),id:f1,result:d1}).strict(),_1=e=>g1.safeParse(e).success;var v1;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(v1||={});const y1=A({jsonrpc:k(`2.0`),id:f1.optional(),error:A({code:P().int(),message:j(),data:O().optional()})}).strict(),b1=e=>y1.safeParse(e).success,x1=ho([p1,h1,g1,y1]);ho([g1,y1]);const S1=d1.strict(),Kle=l1.extend({requestId:f1.optional(),reason:j().optional()}),C1=u1.extend({method:k(`notifications/cancelled`),params:Kle}),w1=A({icons:N(A({src:j(),mimeType:j().optional(),sizes:N(j()).optional(),theme:no([`light`,`dark`]).optional()})).optional()}),T1=A({name:j(),title:j().optional()}),E1=T1.extend({...T1.shape,...w1.shape,version:j(),websiteUrl:j().optional(),description:j().optional()}),qle=Do(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Eo(A({form:Eo(A({applyDefaults:To().optional()}),M(j(),O())).optional(),url:$$.optional()}),M(j(),O()).optional())),Jle=So({list:$$.optional(),cancel:$$.optional(),requests:So({sampling:So({createMessage:$$.optional()}).optional(),elicitation:So({create:$$.optional()}).optional()}).optional()}),Yle=So({list:$$.optional(),cancel:$$.optional(),requests:So({tools:So({call:$$.optional()}).optional()}).optional()}),Xle=A({experimental:M(j(),$$).optional(),sampling:A({context:$$.optional(),tools:$$.optional()}).optional(),elicitation:qle.optional(),roots:A({listChanged:To().optional()}).optional(),tasks:Jle.optional(),extensions:M(j(),$$).optional()}),Zle=a1.extend({protocolVersion:j(),capabilities:Xle,clientInfo:E1}),D1=c1.extend({method:k(`initialize`),params:Zle}),O1=e=>D1.safeParse(e).success,Qle=A({experimental:M(j(),$$).optional(),logging:$$.optional(),completions:$$.optional(),prompts:A({listChanged:To().optional()}).optional(),resources:A({subscribe:To().optional(),listChanged:To().optional()}).optional(),tools:A({listChanged:To().optional()}).optional(),tasks:Yle.optional(),extensions:M(j(),$$).optional()}),$le=d1.extend({protocolVersion:j(),capabilities:Qle,serverInfo:E1,instructions:j().optional()}),k1=u1.extend({method:k(`notifications/initialized`),params:l1.optional()}),eue=e=>k1.safeParse(e).success,A1=c1.extend({method:k(`ping`),params:a1.optional()}),tue=A({progress:P(),total:po(P()),message:po(j())}),nue=A({...l1.shape,...tue.shape,progressToken:e1}),j1=u1.extend({method:k(`notifications/progress`),params:nue}),rue=a1.extend({cursor:t1.optional()}),M1=c1.extend({params:rue.optional()}),N1=d1.extend({nextCursor:t1.optional()}),iue=no([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P1=A({taskId:j(),status:iue,ttl:ho([P(),Ra()]),createdAt:j(),lastUpdatedAt:j(),pollInterval:po(P()),statusMessage:po(j())}),F1=d1.extend({task:P1}),aue=l1.merge(P1),I1=u1.extend({method:k(`notifications/tasks/status`),params:aue}),L1=c1.extend({method:k(`tasks/get`),params:a1.extend({taskId:j()})}),R1=d1.merge(P1),z1=c1.extend({method:k(`tasks/result`),params:a1.extend({taskId:j()})});d1.loose();const B1=M1.extend({method:k(`tasks/list`)}),V1=N1.extend({tasks:N(P1)}),H1=c1.extend({method:k(`tasks/cancel`),params:a1.extend({taskId:j()})}),oue=d1.merge(P1),U1=A({uri:j(),mimeType:po(j()),_meta:M(j(),O()).optional()}),W1=U1.extend({text:j()}),G1=j().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),K1=U1.extend({blob:G1}),q1=no([`user`,`assistant`]),J1=A({audience:N(q1).optional(),priority:P().min(0).max(1).optional(),lastModified:fo({offset:!0}).optional()}),Y1=A({...T1.shape,...w1.shape,uri:j(),description:po(j()),mimeType:po(j()),size:po(P()),annotations:J1.optional(),_meta:po(So({}))}),sue=A({...T1.shape,...w1.shape,uriTemplate:j(),description:po(j()),mimeType:po(j()),annotations:J1.optional(),_meta:po(So({}))}),X1=M1.extend({method:k(`resources/list`)}),cue=N1.extend({resources:N(Y1)}),Z1=M1.extend({method:k(`resources/templates/list`)}),lue=N1.extend({resourceTemplates:N(sue)}),Q1=a1.extend({uri:j()}),uue=Q1,$1=c1.extend({method:k(`resources/read`),params:uue}),due=d1.extend({contents:N(ho([W1,K1]))}),fue=u1.extend({method:k(`notifications/resources/list_changed`),params:l1.optional()}),pue=Q1,mue=c1.extend({method:k(`resources/subscribe`),params:pue}),hue=Q1,gue=c1.extend({method:k(`resources/unsubscribe`),params:hue}),_ue=l1.extend({uri:j()}),vue=u1.extend({method:k(`notifications/resources/updated`),params:_ue}),yue=A({name:j(),description:po(j()),required:po(To())}),bue=A({...T1.shape,...w1.shape,description:po(j()),arguments:po(N(yue)),_meta:po(So({}))}),e0=M1.extend({method:k(`prompts/list`)}),t0=N1.extend({prompts:N(bue)}),xue=a1.extend({name:j(),arguments:M(j(),j()).optional()}),n0=c1.extend({method:k(`prompts/get`),params:xue}),r0=A({type:k(`text`),text:j(),annotations:J1.optional(),_meta:M(j(),O()).optional()}),i0=A({type:k(`image`),data:G1,mimeType:j(),annotations:J1.optional(),_meta:M(j(),O()).optional()}),a0=A({type:k(`audio`),data:G1,mimeType:j(),annotations:J1.optional(),_meta:M(j(),O()).optional()}),Sue=A({type:k(`tool_use`),name:j(),id:j(),input:M(j(),O()),_meta:M(j(),O()).optional()}),Cue=A({type:k(`resource`),resource:ho([W1,K1]),annotations:J1.optional(),_meta:M(j(),O()).optional()}),o0=ho([r0,i0,a0,Y1.extend({type:k(`resource_link`)}),Cue]),wue=A({role:q1,content:o0}),Tue=d1.extend({description:j().optional(),messages:N(wue)}),Eue=u1.extend({method:k(`notifications/prompts/list_changed`),params:l1.optional()}),Due=A({title:j().optional(),readOnlyHint:To().optional(),destructiveHint:To().optional(),idempotentHint:To().optional(),openWorldHint:To().optional()}),Oue=A({taskSupport:no([`required`,`optional`,`forbidden`]).optional()}),s0=A({...T1.shape,...w1.shape,description:j().optional(),inputSchema:A({type:k(`object`),properties:M(j(),$$).optional(),required:N(j()).optional()}).catchall(O()),outputSchema:A({type:k(`object`),properties:M(j(),$$).optional(),required:N(j()).optional()}).catchall(O()).optional(),annotations:Due.optional(),execution:Oue.optional(),_meta:M(j(),O()).optional()}),c0=M1.extend({method:k(`tools/list`)}),kue=N1.extend({tools:N(s0)}),l0=d1.extend({content:N(o0).default([]),structuredContent:M(j(),O()).optional(),isError:To().optional()});l0.or(d1.extend({toolResult:O()}));const Aue=o1.extend({name:j(),arguments:M(j(),O()).optional()}),u0=c1.extend({method:k(`tools/call`),params:Aue}),jue=u1.extend({method:k(`notifications/tools/list_changed`),params:l1.optional()});A({autoRefresh:To().default(!0),debounceMs:P().int().nonnegative().default(300)});const d0=no([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Mue=a1.extend({level:d0}),f0=c1.extend({method:k(`logging/setLevel`),params:Mue}),Nue=l1.extend({level:d0,logger:j().optional(),data:O()}),Pue=u1.extend({method:k(`notifications/message`),params:Nue}),Fue=A({hints:N(A({name:j().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),Iue=A({mode:no([`auto`,`required`,`none`]).optional()}),Lue=A({type:k(`tool_result`),toolUseId:j().describe(`The unique identifier for the corresponding tool call.`),content:N(o0).default([]),structuredContent:A({}).loose().optional(),isError:To().optional(),_meta:M(j(),O()).optional()}),Rue=vo(`type`,[r0,i0,a0]),p0=vo(`type`,[r0,i0,a0,Sue,Lue]),zue=A({role:q1,content:ho([p0,N(p0)]),_meta:M(j(),O()).optional()}),Bue=o1.extend({messages:N(zue),modelPreferences:Fue.optional(),systemPrompt:j().optional(),includeContext:no([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(j()).optional(),metadata:$$.optional(),tools:N(s0).optional(),toolChoice:Iue.optional()}),Vue=c1.extend({method:k(`sampling/createMessage`),params:Bue}),m0=d1.extend({model:j(),stopReason:po(no([`endTurn`,`stopSequence`,`maxTokens`]).or(j())),role:q1,content:Rue}),h0=d1.extend({model:j(),stopReason:po(no([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(j())),role:q1,content:ho([p0,N(p0)])}),Hue=A({type:k(`boolean`),title:j().optional(),description:j().optional(),default:To().optional()}),Uue=A({type:k(`string`),title:j().optional(),description:j().optional(),minLength:P().optional(),maxLength:P().optional(),format:no([`email`,`uri`,`date`,`date-time`]).optional(),default:j().optional()}),Wue=A({type:no([`number`,`integer`]),title:j().optional(),description:j().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),Gue=A({type:k(`string`),title:j().optional(),description:j().optional(),enum:N(j()),default:j().optional()}),Kue=A({type:k(`string`),title:j().optional(),description:j().optional(),oneOf:N(A({const:j(),title:j()})),default:j().optional()}),que=ho([ho([A({type:k(`string`),title:j().optional(),description:j().optional(),enum:N(j()),enumNames:N(j()).optional(),default:j().optional()}),ho([Gue,Kue]),ho([A({type:k(`array`),title:j().optional(),description:j().optional(),minItems:P().optional(),maxItems:P().optional(),items:A({type:k(`string`),enum:N(j())}),default:N(j()).optional()}),A({type:k(`array`),title:j().optional(),description:j().optional(),minItems:P().optional(),maxItems:P().optional(),items:A({anyOf:N(A({const:j(),title:j()}))}),default:N(j()).optional()})])]),Hue,Uue,Wue]),Jue=ho([o1.extend({mode:k(`form`).optional(),message:j(),requestedSchema:A({type:k(`object`),properties:M(j(),que),required:N(j()).optional()})}),o1.extend({mode:k(`url`),message:j(),elicitationId:j(),url:j().url()})]),Yue=c1.extend({method:k(`elicitation/create`),params:Jue}),Xue=l1.extend({elicitationId:j()}),Zue=u1.extend({method:k(`notifications/elicitation/complete`),params:Xue}),g0=d1.extend({action:no([`accept`,`decline`,`cancel`]),content:Do(e=>e===null?void 0:e,M(j(),ho([j(),P(),To(),N(j())])).optional())}),Que=A({type:k(`ref/resource`),uri:j()}),$ue=A({type:k(`ref/prompt`),name:j()}),ede=a1.extend({ref:ho([$ue,Que]),argument:A({name:j(),value:j()}),context:A({arguments:M(j(),j()).optional()}).optional()}),_0=c1.extend({method:k(`completion/complete`),params:ede});function tde(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function nde(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const rde=d1.extend({completion:So({values:N(j()).max(100),total:po(P().int()),hasMore:po(To())})}),ide=A({uri:j().startsWith(`file://`),name:j().optional(),_meta:M(j(),O()).optional()}),ade=c1.extend({method:k(`roots/list`),params:a1.optional()}),v0=d1.extend({roots:N(ide)}),ode=u1.extend({method:k(`notifications/roots/list_changed`),params:l1.optional()});ho([A1,D1,_0,f0,n0,e0,X1,Z1,$1,mue,gue,u0,c0,L1,z1,B1,H1]),ho([C1,j1,k1,ode,I1]),ho([S1,m0,h0,g0,v0,R1,V1,F1]),ho([A1,Vue,Yue,ade,L1,z1,B1,H1]),ho([C1,j1,Pue,vue,fue,jue,Eue,I1,Zue]),ho([S1,$le,rde,Tue,t0,cue,lue,due,l0,kue,R1,V1,F1]);var y0=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===v1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new sde(e.elicitations,n)}return new e(t,n,r)}},sde=class extends y0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(v1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function b0(e){return e===`completed`||e===`failed`||e===`cancelled`}const cde=Symbol(`Let zodToJsonSchema decide on which parser to use`),x0={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`},lde=e=>typeof e==`string`?{...x0,name:e}:{...x0,...e},ude=e=>{let t=lde(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 S0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function C0(e,t,n,r,i){e[t]=n,S0(e,t,r,i)}const w0=(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 T0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?w0(t,e.currentPath):t.join(`/`)}}function dde(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=R0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&C0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&C0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(C0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),C0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function fde(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?C0(n,`minimum`,r.value,r.message,t):C0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),C0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?C0(n,`maximum`,r.value,r.message,t):C0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),C0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:C0(n,`multipleOf`,r.value,r.message,t);break}return n}function pde(){return{type:`boolean`}}function E0(e,t){return R0(e.type._def,t)}const mde=(e,t)=>R0(e.innerType._def,t);function D0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>D0(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 hde(e,t)}}const hde=(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`:C0(n,`minimum`,r.value,r.message,t);break;case`max`:C0(n,`maximum`,r.value,r.message,t);break}return n};function gde(e,t){return{...R0(e.innerType._def,t),default:e.defaultValue()}}function _de(e,t){return t.effectStrategy===`input`?R0(e.schema._def,t):T0(t)}function vde(e){return{type:`string`,enum:Array.from(e.values)}}const yde=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function bde(e,t){let n=[R0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),R0(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(yde(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 xde(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 O0;const k0={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:()=>(O0===void 0&&(O0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),O0),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 A0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:C0(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`:M0(n,`email`,r.message,t);break;case`format:idn-email`:M0(n,`idn-email`,r.message,t);break;case`pattern:zod`:N0(n,k0.email,r.message,t);break}break;case`url`:M0(n,`uri`,r.message,t);break;case`uuid`:M0(n,`uuid`,r.message,t);break;case`regex`:N0(n,r.regex,r.message,t);break;case`cuid`:N0(n,k0.cuid,r.message,t);break;case`cuid2`:N0(n,k0.cuid2,r.message,t);break;case`startsWith`:N0(n,RegExp(`^${j0(r.value,t)}`),r.message,t);break;case`endsWith`:N0(n,RegExp(`${j0(r.value,t)}$`),r.message,t);break;case`datetime`:M0(n,`date-time`,r.message,t);break;case`date`:M0(n,`date`,r.message,t);break;case`time`:M0(n,`time`,r.message,t);break;case`duration`:M0(n,`duration`,r.message,t);break;case`length`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),C0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:N0(n,RegExp(j0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&M0(n,`ipv4`,r.message,t),r.version!==`v4`&&M0(n,`ipv6`,r.message,t);break;case`base64url`:N0(n,k0.base64url,r.message,t);break;case`jwt`:N0(n,k0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&N0(n,k0.ipv4Cidr,r.message,t),r.version!==`v4`&&N0(n,k0.ipv6Cidr,r.message,t);break;case`emoji`:N0(n,k0.emoji(),r.message,t);break;case`ulid`:N0(n,k0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:M0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:C0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:N0(n,k0.base64,r.message,t);break}break;case`nanoid`:N0(n,k0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function j0(e,t){return t.patternStrategy===`escape`?Cde(e):e}const Sde=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Cde(e){let t=``;for(let n=0;n<e.length;n++)Sde.has(e[n])||(t+=`\\`),t+=e[n];return t}function M0(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}}})):C0(e,`format`,t,n,r)}function N0(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:P0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):C0(e,`pattern`,P0(t,r),n,r)}function P0(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
|
|
1215
|
+
`).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await gi(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Zc=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Qc(e){try{let t=wc(e.scope);if(!t)return;let n=fB(t);if(n.length===0)return;let r=yB(z(e.skillsRoot,e.name),e.name,t,n,`copy`,pB(e.scope));if(r.length===0)return;await TI(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function $c(e,t){if(t.ok){J(e,200,Yi,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}async function el(e){let{acquiredDir:t,scope:n,sourceLabel:r,ref:i,publisher:a,upstreamSkill:o,actor:s}=e;if(!D)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`No project root resolved.`,detail:`NO_PROJECT_ROOT`};let c=rO(t);if(c)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:c};let l=iO(t);if(!l)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let u=$Y(l);if(u)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:u};let d=L(n===`project`?D:nc,...XD),f=Jc(d),p=n===`project`?g:nc,m=ZB(p,n),h=z(p,m),_=Soe(f,l.contentHash);if(_&&ic(n,_)!==null)return{ok:!0,body:{name:_,path:`${_}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:r,ref:i,contentHash:l.contentHash,publisher:a},warnings:[]}};let v=DX(l.name),y=e=>ic(n,e)!==null||V(z(h,e,`SKILL.md`)),b=y(v),x=v;if(b){x=`${v}-imported`;let e=2;for(;y(x);)x=`${v}-imported-${e}`,e+=1}let S=qs(l.skillMd).body,C=XP({skillsRoot:h,name:x,body:S,frontmatter:{name:x,description:l.description}});if(!C.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write imported skill.`,detail:C.error.code,cause:Error(C.error.message)};let w=[...C.warnings];for(let e of l.files){let t=$P({skillsRoot:h,name:x,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:QY});if(!t.ok){let n=tF({skillsRoot:h,name:x});return{ok:!1,status:n.ok?400:500,urn:n.ok?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,title:`Failed to write the complete imported skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(n.ok?t.error.message:`${t.error.message}; rollback: ${n.error.message}`)}}}n===`project`&&(di(s,`${m}/${x}/SKILL`,`skill-import: ${r} -> ${m}/${x}/SKILL.md`),await gi(`skill-import`));let T=Yc(h,x),E=EO(r),ee=n===`project`?await Xc(Zc(s),`${m}/${x}`):void 0;if(await QJ(d,e=>$D(e,x,{source:r,...E?{pluginProvider:E.provider}:{},ref:i,contentHash:l.contentHash,files:l.files.map(e=>e.relPath),...T===void 0?{}:{localHash:T},...ee===void 0?{}:{baselineRef:ee},publisher:a,importedAt:new Date().toISOString(),...o===void 0?{}:{skill:o}})),e.skipProjection!==!0)try{let e=fB(p);if(e.length>0){let t=z(h,x),r=pB(n),i=e.filter(e=>{let n=mB(p,e,x,r);return n!==null&&n!==t&&V(n)}),a=i.filter(e=>{let t=mB(p,e,x,r);try{return t!==null&&$l(t).isSymbolicLink()}catch{return!1}});xB({canonicalAbs:t,canonicalHash:iO(t)?.contentHash??``,canonicalRootRel:m,name:x,cwd:p,targets:e,mode:pc(n,x,{hosts:[`<source>`,...i],linkedHosts:a}),roots:pB(n)})}}catch(e){F(`skill-import`).warn({err:e,skill:x},`post-import editor fan-out failed (import kept)`)}return Me?.(`files`),{ok:!0,body:{name:x,path:`${m}/${x}/SKILL.md`,created:C.created,alreadyImported:!1,...b?{collisionRenamedFrom:l.name}:{},provenance:{source:r,ref:i,contentHash:l.contentHash,publisher:a},warnings:w}}}let tl=q(Br,async(e,t,n)=>{let r=()=>{};try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l;{let e=n.source;try{let i=await lO(e,n.skill),u=i?.source??e,d=n.skill??i?.skill,f=i?.spec??qD(u);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(ZY(t,f,`skill-import`))return;let p=await YD(f);r=p.cleanup,s=p.ref;let m=aO(p.dir);if(m.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let h=m[0];if(d){let e=m.find(e=>e.name===d)??m.find(e=>nO(e.dir)?.name===d);if(!e){K(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${d}" not among: ${m.map(e=>e.name).join(`, `)}.`});return}h=e}else if(m.length>1){K(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:m.map(e=>e.name).join(`, `)});return}a=h.dir,l=h.name,o=e,c=i?.publisher??qc(u)}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}$c(t,await el({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),nl=q(bt,async(e,t,n)=>{let r=()=>{};try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l;try{let e=await lO(i,n.skills[0]),u=e?.source??i,d=e?.spec??qD(u);if(!d){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(ZY(t,d,`skills-import-bulk`))return;if(l=e?.publisher??qc(u),d.kind===`well-known`)a=d,o=await GD(d.origin);else{let e=await YD(d);r=e.cleanup,c=e.ref,s=aO(e.dir)}}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let u=[];for(let t of new Set(n.skills)){let r,d,f=()=>{};if(a!==null)try{let e=await YD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,d=t}catch(e){u.push({requested:t,status:e instanceof zD?`not-found`:`failed`,warnings:[],...e instanceof zD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>iO(e.dir)?.name===t);if(!e){u.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,d=e.name}try{let a=await el({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:d,actor:e,skipProjection:n.install===!1});if(!a.ok){F(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}u.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){F(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}J(t,200,kt,{results:u,imported:u.filter(e=>e.status===`imported`).length,alreadyImported:u.filter(e=>e.status===`already-imported`).length,failed:u.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),rl=8*1024*1024,il=32*1024*1024;function al(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=z(e,n);return r!==e&&!r.startsWith(e+B)?null:r}function ol(e){return new Promise((t,n)=>{let r;try{r=(0,HO.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:rl}})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>il){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function sl(e,t){return new Promise((n,r)=>{(0,ij.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=al(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){ls(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>rl){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>il){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{ls(I(n),{recursive:!0}),vs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function cl(e,t){let n=tu(L(yu(),`ok-skill-upload-`)),r=()=>{try{ps(n,{recursive:!0,force:!0})}catch{}};try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=tc(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=pM({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},Ze);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await ol(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await sl(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=al(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}ls(I(r),{recursive:!0}),vs(r,e.data)}let u=aO(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];$c(t,await el({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let ll=q(wee,async(e,t,n)=>{try{let e=rc(n.scope);if(!ec(n.name,t,`skill-install`))return;if(n.scope===`project`&&!D){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=wc(n.scope),i=z(e,n.name),a=n.scope===`project`?g:nc,o=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name),s=o?z(a,o.dir):i;if(!V(s)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Bn(n.scope===`project`?`${R(a,s).split(B).join(`/`)}/SKILL`:Qi(n.scope,n.name));let c=uB(s,n.name);if(!c.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){let e=[];if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let r=n.scope===`project`?be:Ve,i=n.fork.editor===`agents`?`.agents/skills`:r[n.fork.editor]??null;if(i===null){K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:n.fork.editor});return}let s=z(a,i,n.name),c=z(a,o.dir),l=iO(s);if(l===null||s===c){K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return}if(l.contentHash===o.contentHash){K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return}let u=new Date().toISOString().replace(/[:.]/g,`-`),d=(e,t)=>{try{let r=z(nc,`.ok`,`edit-backups`,`forks`,`${n.name}-${t}-${u}`);ls(z(r,`..`),{recursive:!0}),fs(e,r,{recursive:!0})}catch(e){X.warn({name:n.name,err:e},`[skill-fork] stash failed`)}};if(n.fork.action===`align`)d(s,n.fork.editor),ps(s,{recursive:!0,force:!0}),xB({canonicalAbs:c,canonicalHash:o.contentHash,canonicalRootRel:I(o.dir),name:n.name,cwd:a,targets:[n.fork.editor].filter(yn),roots:pB(n.scope)});else if(n.fork.action===`make-source`){let e=o.hosts.filter(yn);d(c,`source`),wB({canonicalAbs:c,canonicalHash:o.contentHash,name:n.name,cwd:a,targets:e,roots:pB(n.scope)}),ps(c,{recursive:!0,force:!0});let t=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name);t&&xB({canonicalAbs:z(a,t.dir),canonicalHash:t.contentHash,canonicalRootRel:I(t.dir),name:n.name,cwd:a,targets:e,roots:pB(n.scope)})}else{let r=n.fork.toName;if(!nt.test(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:r});return}if((n.scope===`project`?nV(g):rV(nc)).some(e=>e.name===r)){K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:r});return}let o=z(a,i,r);ns(s,o);let c=z(o,`SKILL.md`);try{let{fenced:t,body:n}=qn(H(c,`utf-8`)),i=Aa(t,{name:r});i.ok?vs(c,`${i.nextFenced}${n}`):(X.warn({name:r,reason:i.error.kind},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md still declares the old name — edit the frontmatter to match.`))}catch(t){X.warn({name:r,err:t},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md could not be updated — edit the frontmatter to match.`)}}Me?.(`files`),J(t,200,mi,{name:n.name,hosts:o.hosts.filter(yn),scripts:!1,warnings:e,warningCodes:e.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let l=n.setSource??n.source,u=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),d=n.targets,f=[],p=[];if(n.add!==void 0||n.remove!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=e=>e.replace(/\\/g,`/`).replace(/^~\//,``),r=o.hosts[0];if(r!==void 0&&(n.remove??[]).some(t=>e(t)===r)){K(t,400,`urn:ok:error:invalid-request`,`"${r}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`});return}let i=new Set(o.hosts.filter(e=>yn(e)));for(let t of n.add??[])yn(t)?i.add(t):f.push(e(t));let s=GB(a,n.scope),c=[],l=[];for(let e of n.add??[])if(yn(e)&&s[e]!==void 0&&!V(z(a,s[e],n.name,`SKILL.md`))){let t=e===`agents`?`.agents/skills`:(n.scope===`project`?be:Ve)[e]??null;t!==null&&l.push(t)}for(let t of n.remove??[])if(yn(t)){if(!i.has(t)&&s[t]!==void 0&&V(z(a,s[t],n.name,`SKILL.md`))){let e=t===`agents`?`.agents/skills`:(n.scope===`project`?be:Ve)[t]??null;e!==null&&c.push(e)}i.delete(t)}else p.push(e(t));for(let{subRoot:e,exclude:r}of[...l.map(e=>({subRoot:e,exclude:void 0})),...c.map(e=>({subRoot:e,exclude:[n.name]}))]){let n=PJ({base:a,folderRel:e,...r===void 0?{}:{exclude:r}});if(n.ok&&await IJ(a,e,{expect:`own`}),!n.ok){K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e} following its pool (${n.reason}).`,{handler:`skill-install`,detail:n.reason});return}}d=[...i]}if(l&&!o){let e=l,i=SB({canonicalAbs:s,canonicalHash:iO(s)?.contentHash??``,name:n.name,cwd:a,newTarget:e,roots:pB(n.scope)});if(!i.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:i.reason});return}await EI(r,n.name),await FJ(a,n.name,e),Me?.(`files`);let o=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name);J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:R(a,i.newAbs).split(B).join(`/`)},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?D:nc;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.place.dir.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),i=z(e,r),a=`${r}/${n.name}`,l=AB(e,a),u=z(e),d=oc(r);if(r===``||l===null||!l.startsWith(u+B)||d){K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}if(l===z(s)){J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:a},{handler:`skill-install`});return}if(V(l)){K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}ls(i,{recursive:!0}),n.place.mode===`link`?as(R(i,z(s)),l,`dir`):fs(s,l,{recursive:!0,dereference:!0});let f=a;await HJ(e,n.name,{path:f,mode:n.place.mode,...n.place.mode===`copy`?{hash:iO(s)?.contentHash}:{}}),Me?.(`files`),J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:f},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?D:nc;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.unplace.path.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``);if(!BJ(e)[n.name]?.find(e=>e.path===r)){K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r});return}let i=AB(e,r);if(i===null){K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}let a=iO(s)?.contentHash??``;switch(bB(i,z(s),a)){case`different`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r});return;case`absent`:break;default:ps(i,{recursive:!0,force:!0})}await VJ(e,n.name,r),Me?.(`files`),J(t,200,mi,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?D:nc,l=pB(n.scope),u=yn(e)?e===`agents`?`.agents/skills`:l[e]:e.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),d=u===null||u===``?null:AB(a??r,`${u}/${n.name}`);if(u===null||u===``||d===null){K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return}let f=z(s),p=o.contentHash,m=bB(d,f,p);if(m===`canonical-dir`){K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return}if(m===`different`){K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return}if(m===`absent`){K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return}let h=i===`link`&&m===`link-to-canonical`||i===`copy`&&m===`same-copy`;if(h&&await HJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}}),!h){let e=I(d);ps(d,{recursive:!0,force:!0}),ls(e,{recursive:!0}),i===`link`?as(R(e,f),d,`dir`):fs(f,d,{recursive:!0,dereference:!0}),await HJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}})}Me?.(`files`),J(t,200,mi,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let m=n.scope===`global`?d?Rt.filter(e=>d?.some(t=>t===e)):[...Rt]:d===void 0?fB(r):Rt.filter(e=>d?.some(t=>t===e)),h=[],_=[];if(m.length===0&&d===void 0&&(h.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),c.hasScripts&&(h.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),c.warnings.length>0&&(h.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=d?.includes(`agents`)===!0?[...m,`agents`]:[...m],v=n.scope===`project`?D:nc,y=u===void 0?pc(n.scope,n.name,o):u?`link`:`copy`;if(l){let e=o.hosts[0],i=l,u=yn(i),d;if(!u){let e=i.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),a=oc(e),o=z(r,e,n.name);if(e===``||a||!o.startsWith(z(r)+B)){K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:i});return}d=o}let f;if(e!==void 0&&i!==e){let e=R(a,z(s)).split(B).join(`/`),c=SB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:u?i:`agents`,...d===void 0?{}:{destDirAbs:d},leaveLinkBehind:!0,roots:pB(n.scope)});if(!c.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}f=R(a,c.newAbs).split(B).join(`/`),await HJ(v??r,n.name,{path:e,mode:`link`});for(let e of BJ(v??r)[n.name]??[]){let t=z(v??r,e.path);if(t===c.newAbs)continue;try{if(!$l(t).isSymbolicLink())continue}catch{continue}let n=null;try{n=U(t)}catch{n=null}(n===null||n===z(s))&&(ps(t,{recursive:!0,force:!0}),as(R(I(t),c.newAbs),t,`dir`))}await HJ(v??r,n.name,{path:f,mode:`copy`}),await FJ(v??r,n.name,i)}Me?.(`files`);let p=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name);J(t,200,mi,{name:n.name,hosts:p?[...p.hosts]:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[],...f===void 0?{}:{sourceMovedTo:f}},{handler:`skill-install`});return}let b=o.hosts.filter(e=>yn(e)),x=o.hosts[0],S;if(d!==void 0&&x!==void 0&&!x.includes(`/`)&&i.length>0&&!i.includes(x)){let e=i[0],c=SB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:e,roots:pB(n.scope)});if(!c.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}s=c.newAbs,S=R(a,c.newAbs).split(B).join(`/`),await HJ(v??r,n.name,{path:S,mode:`copy`}),await FJ(v??r,n.name,e)}let C=S?S.split(`/`).slice(0,-1).join(`/`):e;wB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,targets:d===void 0?[]:b.filter(e=>!i.includes(e)),roots:pB(n.scope)});let w=xB({canonicalAbs:s,canonicalHash:o.contentHash,canonicalRootRel:C,name:n.name,cwd:r,targets:i,mode:y,convertLinks:u===!1,roots:pB(n.scope)});for(let e of w.conflicted)h.push(`A different skill named "${n.name}" already exists in the ${e} skills folder — left untouched.`),_.push(`name-conflict`);if(u!==void 0&&v&&f.length>0){let e=new Set(f.map(e=>`${e}/${n.name}`));for(let t of(BJ(v)[n.name]??[]).filter(t=>e.has(t.path))){let e=z(v,t.path);if(e===z(s))continue;let r=bB(e,z(s),o.contentHash);u===!0&&r===`same-copy`?(ps(e,{recursive:!0,force:!0}),as(R(I(e),z(s)),e,`dir`),await HJ(v,n.name,{path:t.path,mode:`link`})):u===!1&&r===`link-to-canonical`&&(ps(e,{recursive:!0,force:!0}),fs(z(s),e,{recursive:!0,dereference:!0}),await HJ(v,n.name,{path:t.path,mode:`copy`,hash:o.contentHash}))}}for(let t of w.hosts){let i=t===`agents`?`.agents/skills`:be[t];if(i===null||i===e)continue;let a=z(r,i,n.name),s=!1;try{s=$l(a).isSymbolicLink()}catch{continue}if(s){y===`link`&&await HJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`link`});continue}let c=V(L(a,`SKILL.md`))?iO(a)?.contentHash:void 0;c!==void 0&&c===o.contentHash&&await HJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`copy`,hash:c})}if((f.length>0||p.length>0)&&v){let e=z(s);for(let t of f){let r=oc(t),i=z(v,t),a=AB(v,`${t}/${n.name}`);if(t===``||r||a===null||a===e){h.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=bB(a,e,o.contentHash);if(s===`different`){h.push(`A different "${n.name}" already exists at ${t} — left untouched.`),_.push(`name-conflict`);continue}s===`absent`&&(ls(i,{recursive:!0}),y===`link`?as(R(i,e),a,`dir`):fs(e,a,{recursive:!0,dereference:!0})),await HJ(v,n.name,{path:`${t}/${n.name}`,mode:y,...y===`copy`?{hash:o.contentHash}:{}})}for(let t of p){let r=`${t}/${n.name}`,i=BJ(v)[n.name]?.find(e=>e.path===r),a=AB(v,r);if(a===null){h.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=bB(a,e,o.contentHash);if(s===`different`){h.push(`The copy at ${r} has been hand-edited (a fork) — refused, never deleted. Remove it manually if you mean it.`),_.push(`place-fork-refused`);continue}s!==`absent`&&s!==`canonical-dir`&&ps(a,{recursive:!0,force:!0}),i&&await VJ(v,n.name,r)}}let T=(n.scope===`project`?nV(g):rV(nc)).find(e=>e.name===n.name),E=T?[...T.hosts]:w.hosts;Me?.(`files`),J(t,200,mi,{name:n.name,hosts:E,scripts:c.hasScripts,warnings:h,warningCodes:_,...S===void 0?{}:{sourceMovedTo:S}},{handler:`skill-install`});return}let v=aB(CI(r).skills[n.name]?.hosts??[]).filter(e=>!m.includes(e));v.length>0&&TB(n.name,r,v,pB(n.scope));let y=L(r,...XD),b=V(y)?H(y,`utf-8`):null,x=b===null?null:QD(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=u===void 0?S?`copy`:`symlink`:u?`symlink`:`copy`,w=yB(s,n.name,r,m,C,pB(n.scope));w.length===0?await EI(r,n.name):await TI(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),Me?.(`files`),J(t,200,mi,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:h,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),ul=q(Vee,async(e,t,n)=>{try{if(!ec(n.name,t,`skill-uninstall`))return;let e=wc(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await Tc(e,n.name,n.scope);Me?.(`files`),J(t,200,pt,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),dl=eW({GET:q(jn,async(e,t)=>{try{let e=fB(D??``),n=(e,t)=>{let n=LJ(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,nee,{targets:e,configured:!1,folders:[...D?kJ(g,JB(g,`project`)).map(e=>({...e,scope:`project`,...n(g,e)})):[],...kJ(nc,JB(nc,`global`)).map(e=>({...e,scope:`global`,...n(nc,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Fr,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?g:nc;if(e.scope===`project`&&!D){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await RJ(r,i.join(`/`)),Me?.(`files`),J(t,200,p,{targets:fB(D??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(JB(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?NJ({base:r,folderRel:e.root,targetRootRel:a}):PJ({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await IJ(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),Me?.(`files`),J(t,200,p,{targets:fB(D??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),fl=q(T,async(e,t,n)=>{try{let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!ec(n.name,t,`skill-restore`)||bc(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=ge?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await KJ({shadow:r,contentDir:g,contentRoot:De??`.`,name:n.name,version:n.version,skillDirRel:mc(n.name)});if(!i.ok){fc(t,i,`skill-restore`);return}let a=[],o=uB(z(g,mc(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),di(e,ui(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await gi(`skill-restore`),Me?.(`files`),J(t,200,da,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),pl=q(ya,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!ec(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?nc:g,{root:a,dirRel:o,realDir:s}=jc(n.scope,n.name),c=!o.startsWith(`${gn}/`);if(s===null||!V(z(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let l=L(n.scope===`global`?nc:D,...XD),u=Jc(l).skills[n.name];if(!u){let e=xoe(n.name,iO(z(a,n.name))?.contentHash??``,new Date().toISOString())??vc(i,n.name);e&&(u=e)}if(!u){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await QJ(l,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??u,autoUpdate:n.setAutoUpdate}}})),J(t,200,Ut,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let d,f=null,p=!1;try{let e=await lO(u.source,u.skill??n.name),i=e?.source??Zoe(u.source,u.pluginProvider),a=e?.skill??u.skill,o=e?.spec??qD(i);if(!o){K(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:u.source});return}if(ZY(t,o,`skill-reimport`))return;let s=await YD(o);r=s.cleanup,d=s.ref;let c=aO(s.dir),l=(a?c.find(e=>e.name===a):void 0)??c.find(e=>e.name===n.name)??c.find(e=>iO(e.dir)?.name===n.name)??(c.length===1?c[0]:void 0);if(!l){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:c.map(e=>e.name).join(`, `)});return}let p=rO(l.dir);if(p){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:p});return}f=iO(l.dir)}catch(e){if(e instanceof zD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!f){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let m=$Y(f);if(m){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:m});return}p=f.files.some(e=>e.relPath.startsWith(`scripts/`));let h=iO(z(a,n.name)),_=new Set(f.files.map(e=>e.relPath)),v=new Set((h?.files??[]).map(e=>e.relPath)),y=(u.files??(u.localHash!==void 0&&h?.contentHash===u.localHash?h.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(f.contentHash===u.contentHash&&y.length===0){J(t,200,Ut,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let b=qs(f.skillMd).body;if(n.dryRun){let e=iO(z(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&D)try{let e=Ms({baseDir:D,timeout:{block:15e3}}),t=R(D,z(a,n.name)).split(B).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}J(t,200,Ut,{name:n.name,updated:!0,source:u.source,localBody:qs(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await br(e,`deleted-upstream`)}let x=XP({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:f.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of f.files){let r=$P({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:QY});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=eF({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(di(e,ui(`skill`,``,n.name),`skill-reimport: ${u.source} -> ${o}`),await gi(`skill-reimport`));let C=Yc(a,n.name),w=n.scope===`project`?await Xc(Zc(e),o):void 0;await QJ(l,e=>$D(e,n.name,{...e.skills[n.name]??u,contentHash:f.contentHash,files:f.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:d,importedAt:new Date().toISOString()})),!c&&n.scope===`project`&&await Qc({skillsRoot:a,name:n.name,scope:`project`,hasScripts:p,handler:`skill-reimport`}),Me?.(`files`),J(t,200,Ut,{name:n.name,updated:!0,source:u.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),ml=q(Zt,async(e,t,n)=>{try{if(!D){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=pM(n,Ze);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!ec(n.name,t,`skill-revert`)||bc(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=L(D,...XD),i=Jc(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=ge?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await KJ({shadow:a,contentDir:g,contentRoot:De??`.`,name:n.name,version:i.baselineRef,skillDirRel:mc(n.name)});if(!o.ok){fc(t,o,`skill-revert`);return}di(e,ui(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await gi(`skill-revert`);let s=z(g,mc(n.name),`..`),c=Yc(s,n.name);await QJ(r,e=>$D(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===rc(`project`)&&await Qc({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),Me?.(`files`),J(t,200,fe,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function hl(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])=>h({kind:`folder`,path:e,modifiedTs:t}))}function gl(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 _l(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function vl(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 yl(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function bl(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function xl(e,t,n,r){let i=r.documents.filter(e=>!Oi(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!wt?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};wt.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await wt.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Tt?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=wt.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function Sl(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`?gl(e.document.content,t):void 0}}async function Cl(e){let t=performance.now();if(Ml())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await Nl(),i=await xl(e.query,e.intent,e.semanticParam,n),a=uee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>Sl(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},Hse({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 wl(){let e=[],t=new Set;for(let n of nV(g)){let r=z(g,n.dir,`SKILL.md`);try{let i=uu(r);e.push({name:n.name,absolutePath:r,docPath:`${n.dir}/SKILL`,mtimeMs:i.mtimeMs,size:i.size}),t.add(n.name)}catch{}}let n=rc(`project`);if(!V(n))return e;let r;try{r=au(n,{withFileTypes:!0})}catch{return e}for(let i of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!i.isDirectory()||!nt.test(i.name)||t.has(i.name))continue;let r=z(n,i.name,`SKILL.md`);try{let t=uu(r);e.push({name:i.name,absolutePath:r,docPath:`${gn}/${i.name}/SKILL`,mtimeMs:t.mtimeMs,size:t.size})}catch{}}return e}function Tl(){let e=[];for(let t of wl()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=qs(H(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(h({kind:`page`,path:t.docPath,title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function El(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Dl=new Map;async function Ol(){let e=[],t=[],n=new Set;for(let[r,i]of C()){if(dC(r)||fC(r)||Li(r)?.kind===`skill`||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(h({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=El(i),o=Dl.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await wu(i.canonicalPath,`utf-8`)}catch(e){l=!0,X.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=ER(s,r)}catch(e){X.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=h({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Dl.set(r,{key:a,doc:u}),e.push(u)}for(let e of Dl.keys())n.has(e)||Dl.delete(e);let r=zX(),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`),pX().add(1)),{documents:[...e,...Tl(),...i,...hl([...e,...i])],truncated:a}}function kl(){return wl().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Al(){return E?`gen:${E()}|skills${kl()}`:`${[...C()].filter(([e])=>!dC(e)&&!fC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${El(t)}`).join(``)}|skills${kl()}`}let jl=gt===void 0;gt?.then(()=>{jl=!0},e=>{jl=!0,X.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Ml(){return!jl}async function Nl(){let e=`${g}${D??``}`,t=Al(),n=TZ.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 Ol();if(!e)return hX().add(1,{mode:`cold`}),{corpus:ja(t),truncated:n};let a=Ae(e,t);if(a.rebuilt){hX().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 hX().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}})();TZ.set(e,{fingerprint:t,pending:a});try{let n=await a;return TZ.get(e)?.pending===a&&TZ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw TZ.get(e)?.pending===a&&TZ.delete(e),t}}function Pl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Nl().catch(e=>{X.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}Pl();let Fl=eW({GET:q(jn,$U(async(e,t)=>{let n=Zee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=_l(n.get(`intent`)),o=Sc(n.get(`ranking`)),s=vl(n.get(`scope`)??n.get(`scopes`)),c=yl(n.get(`semantic`)),l=bl(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,Ye,await Cl({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Ci,$U(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=_l(n.intent),a=Sc(n.ranking),o=vl(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=yl(n.semantic),l=bl(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,Ye,await Cl({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`}),Ll=q(jn,$U(async(e,t)=>{J(t,200,jee,{...await Kz(gu())},{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 Rl(e,t){if(r(e,t,{handler:`handoff`}))try{await xce(e,t,{contentDir:g,platform:process.platform,isSchemeRegistered:sn.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:MC(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Bl(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await aI(e,t,{contentDir:g,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:MC(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Ul=q(pee,async(e,t,n)=>{try{if(!D){FR(`no-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`no-remote`},{handler:jR});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!MR(e,n.kind)){FR(`invalid-path`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`invalid-path`},{handler:jR});return}let r=BR(D);if(r===null){if(WR(D).kind===`no-remote`){FR(`no-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`no-remote`},{handler:jR});return}FR(`detached-head`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`detached-head`},{handler:jR});return}let i=WR(D);if(i.kind===`no-remote`){FR(`no-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`no-remote`},{handler:jR});return}if(i.kind===`non-github`){FR(`non-github-remote`,{kind:n.kind}),J(t,200,we,{ok:!1,error:`non-github-remote`},{handler:jR});return}if(!JR(D,r)){FR(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,we,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:jR});return}let a=_Z(D,g);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=NR(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=PR(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Wh(s)}`,l=await LR(D,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);FR(`ok`,{branchExists:!0,kind:n.kind,freshness:l}),J(t,200,we,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:l},{handler:jR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:jR,cause:e})}},{handler:jR,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jR})}),Wl=q(jn,async(e,t)=>{try{if(!D){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:zU});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(!ti(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:zU});return}if(!LU(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:zU});return}J(t,200,dee,await RU(D,r,i,a),{handler:zU})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zU,cause:e})}},{handler:zU,method:`GET`,skipBodyParse:!0}),Gl=q(Sn,async(e,t,n)=>{try{if(!D){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:uz});return}if(!LU(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:uz});return}let e=_Z(D,g);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;J(t,200,Nt,await pz(D,n.branch,r,n.kind),{handler:uz})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:uz,cause:e})}},{handler:uz,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:uz})}),Kl=q(je,async(e,t,n)=>{if(pM(n,Ze).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:WU});return}if(!D){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:WU});return}try{J(t,200,nn,await Ns(()=>KU(D,n.branch,{fastForward:n.fastForward===!0})),{handler:WU})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:WU,cause:e})}},{handler:WU,method:`POST`});async function ql(e){let[t,...n]=Ke,r=[...n,...e];return await new Promise((e,n)=>{let i=Il(t,r,ZF({...go,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},QR),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 ${QR}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=lz(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Jl=q(jn,async(e,t)=>{if(!Bt.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:YR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ql([`share`,`owners`,`--json`]),n=nz(tz(e));cz(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,Ge,n,{handler:YR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:YR,cause:e})}finally{Bt.release(`/api/share/publish/owners`)}},{handler:YR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:YR})}),Yl=q(jn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!ez(r)||!$R(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:XR});return}if(!Bt.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:XR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ql([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=iz(tz(e));cz(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,vi,n,{handler:XR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:XR,cause:e})}finally{Bt.release(`/api/share/publish/name-check`)}},{handler:XR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:XR})}),Xl=q(yee,async(e,t,n)=>{if(!D){cz(`publish-create`,`no-project`),J(t,200,mn,{ok:!1,error:`no-project`},{handler:ZR});return}if(!ez(n.owner)||!$R(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:ZR});return}if(!Bt.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:ZR,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,D,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await ql(e),i=sz(tz(r));cz(`publish-create`,i.ok?`ok`:i.error),i.ok&&Ue?.()?.refreshRemote().catch(()=>{}),J(t,200,mn,i,{handler:ZR})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:ZR,cause:e})}finally{Bt.release(`/api/share/publish`)}},{handler:ZR,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ZR})}),Ql=q(Xt,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,de,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),nu=D?iN(D):null;async function ru(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:fM(e.headers),previewUrl:null,port:nu?Gs(nu)?.port??0:0,singleFile:Pt};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,dt,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let iu=`local-op-embeddings-set-key`,ou=`local-op-embeddings-clear-key`,su=`/api/local-op/embeddings`;function cu(){let e=At?.();return{projectDir:D??g,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let lu=q(Si,async(e,t,n)=>{if(!Bt.tryAcquire(su)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:iu,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=cu();await new GF(Et).setForProject(e,r,n.key),wt?.reloadCredential(),J(t,200,tt,{keyPresent:!0},{handler:iu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:iu,cause:e})}finally{Bt.release(su)}},{handler:iu,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:iu})}),pu=q(jn,async(e,t)=>{if(!Bt.tryAcquire(su)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:ou,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=cu();await new GF(Et).clearForProject(e,n),wt?.reloadCredential(),J(t,200,tt,{keyPresent:!1},{handler:ou,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:ou,cause:e})}finally{Bt.release(su)}},{handler:ou,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ou})}),mu=`local-op-embeddings-test`,hu=`/api/local-op/embeddings/test`,_u=q(jn,async(e,t)=>{if(!Bt.tryAcquire(hu)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:mu,extraHeaders:{"Retry-After":`5`}});return}try{let e=At?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await RF(new GF(Et),D??g,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Zse({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,Je,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:mu,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:mu,cause:e})}finally{Bt.release(hu)}},{handler:mu,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:mu})}),vu=q(jn,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(wt){let t=wt.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=At?.()?.baseUrl??`https://api.openai.com/v1`,o=await RF(new GF(Et),D??g,a),s=o.apiKey!==null,c=!s&&o.keyless,l=s?o.source:null,u=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,d=0;for(let[e]of x())!dC(e)&&!fC(e)&&!Oi(e)&&(d+=1);J(t,200,bee,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:l,keyHint:u,ready:n,capable:r,embedded:i,total:d},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),bu=0;function xu(){bu+=1,Me?.(`lint-config`)}let Su=()=>`${bu} ${t.getActiveBranch()}`;async function Cu(e,t){let n=jt?.()??hr;try{let r=await vn(e,$L(g,n,{docName:t,projectDir:D??g,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Mt?.()??`warning`;if(ke&&a!==`off`&&!gC(t)){await sr(t,e,`lint-validation`);let r=fR({projectDir:D??g,contentDir:g,baseConfig:n,derivedDocumentIndex:ke,linksValidation:a,admittedDocNames:er,docFilePathFor:e=>cZ(g,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:cZ(g,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 X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Tu(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=nR({projectDir:D??g,contentDir:g});return TL(t.schemas,n)}let Eu=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!DZ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=jt?.()??hr,i=[],a=XL(g,n??void 0,e=>i.push(e)),o=QL(D??g,ZL(r,a),e=>i.push(e));n===null&&i.push(...Tu(o)),J(t,200,Yn,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Du=q(kee,async(e,t,n)=>{let r;try{r=dR(z(g),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}xu();try{let e=jt?.()??hr,n=[],r=XL(g,void 0,e=>n.push(e)),i=QL(D??g,ZL(e,r),e=>n.push(e));n.push(...Tu(i)),J(t,200,Yn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Ou=q(Pn,async(e,t,n)=>{let r;try{let e=z(D??g),t=n.parentPath??[];r=n.delete?Ile(e,n.file):n.field!==void 0&&n.removeField?Ple(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Fle(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Mle(e,n.file,n.field,n.constraint,t):Nle(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Me?.(`files`),xu();try{let e=jt?.()??hr,n=[],r=XL(g,void 0,e=>n.push(e)),i=QL(D??g,ZL(e,r),e=>n.push(e));n.push(...Tu(i)),J(t,200,Yn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),ku=q(jn,async(e,t)=>{try{let e=z(D??g),{schemas:n,truncated:r}=sle(e),i=new Set(n),a=!1;if(lt!==void 0){let t=GX({contentDir:g,contentFilter:lt,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&&Qr(a)){let t=R(e,z(g,a));!t.startsWith(`..`)&&!Hl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,Gee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Au=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},ju=q(jn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!DZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=cZ(g,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=jt?.()??hr,a=[],o=await tR({projectDir:D??g,contentDir:g,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Au});J(t,200,Rr,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof KI){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Mu=new xL,Nu=OJ();function Pu(e,t,n){let r=`${n} ${Su()} ${t??``}`;return Nu.run(r,()=>Ble(e,{targetPath:t})).promise}function Fu(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Iu=q(jn,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&&!qX(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=jt?.()??hr;J(t,200,Ni,await rR({projectDir:D??g,contentDir:g,baseConfig:i,targetPath:r,liveSourceFor:Au,cache:Mu,auditGeneration:Su}),{handler:`lint-audit`})}catch(e){if(e instanceof eR){Fu(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),Ru=q(jn,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&&!qX(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!qX(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=cZ(g,o)??`${o}.md`}let s=jt?.()??hr,c=await Pu(fR({projectDir:D??g,contentDir:g,baseConfig:s,liveSourceFor:Au,derivedDocumentIndex:ke??null,linksValidation:Mt?.(),admittedDocNames:er,docFilePathFor:e=>cZ(g,e),cache:Mu,auditGeneration:Su}),i,xL.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){J(t,200,fi,zle(c),{handler:`audit`});return}J(t,200,Gr,c,{handler:`audit`})}catch(e){if(e instanceof eR){Fu(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),zu=q(qi,async(t,n,r)=>{try{let t=QX(r.docName,n,`lint-fix`);if(t===null)return;let i=Dn(t),a=pM(r,Ze);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,l=a.kind===`anonymous`?o:a.colorSeed,u=a.kind===`agent`?a.clientName:void 0;if(dC(i)||fC(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let d=cZ(g,i);if(d===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}$X(z(g,d),g);let f=jt?.()??hr,{stored:p}=ii(a.summary),m=await s.getSession(i,o,{displayName:c,colorSeed:l,clientName:u}),h=m.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Ole({projectDir:D??g,contentDir:g,baseConfig:f,docRelPath:d,source:h}),b=v,x;if(y!==h){try{let t=tr(u),n=Jn[t]??Lr(l??o);Le?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),m.dc.document.transact(()=>{YT(m.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,qT(m))},m.origin),a.kind!==`anonymous`&&yF(i,o,c,l,void 0,a.kind===`agent`?Zr({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,p)}finally{Le?.touchMode(o,`idle`)}let t=await Bn(i);if(t?.kind===`failure`){Vn(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Hn(n,`lint-fix`);return}zn(i,`lint-fix`);try{b=await vn(m.dc.document.getText(`source`).toString(),_,d)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,nr,{file:d,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 KI){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof BC){VC(n,e,`lint-fix`);return}if(e instanceof GC){qC(n,e,`lint-fix`);return}if(e instanceof nE){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Bu=`link-preview`,Vu=new sG({cacheDir:Pt?null:z(D??g,`.ok`,`local`,`link-previews`)}),Hu=null,Uu=()=>(Hu??=Vu.init(),Hu),Wu=Lt??QW;async function Ku(e){let t=await Wu(e);return t.ok?{ok:!0,metadata:await rG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Wu})}:{ok:!1,reason:t.reason}}let Ju=()=>{try{return zt?.()===!0}catch{return!1}},Yu=q($r,async(e,t,n)=>{try{if(!Ju()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,Ei,{ok:!1,reason:`disabled`},{handler:Bu});return}await Uu();let e=!1,r=await Vu.load(n.url,()=>(e=!0,Ku(n.url)));Vu.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,Ei,i,{handler:Bu})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Bu,cause:e})}},{handler:Bu,method:`POST`,preBodyGate:(e,t)=>{let n=uG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Bu}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Bu}),!1)}}),Xu=KM({service:un,getPrincipal:Ze,onChanged:()=>Me?.(`comments`)}),Zu={"/api/config":ru,"/api/comments":eW({GET:Xu.list,POST:Xu.create},{handler:`comments`}),"/api/comment":eW({GET:Xu.read,POST:Xu.mutate,DELETE:Xu.remove},{handler:`comment`}),"/api/asset":Xa,"/api/asset-text":$a,"/api/document":Ai,"/api/documents":ji,"/api/backlinks":Mi,"/api/backlink-counts":$i,"/api/comment-counts":ta,"/api/link-preview":Yu,"/api/forward-links":na,"/api/link-graph":ia,"/api/dead-links":la,"/api/orphans":oa,"/api/hubs":sa,"/api/tags":Fs,"/api/pages":O,"/api/folder-config":Hs,"/api/template":Qs,"/api/template/import":$s,"/api/templates":Ks,"/api/skill":Rc,"/api/skill-file":Gc,"/api/skill-file/rename":Kc,"/api/skills":Dc,"/api/skills/installed":Fi,"/api/skills/search":Ri,"/api/skills/popular":zi,"/api/skills/detail":Bi,"/api/skills/preview":Vi,"/api/skills/discover":Gi,"/api/skills/resolve-ref":Ki,"/api/skill/import":tl,"/api/skills/import-bulk":nl,"/api/skill/edit-external":Fc,"/api/skill/duplicate":Lc,"/api/skill/move-scope":Ic,"/api/skill-upload":cl,"/api/skill/install":ll,"/api/skill/uninstall":ul,"/api/skill/restore":fl,"/api/skill/reimport":pl,"/api/skill/revert":ml,"/api/skill-targets":dl,"/api/search":Fl,"/api/semantic-status":vu,"/api/lint/config":Eu,"/api/lint/markdownlint-config":Du,"/api/lint/frontmatter-schema":Ou,"/api/lint/frontmatter-schemas":ku,"/api/lint":ju,"/api/lint/audit":Iu,"/api/lint/fix":zu,"/api/audit":Ru,"/api/suggest-links":uo,"/api/page-headings":oo,"/api/create-page":to,"/api/create-folder":ro,"/api/duplicate-path":io,"/api/rename-path":so,"/api/delete-path":co,"/api/trash/cleanup":lo,"/api/upload":fo,"/api/agent-write":_i,"/api/agent-write-md":yi,"/api/agent-write-batch":xi,"/api/frontmatter-patch":wi,"/api/agent-patch":ua,"/api/agent-undo":fa,"/api/agent-activity":ma,"/api/agent-burst-diff":ha,"/api/save-version":wa,"/api/history":Ta,"/api/rollback":ka,"/api/metrics/reconciliation":Fa,"/api/metrics/parse-health":La,"/api/metrics/agent-presence":Wa,"/api/metrics/agent-effects":Ga,"/api/metrics/watcher-recent":Ka,"/api/__embed-detect":Ja,"/api/server-info":Ra,"/api/acp/catalog":Va,"/api/share/construct-url":Ul,"/api/share/target-status":Gl,"/api/git/branch-info":Wl,"/api/git/checkout":Kl,"/api/share/publish/owners":Jl,"/api/share/publish/name-check":Yl,"/api/share/publish":Xl,"/api/principal":Ha,"/api/rescue":eo,"/api/workspace":Ya,"/api/sync/status":_s,"/api/sync/trigger":ys,"/api/sync/conflicts":bs,"/api/sync/conflict-content":Ts,"/api/sync/resolve-conflict":xs,"/api/local-op/clone":yo,"/api/local-op/ok-init":Co,"/api/local-op/auth/login":Vo,"/api/local-op/auth/status":Xo,"/api/local-op/auth/pat":$o,"/api/local-op/auth/gh-login":Go,"/api/local-op/auth/cancel":qo,"/api/local-op/auth/repos":ts,"/api/local-op/auth/signout":ss,"/api/local-op/auth/set-identity":hs,"/api/local-op/embeddings/set-key":lu,"/api/local-op/embeddings/clear-key":pu,"/api/local-op/embeddings/test":_u,"/api/installed-agents":Ps,"/api/spawn-cursor":Bl,"/api/handoff":Rl,"/api/install-skill":js,"/api/skill/install-state":Ll,"/api/seed/plan":Ds,"/api/seed/apply":Os,"/api/seed/packs":ks,"/api/client-logs":Ql};pe&&(Zu[`/api/test-reset`]=va,Zu[`/api/test-flush-git`]=_a,Zu[`/api/test-rescan-backlinks`]=xa,Zu[`/api/test-rescan-files`]=Ca);let Qu=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),$u=[`/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};Ose({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`:Zu[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?Oae(e):void 0;if(c!==void 0&&(kae(e,c),typeof t.setHeader==`function`&&t.setHeader(AC,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,X.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&&!Tj(r,n)){K(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, ${AC}, ${xr.protocol}, ${xr.runtime}, ${xr.kind}`),t.setHeader(`Access-Control-Expose-Headers`,AC)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Qu.has(r)||$u.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!mj(n)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Pt&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!mj(n)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=Bo.extract(Ho.active(),e.headers),u=Yee(),d=Date.now();await Ho.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:Jee.SERVER,attributes:{[Es]:o,[Cs]:s,[ws]:r,[Ss]:`http`,[Xee]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=Zu[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 Da(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await Is(e,t,n))}a||K(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(As,s),s>=500&&n.setStatus({code:zo.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:zo.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&K(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;eX().record(e,{[Es]:o,[Cs]:s,[As]:t.statusCode})}}))}}}function AZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function jZ(e){let t;try{t=au(e.contentDir,{withFileTypes:!0})}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&bC(n.name,Qa)&&e.basenameIndex.add(n.name)}async function MZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Tu(i,{withFileTypes:!0})}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=Ej(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Cu(a)}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Eu(a)}catch(t){let n=AZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Dj(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Du(i)}catch(t){let n=AZ(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()&&bC(a,Ba)&&!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()&&bC(a,Ba)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const NZ=A({principalId:j().optional(),tabSessionId:j().optional(),expectedServerInstanceId:j().optional(),expectedBranch:j().optional(),expectedDocLineageEpoch:j().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:j().optional(),clientKind:j().optional()}).loose(),PZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function FZ(e){return PZ.includes(e)}function IZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function LZ(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!FZ(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 RZ=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=IZ(e,this.payload)}};function zZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=NZ.safeParse(t);return n.success?n.data:void 0}var BZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const VZ=F(`conflict-storage`);var HZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(iN(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!V(this.storePath)){this.conflicts=[];return}try{let e=H(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){VZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){VZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);V(e)||eu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return fu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return VZ.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-CZCF5f5x.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(!Dj(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);lV(r,t),vs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),VZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await gS(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){VZ.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}),VZ.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(!Dj(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(lV(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-CZCF5f5x.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);lV(a,i),vs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);vs(a,n,`utf-8`);break;case`delete`:V(a)&&is(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function UZ(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 WZ(e,t){let n=iN(e);try{eu(n,{recursive:!0}),fu(L(n,pn),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Ds(e);eu(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`};fu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const GZ=new Map;let KZ=!1;function qZ(e,t){try{let n=UZ(e,t);for(let e of GZ.keys())WZ(e,n)}catch{}}function JZ(e){GZ.set(e,(GZ.get(e)??0)+1),KZ||(KZ=!0,process.on(`uncaughtExceptionMonitor`,qZ));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=GZ.get(e)??0;n<=1?GZ.delete(e):GZ.set(e,n-1)}}}function YZ(e){let t=e.scheduler??Gi,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 XZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ZZ(e){if(!V(e))return{};let t;try{t=(0,rj.parse)(H(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(!XZ(t))return{};let n=t.telemetry;if(!XZ(n))return{};let r=n.localSink;return XZ(r)?r:{}}function QZ(e){return typeof e==`boolean`?e:void 0}function $Z(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function eQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function tQ(e){if(XZ(e))return $Z(e.maxBytes)}function nQ(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=ZZ(Xo(`project`,e.projectDir)),n=ZZ(Xo(`project-local`,e.projectDir));if((QZ(n.enabled)??QZ(t.enabled)??!0)===!1)return null;let r=tQ(n.spans)??tQ(t.spans)??52428800,i=tQ(n.logs)??tQ(t.logs)??26214400,a=eQ(n.attributeDenylist)??eQ(t.attributeDenylist)??ro;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var rQ;(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})(rQ||={});var iQ;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(iQ||={});const aQ=rQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),oQ=e=>{switch(typeof e){case`undefined`:return aQ.undefined;case`string`:return aQ.string;case`number`:return Number.isNaN(e)?aQ.nan:aQ.number;case`boolean`:return aQ.boolean;case`function`:return aQ.function;case`bigint`:return aQ.bigint;case`symbol`:return aQ.symbol;case`object`:return Array.isArray(e)?aQ.array:e===null?aQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?aQ.promise:typeof Map<`u`&&e instanceof Map?aQ.map:typeof Set<`u`&&e instanceof Set?aQ.set:typeof Date<`u`&&e instanceof Date?aQ.date:aQ.object;default:return aQ.unknown}},Z=rQ.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 sQ=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,rQ.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()}};sQ.create=e=>new sQ(e);const cQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===aQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,rQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${rQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${rQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${rQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:rQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,rQ.assertNever(e)}return{message:n}};let lQ=cQ;function uQ(){return lQ}const dQ=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 fQ(e,t){let n=uQ(),r=dQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===cQ?void 0:cQ].filter(e=>!!e)});e.common.issues.push(r)}var pQ=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 mQ;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 mQ;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 mQ=Object.freeze({status:`aborted`}),hQ=e=>({status:`dirty`,value:e}),gQ=e=>({status:`valid`,value:e}),_Q=e=>e.status===`aborted`,vQ=e=>e.status===`dirty`,yQ=e=>e.status===`valid`,bQ=e=>typeof Promise<`u`&&e instanceof Promise;var xQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(xQ||={});var SQ=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 CQ=(e,t)=>{if(yQ(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 sQ(e.common.issues);return this._error=t,this._error}}};function wQ(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 TQ=class{get description(){return this._def.description}_getType(e){return oQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:oQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new pQ,ctx:{common:e.parent.common,data:e.data,parsedType:oQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(bQ(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:oQ(e)};return CQ(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:oQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yQ(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=>yQ(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:oQ(e)},r=this._parse({data:e,path:n.path,parent:n});return CQ(n,await(bQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new D$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return O$.create(this,this._def)}nullable(){return k$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return c$.create(this)}promise(){return E$.create(this,this._def)}or(e){return d$.create([this,e],this._def)}and(e){return h$.create(this,e,this._def)}transform(e){return new D$({...wQ(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new A$({...wQ(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new N$({typeName:Q.ZodBranded,type:this,...wQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new j$({...wQ(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return P$.create(this,e)}readonly(){return F$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const EQ=/^c[^\s-]{8,}$/i,DQ=/^[0-9a-z]+$/,OQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kQ=/^[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,AQ=/^[a-z0-9_-]{21}$/i,jQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,MQ=/^[-+]?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)?)??$/,NQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let PQ;const FQ=/^(?:(?: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])$/,IQ=/^(?:(?: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])$/,LQ=/^(([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]))$/,RQ=/^(([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])$/,zQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BQ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,VQ=`((\\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])))`,HQ=RegExp(`^${VQ}$`);function UQ(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 WQ(e){return RegExp(`^${UQ(e)}$`)}function GQ(e){let t=`${VQ}T${UQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function KQ(e,t){return!!((t===`v4`||!t)&&FQ.test(e)||(t===`v6`||!t)&&LQ.test(e))}function qQ(e,t){if(!jQ.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 JQ(e,t){return!!((t===`v4`||!t)&&IQ.test(e)||(t===`v6`||!t)&&RQ.test(e))}var YQ=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==aQ.string){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.string,received:t.parsedType}),mQ}let t=new pQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)NQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)PQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),PQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)kQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)AQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)EQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)DQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)OQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),fQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?GQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?HQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?WQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?MQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?KQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?qQ(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?JQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?zQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?BQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):rQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Z.invalid_string,...xQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...xQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...xQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...xQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...xQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...xQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...xQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...xQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...xQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...xQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...xQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...xQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...xQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...xQ.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,...xQ.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,...xQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...xQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...xQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...xQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...xQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...xQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...xQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...xQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...xQ.errToObj(t)})}nonempty(e){return this.min(1,xQ.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}};YQ.create=e=>new YQ({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...wQ(e)});function XQ(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 ZQ=class e extends TQ{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)!==aQ.number){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.number,received:t.parsedType}),mQ}let t,n=new pQ;for(let r of this._def.checks)r.kind===`int`?rQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?XQ(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):rQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:xQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:xQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:xQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:xQ.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`&&rQ.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)}};ZQ.create=e=>new ZQ({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...wQ(e)});var QQ=class e extends TQ{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)!==aQ.bigint)return this._getInvalidInput(e);let t,n=new pQ;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),fQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):rQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.bigint,received:t.parsedType}),mQ}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.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:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.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}};QQ.create=e=>new QQ({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...wQ(e)});var $Q=class extends TQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==aQ.boolean){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.boolean,received:t.parsedType}),mQ}return gQ(e.data)}};$Q.create=e=>new $Q({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...wQ(e)});var e$=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==aQ.date){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.date,received:t.parsedType}),mQ}if(Number.isNaN(e.data.getTime()))return fQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),mQ;let t=new pQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):rQ.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:xQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:xQ.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)}};e$.create=e=>new e$({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...wQ(e)});var t$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.symbol){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.symbol,received:t.parsedType}),mQ}return gQ(e.data)}};t$.create=e=>new t$({typeName:Q.ZodSymbol,...wQ(e)});var n$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.undefined,received:t.parsedType}),mQ}return gQ(e.data)}};n$.create=e=>new n$({typeName:Q.ZodUndefined,...wQ(e)});var r$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.null){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.null,received:t.parsedType}),mQ}return gQ(e.data)}};r$.create=e=>new r$({typeName:Q.ZodNull,...wQ(e)});var i$=class extends TQ{constructor(){super(...arguments),this._any=!0}_parse(e){return gQ(e.data)}};i$.create=e=>new i$({typeName:Q.ZodAny,...wQ(e)});var a$=class extends TQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gQ(e.data)}};a$.create=e=>new a$({typeName:Q.ZodUnknown,...wQ(e)});var o$=class extends TQ{_parse(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.never,received:t.parsedType}),mQ}};o$.create=e=>new o$({typeName:Q.ZodNever,...wQ(e)});var s$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.void,received:t.parsedType}),mQ}return gQ(e.data)}};s$.create=e=>new s$({typeName:Q.ZodVoid,...wQ(e)});var c$=class e extends TQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==aQ.array)return fQ(t,{code:Z.invalid_type,expected:aQ.array,received:t.parsedType}),mQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(fQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(fQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(fQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new SQ(t,e,t.path,n)))).then(e=>pQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new SQ(t,e,t.path,n)));return pQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:xQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:xQ.toString(n)}})}nonempty(e){return this.min(1,e)}};c$.create=(e,t)=>new c$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...wQ(t)});function l$(e){if(e instanceof u$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=O$.create(l$(r))}return new u$({...e._def,shape:()=>t})}else if(e instanceof c$)return new c$({...e._def,type:l$(e.element)});else if(e instanceof O$)return O$.create(l$(e.unwrap()));else if(e instanceof k$)return k$.create(l$(e.unwrap()));else if(e instanceof g$)return g$.create(e.items.map(e=>l$(e)));else return e}var u$=class e extends TQ{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=rQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==aQ.object){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.object,received:t.parsedType}),mQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof o$&&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 SQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof o$){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&&(fQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new SQ(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=>pQ.mergeObjectSync(t,e)):pQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return xQ.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:xQ.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of rQ.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 rQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return l$(this)}partial(t){let n={};for(let e of rQ.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 rQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof O$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return C$(rQ.objectKeys(this.shape))}};u$.create=(e,t)=>new u$({shape:()=>e,unknownKeys:`strip`,catchall:o$.create(),typeName:Q.ZodObject,...wQ(t)}),u$.strictCreate=(e,t)=>new u$({shape:()=>e,unknownKeys:`strict`,catchall:o$.create(),typeName:Q.ZodObject,...wQ(t)}),u$.lazycreate=(e,t)=>new u$({shape:e,unknownKeys:`strip`,catchall:o$.create(),typeName:Q.ZodObject,...wQ(t)});var d$=class extends TQ{_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 sQ(e.ctx.common.issues));return fQ(t,{code:Z.invalid_union,unionErrors:n}),mQ}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 sQ(e));return fQ(t,{code:Z.invalid_union,unionErrors:i}),mQ}}get options(){return this._def.options}};d$.create=(e,t)=>new d$({options:e,typeName:Q.ZodUnion,...wQ(t)});const f$=e=>e instanceof x$?f$(e.schema):e instanceof D$?f$(e.innerType()):e instanceof S$?[e.value]:e instanceof w$?e.options:e instanceof T$?rQ.objectValues(e.enum):e instanceof A$?f$(e._def.innerType):e instanceof n$?[void 0]:e instanceof r$?[null]:e instanceof O$?[void 0,...f$(e.unwrap())]:e instanceof k$?[null,...f$(e.unwrap())]:e instanceof N$||e instanceof F$?f$(e.unwrap()):e instanceof j$?f$(e._def.innerType):[];var p$=class e extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==aQ.object)return fQ(t,{code:Z.invalid_type,expected:aQ.object,received:t.parsedType}),mQ;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}):(fQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),mQ)}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=f$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...wQ(r)})}};function m$(e,t){let n=oQ(e),r=oQ(t);if(e===t)return{valid:!0,data:e};if(n===aQ.object&&r===aQ.object){let n=rQ.objectKeys(t),r=rQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=m$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===aQ.array&&r===aQ.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=m$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===aQ.date&&r===aQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var h$=class extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(_Q(e)||_Q(r))return mQ;let i=m$(e.value,r.value);return i.valid?((vQ(e)||vQ(r))&&t.dirty(),{status:t.value,value:i.data}):(fQ(n,{code:Z.invalid_intersection_types}),mQ)};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}))}};h$.create=(e,t,n)=>new h$({left:e,right:t,typeName:Q.ZodIntersection,...wQ(n)});var g$=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==aQ.array)return fQ(n,{code:Z.invalid_type,expected:aQ.array,received:n.parsedType}),mQ;if(n.data.length<this._def.items.length)return fQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),mQ;!this._def.rest&&n.data.length>this._def.items.length&&(fQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new SQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>pQ.mergeArray(t,e)):pQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};g$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new g$({items:e,typeName:Q.ZodTuple,rest:null,...wQ(t)})};var _$=class e extends TQ{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!==aQ.object)return fQ(n,{code:Z.invalid_type,expected:aQ.object,received:n.parsedType}),mQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new SQ(n,e,n.path,e)),value:a._parse(new SQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?pQ.mergeObjectAsync(t,r):pQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof TQ?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...wQ(r)}):new e({keyType:YQ.create(),valueType:t,typeName:Q.ZodRecord,...wQ(n)})}},v$=class extends TQ{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!==aQ.map)return fQ(n,{code:Z.invalid_type,expected:aQ.map,received:n.parsedType}),mQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new SQ(n,e,n.path,[a,`key`])),value:i._parse(new SQ(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 mQ;(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 mQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};v$.create=(e,t,n)=>new v$({valueType:t,keyType:e,typeName:Q.ZodMap,...wQ(n)});var y$=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==aQ.set)return fQ(n,{code:Z.invalid_type,expected:aQ.set,received:n.parsedType}),mQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(fQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(fQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return mQ;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 SQ(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:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:xQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};y$.create=(e,t)=>new y$({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...wQ(t)});var b$=class e extends TQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==aQ.function)return fQ(t,{code:Z.invalid_type,expected:aQ.function,received:t.parsedType}),mQ;function n(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),cQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),cQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof E$){let e=this;return gQ(async function(...t){let o=new sQ([]),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 gQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new sQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new sQ([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:g$.create(t).rest(a$.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||g$.create([]).rest(a$.create()),returns:n||a$.create(),typeName:Q.ZodFunction,...wQ(r)})}},x$=class extends TQ{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})}};x$.create=(e,t)=>new x$({getter:e,typeName:Q.ZodLazy,...wQ(t)});var S$=class extends TQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return fQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),mQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};S$.create=(e,t)=>new S$({value:e,typeName:Q.ZodLiteral,...wQ(t)});function C$(e,t){return new w$({values:e,typeName:Q.ZodEnum,...wQ(t)})}var w$=class e extends TQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{expected:rQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),mQ}return gQ(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})}};w$.create=C$;var T$=class extends TQ{_parse(e){let t=rQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==aQ.string&&n.parsedType!==aQ.number){let e=rQ.objectValues(t);return fQ(n,{expected:rQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(rQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=rQ.objectValues(t);return fQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),mQ}return gQ(e.data)}get enum(){return this._def.values}};T$.create=(e,t)=>new T$({values:e,typeName:Q.ZodNativeEnum,...wQ(t)});var E$=class extends TQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==aQ.promise&&t.common.async===!1?(fQ(t,{code:Z.invalid_type,expected:aQ.promise,received:t.parsedType}),mQ):gQ((t.parsedType===aQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};E$.create=(e,t)=>new E$({type:e,typeName:Q.ZodPromise,...wQ(t)});var D$=class extends TQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{fQ(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 mQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(r.value):r});{if(t.value===`aborted`)return mQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(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`?mQ:(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`?mQ:(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(!yQ(e))return mQ;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=>yQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):mQ);rQ.assertNever(r)}};D$.create=(e,t,n)=>new D$({schema:e,typeName:Q.ZodEffects,effect:t,...wQ(n)}),D$.createWithPreprocess=(e,t,n)=>new D$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...wQ(n)});var O$=class extends TQ{_parse(e){return this._getType(e)===aQ.undefined?gQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};O$.create=(e,t)=>new O$({innerType:e,typeName:Q.ZodOptional,...wQ(t)});var k$=class extends TQ{_parse(e){return this._getType(e)===aQ.null?gQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};k$.create=(e,t)=>new k$({innerType:e,typeName:Q.ZodNullable,...wQ(t)});var A$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===aQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};A$.create=(e,t)=>new A$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...wQ(t)});var j$=class extends TQ{_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 bQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new sQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new sQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};j$.create=(e,t)=>new j$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...wQ(t)});var M$=class extends TQ{_parse(e){if(this._getType(e)!==aQ.nan){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:aQ.nan,received:t.parsedType}),mQ}return{status:`valid`,value:e.data}}};M$.create=e=>new M$({typeName:Q.ZodNaN,...wQ(e)});var N$=class extends TQ{_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}},P$=class e extends TQ{_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`?mQ:e.status===`dirty`?(t.dirty(),hQ(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`?mQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},F$=class extends TQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(yQ(e)&&(e.value=Object.freeze(e.value)),e);return bQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};F$.create=(e,t)=>new F$({innerType:e,typeName:Q.ZodReadonly,...wQ(t)}),u$.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),YQ.create,ZQ.create,M$.create,QQ.create,$Q.create,e$.create,t$.create,n$.create,r$.create,i$.create,a$.create,o$.create,s$.create,c$.create;const I$=u$.create;u$.strictCreate,d$.create,p$.create,h$.create,g$.create,_$.create,v$.create,y$.create,b$.create,x$.create,S$.create,w$.create,T$.create,E$.create,D$.create,O$.create,k$.create,D$.createWithPreprocess,P$.create;const L$=to(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);io.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Wa(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>eo(e,t,n),e.parseAsync=async(t,n)=>Ha(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>bo(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)=>yo(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),R$=to(`ZodMiniObject`,(e,t)=>{Fo.init(e,t),L$.init(e,t),Za(e,`shape`,()=>t.shape)});function z$(e,t){return new R$({type:`object`,shape:e??{},...$a(t)})}function B$(e){return!!e._zod}function V$(e){let t=Object.values(e);if(t.length===0)return z$({});let n=t.every(B$),r=t.every(e=>!B$(e));if(n)return z$(e);if(r)return I$(e);throw Error(`Mixed Zod versions detected in object shape.`)}function H$(e,t){return B$(e)?eo(e,t):e.safeParse(t)}async function U$(e,t){return B$(e)?await bo(e,t):await e.safeParseAsync(t)}function W$(e){if(!e)return;let t;if(t=B$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function G$(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 V$(e)}}if(B$(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 K$(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 q$(e){return e.description}function J$(e){if(B$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Y$(e){if(B$(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 X$=`2025-11-25`,Z$=[X$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Q$=`io.modelcontextprotocol/related-task`,$$=ko(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),e1=ho([j(),P().int()]),t1=j();So({ttl:P().optional(),pollInterval:P().optional()});const n1=A({ttl:P().optional()}),r1=A({taskId:j()}),i1=So({progressToken:e1.optional(),[Q$]:r1.optional()}),a1=A({_meta:i1.optional()}),o1=a1.extend({task:n1.optional()}),s1=e=>o1.safeParse(e).success,c1=A({method:j(),params:a1.loose().optional()}),l1=A({_meta:i1.optional()}),u1=A({method:j(),params:l1.loose().optional()}),d1=So({_meta:i1.optional()}),f1=ho([j(),P().int()]),p1=A({jsonrpc:k(`2.0`),id:f1,...c1.shape}).strict(),m1=e=>p1.safeParse(e).success,h1=A({jsonrpc:k(`2.0`),...u1.shape}).strict(),Gle=e=>h1.safeParse(e).success,g1=A({jsonrpc:k(`2.0`),id:f1,result:d1}).strict(),_1=e=>g1.safeParse(e).success;var v1;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(v1||={});const y1=A({jsonrpc:k(`2.0`),id:f1.optional(),error:A({code:P().int(),message:j(),data:O().optional()})}).strict(),b1=e=>y1.safeParse(e).success,x1=ho([p1,h1,g1,y1]);ho([g1,y1]);const S1=d1.strict(),Kle=l1.extend({requestId:f1.optional(),reason:j().optional()}),C1=u1.extend({method:k(`notifications/cancelled`),params:Kle}),w1=A({icons:N(A({src:j(),mimeType:j().optional(),sizes:N(j()).optional(),theme:no([`light`,`dark`]).optional()})).optional()}),T1=A({name:j(),title:j().optional()}),E1=T1.extend({...T1.shape,...w1.shape,version:j(),websiteUrl:j().optional(),description:j().optional()}),qle=Do(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Eo(A({form:Eo(A({applyDefaults:To().optional()}),M(j(),O())).optional(),url:$$.optional()}),M(j(),O()).optional())),Jle=So({list:$$.optional(),cancel:$$.optional(),requests:So({sampling:So({createMessage:$$.optional()}).optional(),elicitation:So({create:$$.optional()}).optional()}).optional()}),Yle=So({list:$$.optional(),cancel:$$.optional(),requests:So({tools:So({call:$$.optional()}).optional()}).optional()}),Xle=A({experimental:M(j(),$$).optional(),sampling:A({context:$$.optional(),tools:$$.optional()}).optional(),elicitation:qle.optional(),roots:A({listChanged:To().optional()}).optional(),tasks:Jle.optional(),extensions:M(j(),$$).optional()}),Zle=a1.extend({protocolVersion:j(),capabilities:Xle,clientInfo:E1}),D1=c1.extend({method:k(`initialize`),params:Zle}),O1=e=>D1.safeParse(e).success,Qle=A({experimental:M(j(),$$).optional(),logging:$$.optional(),completions:$$.optional(),prompts:A({listChanged:To().optional()}).optional(),resources:A({subscribe:To().optional(),listChanged:To().optional()}).optional(),tools:A({listChanged:To().optional()}).optional(),tasks:Yle.optional(),extensions:M(j(),$$).optional()}),$le=d1.extend({protocolVersion:j(),capabilities:Qle,serverInfo:E1,instructions:j().optional()}),k1=u1.extend({method:k(`notifications/initialized`),params:l1.optional()}),eue=e=>k1.safeParse(e).success,A1=c1.extend({method:k(`ping`),params:a1.optional()}),tue=A({progress:P(),total:po(P()),message:po(j())}),nue=A({...l1.shape,...tue.shape,progressToken:e1}),j1=u1.extend({method:k(`notifications/progress`),params:nue}),rue=a1.extend({cursor:t1.optional()}),M1=c1.extend({params:rue.optional()}),N1=d1.extend({nextCursor:t1.optional()}),iue=no([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P1=A({taskId:j(),status:iue,ttl:ho([P(),Ra()]),createdAt:j(),lastUpdatedAt:j(),pollInterval:po(P()),statusMessage:po(j())}),F1=d1.extend({task:P1}),aue=l1.merge(P1),I1=u1.extend({method:k(`notifications/tasks/status`),params:aue}),L1=c1.extend({method:k(`tasks/get`),params:a1.extend({taskId:j()})}),R1=d1.merge(P1),z1=c1.extend({method:k(`tasks/result`),params:a1.extend({taskId:j()})});d1.loose();const B1=M1.extend({method:k(`tasks/list`)}),V1=N1.extend({tasks:N(P1)}),H1=c1.extend({method:k(`tasks/cancel`),params:a1.extend({taskId:j()})}),oue=d1.merge(P1),U1=A({uri:j(),mimeType:po(j()),_meta:M(j(),O()).optional()}),W1=U1.extend({text:j()}),G1=j().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),K1=U1.extend({blob:G1}),q1=no([`user`,`assistant`]),J1=A({audience:N(q1).optional(),priority:P().min(0).max(1).optional(),lastModified:fo({offset:!0}).optional()}),Y1=A({...T1.shape,...w1.shape,uri:j(),description:po(j()),mimeType:po(j()),size:po(P()),annotations:J1.optional(),_meta:po(So({}))}),sue=A({...T1.shape,...w1.shape,uriTemplate:j(),description:po(j()),mimeType:po(j()),annotations:J1.optional(),_meta:po(So({}))}),X1=M1.extend({method:k(`resources/list`)}),cue=N1.extend({resources:N(Y1)}),Z1=M1.extend({method:k(`resources/templates/list`)}),lue=N1.extend({resourceTemplates:N(sue)}),Q1=a1.extend({uri:j()}),uue=Q1,$1=c1.extend({method:k(`resources/read`),params:uue}),due=d1.extend({contents:N(ho([W1,K1]))}),fue=u1.extend({method:k(`notifications/resources/list_changed`),params:l1.optional()}),pue=Q1,mue=c1.extend({method:k(`resources/subscribe`),params:pue}),hue=Q1,gue=c1.extend({method:k(`resources/unsubscribe`),params:hue}),_ue=l1.extend({uri:j()}),vue=u1.extend({method:k(`notifications/resources/updated`),params:_ue}),yue=A({name:j(),description:po(j()),required:po(To())}),bue=A({...T1.shape,...w1.shape,description:po(j()),arguments:po(N(yue)),_meta:po(So({}))}),e0=M1.extend({method:k(`prompts/list`)}),t0=N1.extend({prompts:N(bue)}),xue=a1.extend({name:j(),arguments:M(j(),j()).optional()}),n0=c1.extend({method:k(`prompts/get`),params:xue}),r0=A({type:k(`text`),text:j(),annotations:J1.optional(),_meta:M(j(),O()).optional()}),i0=A({type:k(`image`),data:G1,mimeType:j(),annotations:J1.optional(),_meta:M(j(),O()).optional()}),a0=A({type:k(`audio`),data:G1,mimeType:j(),annotations:J1.optional(),_meta:M(j(),O()).optional()}),Sue=A({type:k(`tool_use`),name:j(),id:j(),input:M(j(),O()),_meta:M(j(),O()).optional()}),Cue=A({type:k(`resource`),resource:ho([W1,K1]),annotations:J1.optional(),_meta:M(j(),O()).optional()}),o0=ho([r0,i0,a0,Y1.extend({type:k(`resource_link`)}),Cue]),wue=A({role:q1,content:o0}),Tue=d1.extend({description:j().optional(),messages:N(wue)}),Eue=u1.extend({method:k(`notifications/prompts/list_changed`),params:l1.optional()}),Due=A({title:j().optional(),readOnlyHint:To().optional(),destructiveHint:To().optional(),idempotentHint:To().optional(),openWorldHint:To().optional()}),Oue=A({taskSupport:no([`required`,`optional`,`forbidden`]).optional()}),s0=A({...T1.shape,...w1.shape,description:j().optional(),inputSchema:A({type:k(`object`),properties:M(j(),$$).optional(),required:N(j()).optional()}).catchall(O()),outputSchema:A({type:k(`object`),properties:M(j(),$$).optional(),required:N(j()).optional()}).catchall(O()).optional(),annotations:Due.optional(),execution:Oue.optional(),_meta:M(j(),O()).optional()}),c0=M1.extend({method:k(`tools/list`)}),kue=N1.extend({tools:N(s0)}),l0=d1.extend({content:N(o0).default([]),structuredContent:M(j(),O()).optional(),isError:To().optional()});l0.or(d1.extend({toolResult:O()}));const Aue=o1.extend({name:j(),arguments:M(j(),O()).optional()}),u0=c1.extend({method:k(`tools/call`),params:Aue}),jue=u1.extend({method:k(`notifications/tools/list_changed`),params:l1.optional()});A({autoRefresh:To().default(!0),debounceMs:P().int().nonnegative().default(300)});const d0=no([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Mue=a1.extend({level:d0}),f0=c1.extend({method:k(`logging/setLevel`),params:Mue}),Nue=l1.extend({level:d0,logger:j().optional(),data:O()}),Pue=u1.extend({method:k(`notifications/message`),params:Nue}),Fue=A({hints:N(A({name:j().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),Iue=A({mode:no([`auto`,`required`,`none`]).optional()}),Lue=A({type:k(`tool_result`),toolUseId:j().describe(`The unique identifier for the corresponding tool call.`),content:N(o0).default([]),structuredContent:A({}).loose().optional(),isError:To().optional(),_meta:M(j(),O()).optional()}),Rue=vo(`type`,[r0,i0,a0]),p0=vo(`type`,[r0,i0,a0,Sue,Lue]),zue=A({role:q1,content:ho([p0,N(p0)]),_meta:M(j(),O()).optional()}),Bue=o1.extend({messages:N(zue),modelPreferences:Fue.optional(),systemPrompt:j().optional(),includeContext:no([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(j()).optional(),metadata:$$.optional(),tools:N(s0).optional(),toolChoice:Iue.optional()}),Vue=c1.extend({method:k(`sampling/createMessage`),params:Bue}),m0=d1.extend({model:j(),stopReason:po(no([`endTurn`,`stopSequence`,`maxTokens`]).or(j())),role:q1,content:Rue}),h0=d1.extend({model:j(),stopReason:po(no([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(j())),role:q1,content:ho([p0,N(p0)])}),Hue=A({type:k(`boolean`),title:j().optional(),description:j().optional(),default:To().optional()}),Uue=A({type:k(`string`),title:j().optional(),description:j().optional(),minLength:P().optional(),maxLength:P().optional(),format:no([`email`,`uri`,`date`,`date-time`]).optional(),default:j().optional()}),Wue=A({type:no([`number`,`integer`]),title:j().optional(),description:j().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),Gue=A({type:k(`string`),title:j().optional(),description:j().optional(),enum:N(j()),default:j().optional()}),Kue=A({type:k(`string`),title:j().optional(),description:j().optional(),oneOf:N(A({const:j(),title:j()})),default:j().optional()}),que=ho([ho([A({type:k(`string`),title:j().optional(),description:j().optional(),enum:N(j()),enumNames:N(j()).optional(),default:j().optional()}),ho([Gue,Kue]),ho([A({type:k(`array`),title:j().optional(),description:j().optional(),minItems:P().optional(),maxItems:P().optional(),items:A({type:k(`string`),enum:N(j())}),default:N(j()).optional()}),A({type:k(`array`),title:j().optional(),description:j().optional(),minItems:P().optional(),maxItems:P().optional(),items:A({anyOf:N(A({const:j(),title:j()}))}),default:N(j()).optional()})])]),Hue,Uue,Wue]),Jue=ho([o1.extend({mode:k(`form`).optional(),message:j(),requestedSchema:A({type:k(`object`),properties:M(j(),que),required:N(j()).optional()})}),o1.extend({mode:k(`url`),message:j(),elicitationId:j(),url:j().url()})]),Yue=c1.extend({method:k(`elicitation/create`),params:Jue}),Xue=l1.extend({elicitationId:j()}),Zue=u1.extend({method:k(`notifications/elicitation/complete`),params:Xue}),g0=d1.extend({action:no([`accept`,`decline`,`cancel`]),content:Do(e=>e===null?void 0:e,M(j(),ho([j(),P(),To(),N(j())])).optional())}),Que=A({type:k(`ref/resource`),uri:j()}),$ue=A({type:k(`ref/prompt`),name:j()}),ede=a1.extend({ref:ho([$ue,Que]),argument:A({name:j(),value:j()}),context:A({arguments:M(j(),j()).optional()}).optional()}),_0=c1.extend({method:k(`completion/complete`),params:ede});function tde(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function nde(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const rde=d1.extend({completion:So({values:N(j()).max(100),total:po(P().int()),hasMore:po(To())})}),ide=A({uri:j().startsWith(`file://`),name:j().optional(),_meta:M(j(),O()).optional()}),ade=c1.extend({method:k(`roots/list`),params:a1.optional()}),v0=d1.extend({roots:N(ide)}),ode=u1.extend({method:k(`notifications/roots/list_changed`),params:l1.optional()});ho([A1,D1,_0,f0,n0,e0,X1,Z1,$1,mue,gue,u0,c0,L1,z1,B1,H1]),ho([C1,j1,k1,ode,I1]),ho([S1,m0,h0,g0,v0,R1,V1,F1]),ho([A1,Vue,Yue,ade,L1,z1,B1,H1]),ho([C1,j1,Pue,vue,fue,jue,Eue,I1,Zue]),ho([S1,$le,rde,Tue,t0,cue,lue,due,l0,kue,R1,V1,F1]);var y0=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===v1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new sde(e.elicitations,n)}return new e(t,n,r)}},sde=class extends y0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(v1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function b0(e){return e===`completed`||e===`failed`||e===`cancelled`}const cde=Symbol(`Let zodToJsonSchema decide on which parser to use`),x0={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`},lde=e=>typeof e==`string`?{...x0,name:e}:{...x0,...e},ude=e=>{let t=lde(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 S0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function C0(e,t,n,r,i){e[t]=n,S0(e,t,r,i)}const w0=(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 T0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?w0(t,e.currentPath):t.join(`/`)}}function dde(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=R0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&C0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&C0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(C0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),C0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function fde(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?C0(n,`minimum`,r.value,r.message,t):C0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),C0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?C0(n,`maximum`,r.value,r.message,t):C0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),C0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:C0(n,`multipleOf`,r.value,r.message,t);break}return n}function pde(){return{type:`boolean`}}function E0(e,t){return R0(e.type._def,t)}const mde=(e,t)=>R0(e.innerType._def,t);function D0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>D0(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 hde(e,t)}}const hde=(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`:C0(n,`minimum`,r.value,r.message,t);break;case`max`:C0(n,`maximum`,r.value,r.message,t);break}return n};function gde(e,t){return{...R0(e.innerType._def,t),default:e.defaultValue()}}function _de(e,t){return t.effectStrategy===`input`?R0(e.schema._def,t):T0(t)}function vde(e){return{type:`string`,enum:Array.from(e.values)}}const yde=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function bde(e,t){let n=[R0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),R0(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(yde(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 xde(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 O0;const k0={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:()=>(O0===void 0&&(O0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),O0),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 A0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:C0(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`:M0(n,`email`,r.message,t);break;case`format:idn-email`:M0(n,`idn-email`,r.message,t);break;case`pattern:zod`:N0(n,k0.email,r.message,t);break}break;case`url`:M0(n,`uri`,r.message,t);break;case`uuid`:M0(n,`uuid`,r.message,t);break;case`regex`:N0(n,r.regex,r.message,t);break;case`cuid`:N0(n,k0.cuid,r.message,t);break;case`cuid2`:N0(n,k0.cuid2,r.message,t);break;case`startsWith`:N0(n,RegExp(`^${j0(r.value,t)}`),r.message,t);break;case`endsWith`:N0(n,RegExp(`${j0(r.value,t)}$`),r.message,t);break;case`datetime`:M0(n,`date-time`,r.message,t);break;case`date`:M0(n,`date`,r.message,t);break;case`time`:M0(n,`time`,r.message,t);break;case`duration`:M0(n,`duration`,r.message,t);break;case`length`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),C0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:N0(n,RegExp(j0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&M0(n,`ipv4`,r.message,t),r.version!==`v4`&&M0(n,`ipv6`,r.message,t);break;case`base64url`:N0(n,k0.base64url,r.message,t);break;case`jwt`:N0(n,k0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&N0(n,k0.ipv4Cidr,r.message,t),r.version!==`v4`&&N0(n,k0.ipv6Cidr,r.message,t);break;case`emoji`:N0(n,k0.emoji(),r.message,t);break;case`ulid`:N0(n,k0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:M0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:C0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:N0(n,k0.base64,r.message,t);break}break;case`nanoid`:N0(n,k0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function j0(e,t){return t.patternStrategy===`escape`?Cde(e):e}const Sde=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Cde(e){let t=``;for(let n=0;n<e.length;n++)Sde.has(e[n])||(t+=`\\`),t+=e[n];return t}function M0(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}}})):C0(e,`format`,t,n,r)}function N0(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:P0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):C0(e,`pattern`,P0(t,r),n,r)}function P0(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
|
|
1216
1216
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
1217
1217
|
]))`;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 F0(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===Q.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??T0(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Q.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=A0(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Q.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=E0(e.keyType._def,t);return{...n,propertyNames:i}}return n}function wde(e,t){return t.mapStrategy===`record`?F0(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[R0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||T0(t),R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||T0(t)],minItems:2,maxItems:2}}}function Tde(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 Ede(e){return e.target===`openAi`?void 0:{not:T0({...e,currentPath:[...e.currentPath,`not`]})}}function Dde(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const I0={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Ode(e,t){if(t.target===`openApi3`)return L0(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in I0&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=I0[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 L0(e,t)}const L0=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>R0(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 kde(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:I0[e.innerType._def.typeName],nullable:!0}:{type:[I0[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=R0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=R0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Ade(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`,S0(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?C0(n,`minimum`,r.value,r.message,t):C0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),C0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?C0(n,`maximum`,r.value,r.message,t):C0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),C0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:C0(n,`multipleOf`,r.value,r.message,t);break}return n}function jde(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=Nde(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=R0(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=Mde(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Mde(e,t){if(e.catchall._def.typeName!==`ZodNever`)return R0(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 Nde(e){try{return e.isOptional()}catch{return!0}}const Pde=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return R0(e.innerType._def,t);let n=R0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:T0(t)},n]}:T0(t)},Fde=(e,t)=>{if(t.pipeStrategy===`input`)return R0(e.in._def,t);if(t.pipeStrategy===`output`)return R0(e.out._def,t);let n=R0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,R0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Ide(e,t){return R0(e.type._def,t)}function Lde(e,t){let n={type:`array`,uniqueItems:!0,items:R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&C0(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&C0(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Rde(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>R0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:R0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>R0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function zde(e){return{not:T0(e)}}function Bde(e){return T0(e)}const Vde=(e,t)=>R0(e.innerType._def,t),Hde=(e,t,n)=>{switch(t){case Q.ZodString:return A0(e,n);case Q.ZodNumber:return Ade(e,n);case Q.ZodObject:return jde(e,n);case Q.ZodBigInt:return fde(e,n);case Q.ZodBoolean:return pde();case Q.ZodDate:return D0(e,n);case Q.ZodUndefined:return zde(n);case Q.ZodNull:return Dde(n);case Q.ZodArray:return dde(e,n);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return Ode(e,n);case Q.ZodIntersection:return bde(e,n);case Q.ZodTuple:return Rde(e,n);case Q.ZodRecord:return F0(e,n);case Q.ZodLiteral:return xde(e,n);case Q.ZodEnum:return vde(e);case Q.ZodNativeEnum:return Tde(e);case Q.ZodNullable:return kde(e,n);case Q.ZodOptional:return Pde(e,n);case Q.ZodMap:return wde(e,n);case Q.ZodSet:return Lde(e,n);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return Ide(e,n);case Q.ZodNaN:case Q.ZodNever:return Ede(n);case Q.ZodEffects:return _de(e,n);case Q.ZodAny:return T0(n);case Q.ZodUnknown:return Bde(n);case Q.ZodDefault:return gde(e,n);case Q.ZodBranded:return E0(e,n);case Q.ZodReadonly:return Vde(e,n);case Q.ZodCatch:return mde(e,n);case Q.ZodPipeline:return Fde(e,n);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(e=>void 0)(t)}};function R0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==cde)return i}if(r&&!n){let e=Ude(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=Hde(e,e.typeName,t),o=typeof a==`function`?R0(a(),t):a;if(o&&Wde(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Ude=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:w0(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`),T0(t)):t.$refStrategy===`seen`?T0(t):void 0}},Wde=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Gde=(e,t)=>{let n=ude(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:R0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??T0(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=R0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??T0(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 Kde(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function z0(e,t){return B$(e)?Io(e,{target:Kde(t?.target),io:t?.pipeStrategy??`input`}):Gde(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function B0(e){let t=W$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Y$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function V0(e,t){let n=H$(e,t);if(!n.success)throw n.error;return n.data}var qde=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(C1,e=>{this._oncancel(e)}),this.setNotificationHandler(j1,e=>{this._onprogress(e)}),this.setRequestHandler(A1,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(L1,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new y0(v1.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(z1,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new y0(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 y0(v1.InvalidParams,`Task not found: ${r}`);if(!b0(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(b0(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Q$]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(B1,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new y0(v1.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(H1,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new y0(v1.InvalidParams,`Task not found: ${e.params.taskId}`);if(b0(n.status))throw new y0(v1.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new y0(v1.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof y0?e:new y0(v1.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),y0.fromError(v1.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),_1(e)||b1(e)?this._onresponse(e):m1(e)?this._onrequest(e,t):Gle(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=y0.fromError(v1.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Q$]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:v1.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=s1(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 y0(v1.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:v1.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),_1(e)?n(e):n(new y0(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(_1(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),_1(e)?r(e):r(y0.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 y0?e:new y0(v1.InternalError,String(e))}}return}let i;try{let r=await this.request(e,F1,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new y0(v1.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},b0(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new y0(v1.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new y0(v1.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof y0?e:new y0(v1.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Q$]: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 y0?e:new y0(v1.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=H$(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(y0.fromError(v1.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},R1,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},V1,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},oue,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||{},[Q$]: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||{},[Q$]: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||{},[Q$]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=B0(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=B0(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`&&m1(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new y0(v1.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new y0(v1.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new y0(v1.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new y0(v1.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=I1.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),b0(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 y0(v1.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(b0(a.status))throw new y0(v1.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=I1.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),b0(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function H0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Jde(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];H0(a)&&H0(i)?n[r]={...a,...i}:n[r]=i}return n}var Yde=t(Yt(),1),Xde=t(la(),1);function Zde(){let e=new Yde.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Xde.default)(e),e}var Qde=class{constructor(e){this._ajv=e??Zde()}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)}}},$de=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},m0,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},g0,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 efe(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 tfe(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 nfe=class extends qde{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(d0.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 Qde,this.setRequestHandler(D1,e=>this._oninitialize(e)),this.setNotificationHandler(k1,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(f0,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=d0.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new $de(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Jde(this._capabilities,e)}setRequestHandler(e,t){let n=W$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(B$(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=H$(u0,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new y0(v1.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=H$(F1,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new y0(v1.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=H$(l0,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new y0(v1.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){tfe(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&efe(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:Z$.includes(t)?t:X$,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},S1)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},h0,t):this.request({method:`sampling/createMessage`,params:e},m0,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},g0,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},g0,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new y0(v1.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof y0?e:new y0(v1.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},v0,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 U0=Symbol.for(`mcp.completable`);function W0(e){return!!e&&typeof e==`object`&&U0 in e}function rfe(e){return e[U0]?.complete}var ife;(function(e){e.Completable=`McpCompletable`})(ife||={});const afe=/^[A-Za-z0-9._-]{1,128}$/;function ofe(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`),!afe.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 sfe(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 G0(e){let t=ofe(e);return sfe(e,t.warnings),t.isValid}var cfe=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)}},K0=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 nfe(e,t)}get experimental(){return this._experimental||={tasks:new cfe(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Z0(c0)),this.server.assertCanSetRequestHandler(Z0(u0)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(c0,()=>({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=G$(t.inputSchema);return e?z0(e,{strictUnions:!0,pipeStrategy:`input`}):lfe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=G$(t.outputSchema);e&&(n.outputSchema=z0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(u0,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new y0(v1.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new y0(v1.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new y0(v1.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new y0(v1.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof y0&&e.code===v1.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await U$(G$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=K$(`error`in r?r.error:`Unknown error`);throw new y0(v1.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new y0(v1.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await U$(G$(e.outputSchema),t.structuredContent);if(!r.success){let e=K$(`error`in r?r.error:`Unknown error`);throw new y0(v1.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new y0(v1.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Z0(_0)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_0,async e=>{switch(e.params.ref.type){case`ref/prompt`:return tde(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return nde(e),this.handleResourceCompletion(e,e.params.ref);default:throw new y0(v1.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new y0(v1.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new y0(v1.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return $0;let r=W$(n.argsSchema)?.[e.params.argument.name];if(!W0(r))return $0;let i=rfe(r);return i?Q0(await i(e.params.argument.value,e.params.context)):$0}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 $0;throw new y0(v1.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)):$0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Z0(X1)),this.server.assertCanSetRequestHandler(Z0(Z1)),this.server.assertCanSetRequestHandler(Z0($1)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(X1,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Z1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler($1,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new y0(v1.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new y0(v1.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Z0(e0)),this.server.assertCanSetRequestHandler(Z0(n0)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(e0,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?ufe(t.argsSchema):void 0}))})),this.server.setRequestHandler(n0,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new y0(v1.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new y0(v1.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await U$(G$(n.argsSchema),e.params.arguments);if(!r.success){let t=K$(`error`in r?r.error:`Unknown error`);throw new y0(v1.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:V$(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=V$(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=>W0(e instanceof co?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){G0(e);let l={title:t,description:n,inputSchema:X0(r),outputSchema:X0(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`&&G0(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=V$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=V$(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(Y0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Y0(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 lfe={type:`object`,properties:{}};function q0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function J0(e){return`_def`in e||`_zod`in e||q0(e)}function Y0(e){return typeof e!=`object`||!e||J0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(q0)}function X0(e){if(e){if(Y0(e))return V$(e);if(!J0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function ufe(e){let t=W$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:q$(t),required:!J$(t)})):[]}function Z0(e){let t=W$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Y$(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 $0={completion:{values:[],hasMore:!1}};var e2=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},dfe=e=>e instanceof e2?e:new e2(e.message,{cause:e}),ffe=global.Request,t2=class extends ffe{constructor(e,t){typeof e==`object`&&r2 in e&&(e=e[r2]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},pfe=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)},n2=Symbol(`wrapBodyStream`),mfe=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new t2(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[n2]){let e;a.body=new ReadableStream({async pull(t){try{e||=Bu.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=Bu.toWeb(r);return new t2(t,a)},r2=Symbol(`getRequestCache`),i2=Symbol(`requestCache`),a2=Symbol(`incomingKey`),o2=Symbol(`urlKey`),hfe=Symbol(`headersKey`),s2=Symbol(`abortControllerKey`),c2={get method(){return this[a2].method||`GET`},get url(){return this[o2]},get headers(){return this[hfe]||=pfe(this[a2])},[Symbol(`getAbortController`)](){return this[r2](),this[s2]},[r2](){return this[s2]||=new AbortController,this[i2]||=mfe(this.method,this[o2],this.headers,this[a2],this[s2])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(c2,e,{get(){return this[r2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(c2,e,{value:function(){return this[r2]()[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[i2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(c2,t2.prototype);var gfe=(e,t)=>{let n=Object.create(c2);n[a2]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof ed)throw new e2(`Absolute URL for :path is not allowed in HTTP/2`);try{n[o2]=new URL(r).href}catch(e){throw new e2(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof ed?e.authority:e.headers.host)||t;if(!i)throw new e2(`Missing host header`);let a;if(e instanceof ed){if(a=e.scheme,!(a===`http`||a===`https`))throw new e2(`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 e2(`Invalid host header`);return n[o2]=o.href,n},l2=Symbol(`responseCache`),u2=Symbol(`getResponseCache`),d2=Symbol(`cache`),f2=global.Response,p2=class e{#e;#t;[u2](){return delete this[d2],this[l2]||=new f2(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[l2];if(e){this.#t=e,this[u2]();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[d2]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[d2];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[u2]().headers}get status(){return this[d2]?.[0]??this[u2]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(p2.prototype,e,{get(){return this[u2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(p2.prototype,e,{value:function(){return this[u2]()[e]()}})}),Object.defineProperty(p2.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[l2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(p2,f2),Object.setPrototypeOf(p2.prototype,f2.prototype);async function _fe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function m2(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function vfe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:m2(e.getReader(),t)}var h2=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},yfe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=zu);var g2=Symbol(`outgoingEnded`),_2=Symbol(`incomingDraining`),bfe=500,xfe=64*1024*1024,v2=e=>{let t=e;if(e.destroyed||t[_2])return;if(t[_2]=!0,e instanceof ed){try{e.stream?.close?.($ee.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,bfe);a.unref?.();let o=e=>{n+=e.length,n>xfe&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},Sfe=()=>new Response(null,{status:400}),y2=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),b2=(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))},x2=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},S2=async(e,t)=>{let[n,r,i]=e[d2],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=h2(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=h2(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())):(x2(t),await vfe(r,t)?.catch(e=>b2(e,t))),t[g2]?.()},Cfe=e=>typeof e.then==`function`,wfe=async(e,t,n={})=>{if(Cfe(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(y2);if(d2 in e)return S2(e,t);let r=h2(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 _fe(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&&x2(t),await m2(n,t,o))}else r[yfe]||(t.writeHead(e.status,r),t.end());t[g2]?.()},C2=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==t2&&(Object.defineProperty(global,`Request`,{value:t2}),Object.defineProperty(global,`Response`,{value:p2})),async(r,i)=>{let a,o;try{o=gfe(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[n2]=!0,r.on(`end`,()=>{s=!0}),r instanceof ed&&(i[g2]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{v2(r)})})}),i.on(`finish`,()=>{s||v2(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(()=>{v2(r)})})}),a=e(o,{incoming:r,outgoing:i}),d2 in a)return S2(a,i)}catch(e){if(a)return b2(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:dfe(e)),!a)return}else a=o?y2(e):Sfe()}try{return await wfe(a,i,t)}catch(e){return b2(e,i)}}},Tfe=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
|
|
1218
1218
|
`;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>x1.parse(e)):[x1.parse(a)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(O1);if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(m1)){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>O1(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)m1(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)m1(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;m1(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!Z$.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${Z$.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${Z$.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((_1(e)||b1(e))&&(n=e.id),n===void 0){if(_1(e)||b1(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(_1(e)||b1(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},Efe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Tfe(e),this._requestListener=C2(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 C2(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 w2=`x-ok-connection-id`;function T2(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 E2(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||!Dfe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=za(i.error);throw new y0(v1.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function Dfe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const D2=2e3,O2=2e3,Ofe=[/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 k2(e){return Ofe.some(t=>t.test(e))}function kfe(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 Hl(e)?e:null}catch{return null}}function Afe(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&&Hl(a)?a:null}function jfe(e){let t=[];for(let n of e.split(`
|
|
@@ -2025,6 +2025,6 @@ native-divergence-injected
|
|
|
2025
2025
|
`,`utf-8`),o&&E!==void 0){let r=null;try{V(ie)&&(r=H(ie,`utf-8`))}catch(e){r=null,j7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&ui(r)!==ui(E)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:E.length,candidateBytes:S.length})),we(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=lC(e);if(t.length===0)return;o?.record({event:lS,docName:i,writerId:ZS.id,direction:`b`,site:ge,lostLen:t.reduce((e,t)=>e+t.length,0),digest:ma(t.join(`
|
|
2026
2026
|
`))})}catch(e){j7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},OH)}catch(e){throw t.recordStoreFailure(i,P7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(Hre(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let ae=`${ie}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===i){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${i}`);throw e.code=`ENOSPC`,e}await $o(ae,S,`utf-8`),await _s(ae,ie),ZH(ie,$H(S)),t.clearStoreFailure(i),qre();try{d?.(i,f,S,E??null)}catch(e){j7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{is(ae)}catch{}throw C.delete(i),t.recordStoreFailure(i,P7(e)),j7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}j7.info({filePath:ie,bytes:S.length},`[persistence] Wrote ${ie} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){j7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Ko({"persistence.bytes":S.length}),ue()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),Oe?.record((Date.now()-o)/1e3)})}function Me({document:e,documentName:n,lastTransactionOrigin:r}){oe.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function Ne(e=`within-branch`){return ae?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,ae):(ae=(async()=>{let n=e;for(;;){let e=[...oe.entries()];if(oe.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await je({document:r.document,documentName:n,lastTransactionOrigin:r.lastTransactionOrigin})}catch(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`,r=``;try{r=String(e?.message??``)}catch{r=``}let i=ma(r),a;try{a=aSe(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:ma(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}Uie(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),j7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,oe.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{ae=null}),ae)}let Fe={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),dC(i))return;if(fC(i)){Sxe(n,i,h);return}if(pC(i)){OK(n,i,_);return}if(mC(i)){$xe(n,i,v);return}Ae();let o=Date.now();return Qo(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{j7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=Oj(i,r);if(!V(a))return;let o=a;try{let e=U(a);if(!kj(e,r)){j7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(Zs(e)===`ELOOP`){j7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=uu(o).size;if(s>524288)throw j7.warn({documentName:i,fileSize:s,limit:cn},`[persistence] Document exceeds open byte limit; refusing to load`),new rSe(i,s);let c=H(a,`utf-8`),l=n.getXmlFragment(`default`);j7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{kH(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(Pe,crypto.randomUUID())},OH),j7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{j7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):j7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{De?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!dC(n)){if(fC(n)){let t=await wxe(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){j7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(pC(n)){if(await jK(e,n,r,_)===`persisted`){let e=M7(r,c);if(e&&e.id!==$S.id&&!e.id.startsWith(`agent-`)){let t=bK(n);t&&(yF(t.docKey,e.id,e.name,e.id,t.subject),ue())}}return}if(mC(n)){await eSe(e,n,r,v);return}if(t.isBatchInProgress()){Me({document:e,documentName:n,lastTransactionOrigin:r});return}return je({document:e,documentName:n,lastTransactionOrigin:r})}}};async function Ie(){re&&await re}async function Le(){if(re){await re;return}CF()!==0&&(re=se().finally(()=>{re=null,ie&&(ie=!1,ue())}),await re)}function Re(){return{branchDeferred:oe.size,quiescenceDeferred:C.size}}async function ze(e,n){if(!_C(n)){if(t.isBatchInProgress()){Me({document:e,documentName:n,lastTransactionOrigin:null});return}return je({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:Fe,durabilityState:t,flushDeferredStores:Ne,flushPendingGitCommit:de,flushContributors:Le,waitForPendingCommits:Ie,getQueueDepths:Re,forceStore:ze,configPersistenceCtx:h,managedArtifactCtx:_}}const I7=F(`persistence-staleness`);var L7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function sSe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,{getBase:i,isBatchActive:a,peekInFlight:o}=e,s=e.msSinceLastUserTx??Aw,c=new Map,l=!1,u=null;function d(e){return N7(e)}function f(e){return e===void 0?void 0:ui(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Or(r,n):!0}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),_C(n)||zC(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S,y,b)){c.delete(n);continue}m++;let C=r(),w=s(v,C);if(w!==null&&w<t)continue;let T=c.get(n);if(T&&T.fingerprint===x&&(T.declined||C-T.atMs<t))continue;let E=T?.fingerprint!==x;E&&sie();let ee=!E&&T?T.firstDetectedAtMs:C,te=C-ee,ne=null,re=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(ne=`disk-file-never-loaded`):t===null?ne=`disk-file-missing`:ui(t)!==S&&(ne=`disk-diverged-from-base`)}catch(e){e instanceof L7?(ne=`disk-read-refused`,I7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(ne=`disk-read-failed`,re=!0,I7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(ne!==null){g++,lie(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!re}),I7.warn({docName:n,ageMs:w,staleForMs:te,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:ne},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}I7.warn({docName:n,ageMs:w,staleForMs:te,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!1}),cie(),h++;try{await e.forceStore(v,n)}catch(e){I7.error({err:e,docName:n,staleForMs:te},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let ie=v.getText(`source`).toString(),ae=i(n),oe=d(ie);p(oe,f(ae),ie,ae)&&oe===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!0}),I7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?I7.info(v,`[persistence-staleness] sweep complete`):I7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{I7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function cSe(e){try{let t=Ms({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function R7(e){let t=iN(e),n=z(t,`principal.json`),{name:r,email:i}=await cSe(e);if(V(n)){let e;try{e=JSON.parse(H(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Lu()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?Kh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?Kh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return fu(n,JSON.stringify(s,null,2),`utf-8`),s}eu(t,{recursive:!0});let a=`principal-${Lu()}`,o=a.slice(10,18),s={id:a,display_name:r?Kh(r):`Local User`,display_email:i?Kh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return fu(n,JSON.stringify(s,null,2),`utf-8`),s}var lSe=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};function z7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function uSe(e,t){try{if(hC(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(z7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw kS(),Ko({"auth.reason":`doc-deleted`}),new RZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){qie(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:i}));return}r.add(i);let n=t.recentlyRemovedDocs.get(i);if(n===void 0)throw OS(),Ko({"auth.reason":`rename-redirect`}),new RZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw z7(t,i)?(t.recentlyRemovedDocs.delete(i),OS(),Ko({"auth.reason":`rename-redirect`}),new RZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(kS(),Ko({"auth.reason":`doc-deleted`}),new RZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof RZ)throw t;Kie(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const B7=F(`removed-docs-journal`);function V7(e){return L(iN(e),`removed-docs.json`)}function dSe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.docName!=`string`||t.docName.length===0||typeof t.addedAt!=`number`?!1:t.kind===`deleted`?!0:t.kind===`renamed`?typeof t.newDocName==`string`:!1}function fSe(e){let t=V7(e);if(!V(t))return[];try{let e=JSON.parse(H(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return B7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!dSe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return B7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function H7(e,t){let n=V7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};ls(I(n),{recursive:!0});let i=`${n}.tmp`;vs(i,JSON.stringify(r),`utf-8`),ns(i,n)}const U7=F(`server-observers`);function W7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(dC(r)||fC(r)||mC(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=HT({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,deferGuardEnabled:e.deferGuardEnabled,lossDetectorEnabled:e.lossDetectorEnabled,fixedPointBackstopEnabled:e.fixedPointBackstopEnabled,preDrainEnabled:e.preDrainEnabled,lossRing:e.lossRing});return t.set(r,n),!0}catch(e){return U7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),TS(`a`),TS(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(U7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){U7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const G7=`state.json`;function K7(e){return e.lockDir,V(e.shadowRepoDir)?`adopt`:`fresh`}function q7(e){return z(e,G7)}function pSe(e,t){return e===t||e===0&&t===1}var J7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function mSe(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function Y7(e){let t=q7(e);if(!V(t))return{status:`absent`};let n;try{n=H(t,`utf-8`)}catch(e){throw new J7({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new J7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!mSe(r))throw new J7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function X7(e,t){let n=q7(e);eu(I(n),{recursive:!0}),fu(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function Z7(e){let t=F(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Us,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=q7(e.lockDir),s=Y7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!pSe(c.stateSchemaVersion,n))throw new J7({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return X7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(K7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return X7(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return X7(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}function hSe(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function gSe(e){return e.git?.toString()??e.message??``}function Q7(e,t){return t.some(t=>t.test(e))}const _Se={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},vSe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],$7=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],ySe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],bSe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],xSe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],SSe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],CSe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],wSe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],TSe=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],ESe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],DSe=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],OSe=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],kSe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function e9(e){let t=ASe(e);return{...t,userFacingCode:hSe(t.class,t.subclass)}}function ASe(e){let t=e instanceof Error?e:Error(String(e)),n=gSe(t),r=`${t.message}\n${n}`.toLowerCase();if(Q7(r,wSe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(Q7(r,TSe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(Q7(r,ESe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let a=i(t);return a.kind===`auth`?a.subclass===`403`&&Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:a.subclass,retryable:!1,message:_Se[a.subclass],rawStderr:n}:Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Q7(r,vSe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Q7(r,ySe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Q7(r,bSe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Q7(r,xSe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Q7(r,CSe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Q7(r,SSe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Q7(r,kSe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Q7(r,OSe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Q7(r,DSe)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function jSe(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const t9=F(`github-permissions`);function MSe(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function NSe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function PSe(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function FSe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return t9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=PSe(t);return n===null?(t9.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return t9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function ISe(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){t9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function LSe(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,detectGh:a=()=>({available:!1}),tokenStore:o,_fetchFn:s=fetch,_timeoutMs:c=5e3}=e,{token:l,source:u}=await ISe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(t9.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(t9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${MSe(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;t9.info({host:r,tokenSource:u,tokenLen:l===void 0?0:l.length},`[permissions] probe starting`);let f=new AbortController,p=setTimeout(()=>f.abort(),c);try{let e=await s(d,{signal:f.signal,headers:NSe(l)}),t=await FSe(e,l!==void 0);return t9.info({host:r,tokenSource:u,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return f.signal.aborted?(t9.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(t9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function RSe(e){let t=performance.now(),n=await LSe(e);return HSe(n,performance.now()-t),n}function zSe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let n9=null;function BSe(){return n9||=xs().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),n9}let r9=null;function VSe(){return r9||=xs().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),r9}function HSe(e,t){let n=zSe(e);BSe().add(1,n),VSe().record(t,{outcome:n.outcome})}function i9(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}function USe(e,t){return t===`anonymous`?Math.max(180,e):e}const a9=F(`sync-engine`),o9=/^[0-9a-f]{40}$/i,WSe=Ju(Pl);function GSe(e){let{exitCode:t,stderr:n}=e,r=n??``;return t===128||/^fatal:/m.test(r)&&/not possible to fast-forward/i.test(r)?`divergence`:/^error:/m.test(r)&&/would be overwritten by merge/i.test(r)?`overlay-overlap`:`unknown`}function KSe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function s9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function c9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function l9(e){let t=nd(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`?t.repository.readRef(n.ref).kind===`absent`:!1}function qSe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const u9=12e4;var JSe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;mode;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.detectGh=e.detectGh,this.ghTokenSource=jSe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??RSe,this.statePath=z(iN(this.projectDir),`sync-state.json`),this.conflictStore=new HZ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return GR(this.projectDir)}gitHandle(e){return Fs(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){a9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),a9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){a9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=ld(this.projectDir),n=t?L(t,`MERGE_HEAD`):null,r=n!==null&&V(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){a9.warn({count:i().length},`[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state`);for(let e of i())this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count()}else if(i().length>0&&r)try{let e=this.gitHandle(),t=new Set(await gS(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of i())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&a9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){a9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){a9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(i().length>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),a9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=this.conflictStore.list().filter(e=>e.variant===`working-tree`);a.length>0&&await this.notifyContentConflictsDetected(a.map(e=>e.file)),this.mode===`follow`&&await this.refreshAuthTier();let o=i9(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=i9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),a9.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,a9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){a9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await qu(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||l9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||l9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){a9.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){a9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await Ns(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,a9.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,a9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?a9.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):a9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(await this.runPushCycle(),await this.runPullCycle())}async pullOnce(){let e=this.mode,t=await this.runOneShotPull();return a9.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||l9(this.projectDir))return this.recordPullOutcome(`refused`);let e=this.mode,t=this.state,n=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,e===`off`?(this.pausedReason=n,this.transitionTo(t)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?KR(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await ZU(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=WR(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,s9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,a9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){a9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=KSe(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.mode===`full`?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,a9.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),a=!0,a9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!s9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,a9.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!V(L(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return a9.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){let e=this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(e.length===0)return;let t=this.conflictCount,n=ld(this.projectDir),r=n?L(n,`MERGE_HEAD`):null;if(r!==null&&V(r))try{let n=this.gitHandle(),r=new Set(await gS(n.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let t of e)r.has(t.file)||this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<t&&a9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){a9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{a9.info({cleared:e.length},`[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts`);for(let t of e)this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count()}this.conflictCount!==t&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&(a9.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e])),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{a9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??c9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{a9.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){let e=this.syncGhTokenHost();if(this.ghTokenSource.get(e)!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(e))?.token)return`authenticated`}catch(e){a9.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?USe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=qSe(this.consecutiveFailures);return c9(e>0?e/1e3:this.currentPullIntervalSeconds())}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(l9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,a9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.mode!==`full`){let n=await this.doPullCycleB1(e,t);return this.scheduleSaveState(),n}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return`refused`;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}return this.scheduleSaveState(),`succeeded`}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),a9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await gS(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await gS(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=new Map;for(let e of this.conflictStore.list())e.variant===`working-tree`&&i.set(e.file,e);let a;try{a=await this.planOverlapReconciliation(e,t,n,r,i)}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){a9.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...r])}catch(e){return a9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return a9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(a9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(e9(Error(`git merge --ff-only timed out after ${u9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),a9.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return a9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=!0;for(let e of a.upserts)i=this.conflictStore.addConflict(e)&&i;for(let e of a.dissolved)i=this.conflictStore.removeConflict(e)&&i;if(this.conflictCount=this.conflictStore.count(),!i)return a9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(e9(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return a9.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:o},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await WSe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:u9}),{ok:!0}}catch(e){let t=e,n=t.killed===!0||t.signal===`SIGTERM`,r=typeof t.code==`number`?t.code:null,i=typeof t.stderr==`string`?t.stderr:e instanceof Error?e.message:String(e);return{ok:!1,refusal:GSe({exitCode:r,stderr:i}),stderr:i,exitCode:r,timedOut:n}}}async planOverlapReconciliation(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[];for(let p of r){let r=i.get(p),m=r!==void 0;if(!V(L(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),a9.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=H(L(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&a9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=$i(v?await this.gitBlobContent(e,v):``,g,_);if(y.clean){a.push({path:p,bytes:Buffer.from(y.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let b=await this.gitBlobSha(e,`origin/${t}:${p}`);if(b===void 0){a9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({file:p,detectedAt:r?.detectedAt??new Date().toISOString(),variant:`working-tree`,theirsSha:b,baseSha:v}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){for(let{path:t,bytes:n}of e){let e=L(this.projectDir,t);lV(e,this.projectDir),vs(e,n)}for(let e of t){let t=L(this.projectDir,e);lV(t,this.projectDir);try{is(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=L(this.projectDir,e),n=Ej(R(this.contentDir,t));return!n.startsWith(`..`)&&yC(n)&&!this.contentFilter.isExcluded(n)}async gitBlobSha(e,t){try{return(await e.git.revparse([t])).trim()}catch{return}}classifyRefReadFailure(e){let t=e instanceof Error?e.message:String(e);return/does not exist in|exists on disk, but not in/i.test(t)?`absent`:`error`}async gitBlobContent(e,t){return e.git.raw([`cat-file`,`blob`,t])}async countStandingOverlay(e){try{return(await gS(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(!this.pushInFlight&&this.mode===`full`&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(l9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=L(yu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await Ns(async()=>{let e=this.gitHandle(n);if(l9(this.projectDir)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(e9(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i);if(t.length>0)for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));await this.removePathsFromIndex(e,s);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){a9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}a9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[],d=[];try{let n=await gS(e.git,[`diff-tree`,`--name-only`,`-r`,i,c]);if(n.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n){u.push(t);let n=e.get(t)??Ej(R(this.contentDir,L(this.projectDir,t)));n&&!n.startsWith(`..`)&&d.push(n)}}}catch{u=t.map(e=>e.projectRelPath).concat(s),d=t.map(e=>e.contentRelPath)}let f=this.buildCommitMessage(d),p=await ZU(this.projectDir),m=p===null;this.identityUnresolved!==m&&(this.identityUnresolved=m,this.cc1Broadcaster?.signal(`sync-status`));let h=p?.name??`OpenKnowledge`,g=p?.email??`sync@open-knowledge.local`;Ls(e,{GIT_AUTHOR_NAME:h,GIT_AUTHOR_EMAIL:g,GIT_COMMITTER_NAME:h,GIT_COMMITTER_EMAIL:g});let _=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,f])).trim();if(!_||!o9.test(_)){a9.warn({raw:_},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,_,i]),await this.resetRealIndexForPaths(u);let v=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),v=!0}catch{}v?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=_}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=e9(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){a9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}a9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{du(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=L(yu(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await a.git.raw([`add`,`--`,...t])}let i=new Set(n.map(e=>e.projectRelPath)),o=[...r].filter(e=>!i.has(e));await this.removePathsFromIndex(a,o);let s=(await a.git.raw([`write-tree`])).trim();if(s===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let c=[];try{c=await gS(a.git,[`diff-tree`,`--name-only`,`-r`,t,s])}catch{c=n.map(e=>e.projectRelPath).concat(o)}let l=await ZU(this.projectDir),u=l?.name??`OpenKnowledge`,d=l?.email??`sync@open-knowledge.local`;Ls(a,{GIT_AUTHOR_NAME:u,GIT_AUTHOR_EMAIL:d,GIT_COMMITTER_NAME:u,GIT_COMMITTER_EMAIL:d});let f=(await a.git.raw([`commit-tree`,s,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!f||!o9.test(f)?(a9.warn({raw:f},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,f,t]),await this.resetRealIndexForPaths(c,e),f)}finally{try{du(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await gS(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return a9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await gS(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return a9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return a9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){a9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=au(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=L(n,i.name);if(i.isDirectory()){let e=Ej(R(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=Ej(R(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Ej(R(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return V(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await gS(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=L(this.projectDir,e),r=Ej(R(this.contentDir,t));!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&n.add(e)}}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await gS(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){a9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=L(this.projectDir,e),i=Ej(R(this.contentDir,t));!i.startsWith(`..`)&&yC(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),a9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){a9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),a9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=ld(this.projectDir);t=n===null||!V(L(n,`MERGE_HEAD`))}catch(e){a9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),a9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),a9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict resolved callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),a9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,a9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};fu(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){a9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(V(this.statePath))try{let e=H(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){a9.warn({err:e},`[sync] failed to load sync state`)}}};Vo();const YSe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function XSe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(dC(e)||fC(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&YSe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Jo(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Ho.with(Bo.extract(Ho.active(),r),e)}else e()}catch(e){F(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let d9=!1;function f9(){if(d9)return;let e=nte;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){d9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),d9=!0}catch(e){F(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const ZSe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function QSe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(b8).join(` `)} auth git-credential`]}function $Se(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Ll(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],ZF({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(`
|
|
2027
2027
|
`)){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(!kj(a,t))continue;let s=uU(a,t);i.has(s)||V(a)&&i.set(s,o)}return i}function p9(e){f9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=F(`server`),b=new l7,x=()=>b.getActiveBranch(),S=e=>b.getReconciledBase(e),C=(e,t)=>b.setReconciledBase(e,t),w=e=>b.deleteReconciledBase(e),T=e=>b.switchReconciledBaseScope(e),E=e=>b.setBatchInProgress(e),ee=()=>b.isBatchInProgress();function te(){let e=qo({absPath:Xo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=jo(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function ne(){let e=qo({absPath:Xo(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=so(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let r=qo({absPath:Xo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:Ya(r.value.autoSync?.default)??`off`,source:`committed-default`}}function re(){let e=qo({absPath:Xo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?vr(e):hr}function ie(){return qo({absPath:Xo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ae(){return KF(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function oe(){let e=qo({absPath:Xo(`project-local`,n,l),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function se(e){return`${IF(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function ce(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=ne();t=n.mode,ht?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=ae();Ne.applyConfig({enabled:n.enabled,providerFingerprint:se(n)}),e===`__config__/project`&&Te?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}bs();let le=Lu(),ue=iN(n),de=new Bd({localDir:ue,log:F(`acp-registry`)}),fe=new Nd(ue,F(`acp-permissions`));if(Js(ue,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{Z7({lockDir:ue,shadowRepoDir:ud(n)})}catch(e){throw zs(ue),e}let pe=wi(),me=(e,t)=>pe.resolveEmbed(e,t),he=(e,n)=>{let r=pe.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=z(t,r);if(!Dj(i,z(t)))return null;try{let e=uu(i);return e.isFile()?e.size:null}catch{return null}},ge,_e,ve,ye,be,xe,Se,Ce,we,Te=null,Ee=null,Oe=null,ke=null,Ae=null,je=null,Me=ae(),Ne=new uce({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return Xse({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:L(iN(n),`embeddings`),enabled:Me.enabled,providerFingerprint:se(Me)}),Pe=null,Fe=new Set,Ie=!1,Le=[],Re,ze,Be,Ve=new Promise((e,t)=>{ze=e,Be=t});function He(e){Te?.signal(e)}let Ue=null,We=!1,Ge=()=>{try{H7(n,Ke.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Ke=new lSe(void 0,{onEviction:()=>Wie(),onSizeChange:e=>Gie(e),onMutate:()=>{!We||Ue!==null||(Ue=setTimeout(()=>{Ue=null,Ge()},2e3))}});for(let[e,r]of fSe(n))hC(e)||DZ(e)&&([`.md`,`.mdx`].some(n=>{let r=z(t,`${e}${n}`);return Dj(r,z(t))&&V(r)})||Ke.restore(e,r));We=!0;let qe={current:null},Je=(e,t)=>{hC(e)||Ke.setRenamed(e,t)},Ye=e=>{if(!hC(e)){if(Ke.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ke.setDeleted(e),qe.current?.deleted(e)}},Xe=e=>{hC(e)||Ke.delete(e)};try{ge=hL({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:oV(t),rescanInPlaceSkillDirs:()=>oV(t),onAfterRebuild:()=>{_e.refreshContentScope().catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),NU(pt).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?F(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):F(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),_e=new DH({projectDir:n,contentDir:t,contentFilter:ge,getGlobalSkillRoots:()=>SK(be.managedArtifactCtx),signalChannel:He}),ve={current:d},ye=o?Xxe({getShadow:()=>ve.current??null,getCurrentBranch:()=>mt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:ld(n)??void 0,isWriterLive:e=>{if(!ke&&!Ce)return F(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(ke?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Ce?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,be=F7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:ve,ephemeral:v,contentRoot:f,derivedDocumentIndex:_e,configHomedirOverride:l,getCurrentBranch:()=>mt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,getPrincipal:()=>Pe,onAgentCommit:()=>Te?.signal(`session-activity`),onFlushCommit:()=>ye?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Te?.emitDiskAck(e,t),!hC(e)&&eM(r,n)&&(Ae?.(),He(`files`))},onConfigRejected:(e,t)=>Te?.emitConfigValidationRejected(e,t),onConfigPersisted:ce,isRecentlyRemoved:e=>Ke.has(e),mdManager:e.mdManager,getLossRing:()=>xe,durabilityState:b}),Se=new fxe({quiet:r,debounce:i,maxDebounce:a,extensions:[be.extension]});let p=Se;Le.push(bT(()=>p.documents.size),xT(()=>be.getQueueDepths()),CT(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),TT(),v||(je=sSe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>be.forceStore(e,t),getBase:e=>b.getReconciledBase(e),isBatchActive:()=>b.isBatchInProgress(),peekInFlight:e=>b.peekInFlightFlush(e),readDiskBytes:e=>{let n=Oj(e,t),r,i;try{r=U(n),i=uu(r).size}catch(t){let n=Zs(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new L7(`symlink cycle at content path: ${e}`):t}if(!kj(r,t))throw new L7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new L7(`document exceeds the open byte limit: ${e}`);try{return H(r,`utf-8`)}catch(e){if(Zs(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=Se.shouldUnloadDocument.bind(Se);Se.shouldUnloadDocument=e=>{if(Fe.has(e)||Ie&&g(e))return!0;let t=e.name;return hC(t)||S(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Re=async e=>{Fe.add(e);try{await Se.unloadDocument(e)}finally{Fe.delete(e)}},Te=new vC(Se),Oe=new LD(Se),ke=new RD(Se),Ce=new aE(Se);let C=Ce;Le.push(wT(()=>({active:C.liveSessionCount,limit:C.sessionLimit})));let w=p7({derivedDocumentIndex:_e,onDocumentSettled:e=>qe.current?.changed(e)});Se.configuration.extensions.push(w),Se.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=zZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==le)throw new RZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${le}`);let i=n?.expectedBranch,a=x();if(typeof i==`string`&&i.length>0&&i!==a)throw new RZ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(Pe&&n.principalId===Pe.id?o.principalId=Pe.id:Pe?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Pe.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),Se.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!fC(t.documentName)&&!pC(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!mj(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&&bj(a,e.remotePublicHost);if(!hj(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=z(t);function E(e){if(!DZ(e))return null;let t=z(T,DC(e));return Dj(t,T)?t:null}Se.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await uSe(e.documentName,{recentlyRemovedDocs:Ke,resolveFilePath:E,fileExists:V})}}),Se.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=zZ(e.token);Oxe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Se.documents.get(e)})}}),Se.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new D5(e.update);if(t.readVarString(),t.readVarUint()===R5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${cr} rejected — server-only channel`)}});let ee=kZ({hocuspocus:Se,durabilityState:b,remotePublicHost:e.remotePublicHost,sessionManager:Ce,commentDocHooksRef:qe,contentDir:t,contentFilter:ge,serverInstanceId:le,getFileIndex:()=>pt?pt.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>pt?pt.getAllFilesIndex():new Map,getFileIndexGeneration:()=>pt?.getFileIndexGeneration()??0,mutateFileIndex:e=>pt?.mutateFileIndex(e),getFolderIndex:()=>pt?pt.getFolderIndex():new Map,getAliasMap:()=>pt?pt.getAliasMap():new Map,getFolderAliasIndex:()=>pt?pt.getFolderAliasIndex():new Map,rescanFiles:()=>pt?.rescanFromDisk(),enableTestRoutes:u,shadowRef:ve,flushGitCommit:()=>be.flushPendingGitCommit(),flushContributors:()=>be.flushContributors(),getCurrentBranch:()=>mt?.getLastKnownBranch()??null,getDiskAckSVs:()=>Te?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:_e,signalChannel:He,agentFocusBroadcaster:Oe,agentPresenceBroadcaster:ke,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ht,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:me,getBridgeLossReporter:()=>we,getPrincipal:()=>Pe,acpRegistry:de,loadAcpCustomAgents:()=>Vd(ue,F(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Re,ready:Ve,recentlyRemovedDocs:Ke,serializeDoc:nt,evictManagedArtifactLkg:e=>{be.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ne,getSemanticSimilarityFloor:()=>ae().similarityFloor,getLinterBaseConfig:()=>re(),getLinksValidationSetting:()=>ie(),getLinkPreviewsEnabled:oe,embeddingsSecretsFile:UF(l),readSemanticProviderConfig:ae,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{Ae=e}});Se.configuration.extensions.push(ee);let ne=qo({absPath:Xo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),se=ne.value.bridge.deferGuard.enabled,fe=ne.value.bridge.fixedPoint.enabled,pe=ne.value.bridge.preDrain.enabled;xe=ne.value.lossCapture.enabled?new Nre({projectDir:n,maxBytes:ne.value.lossCapture.maxBytes}):void 0,ne.value.bridge.lossDetector.enabled&&(we=wae({shadow:()=>ve.current,ring:xe,getBranch:()=>mt?.getLastKnownBranch()??`main`,contentRoot:f??``}),Ce.attachBridgeLossReporter(we)),Se.configuration.extensions.push(W7({mdManager:Wo,schema:Uo,shadowRef:ve,contentRoot:f,getCurrentBranch:()=>mt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,deferGuardEnabled:se,lossDetectorEnabled:ne.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:fe,preDrainEnabled:pe,lossRing:xe})),Se.configuration.extensions.push(XSe()),Se.configuration.extensions.push(Dxe({getSyncEngine:()=>ht,projectDir:n,contentDir:t}))}catch(e){for(let e of Le.splice(0))e();throw je?.dispose(),je=null,zs(ue),e}let Ze=null,Qe=new Map,$e=[];function tt(e,t){let n=z(e,`rescue`),r=z(n,DC(t));return Dj(r,n)?r:null}function nt(e){let t=Se.documents.get(e);return t?BH(t):null}let rt=(e,t)=>LH(b,Se,e,t,me,he,we);function it(e){if(!RC(e)||ht?.getConflicts().some(r=>c7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let at=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Se.documents){if(hC(n))continue;let r=Se.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{kH(r,i,me,n)},OH)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},ot=null,st=e=>{e&&(ot===null&&(ot=new Set,setImmediate(()=>{let e=ot;if(ot=null,e)try{for(let t of e)at(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),ot.add(e))};function ct(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return KH(e)}}async function lt(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await _e.recordDiskUpsert(e.docName,e.content),He(`files`),Xe(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=Se.documents.get(t);if(!r){await _e.recordDiskUpsert(t,n);return}let i=S(t)??``,a=nt(t)??i,o=NH({docName:t,base:i,ours:a,theirs:n}),s=$H(i).slice(0,6),c=$H(a).slice(0,6),l=$H(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:it(r),await _e.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{rt(t,o.newContent),C(t,o.newContent),_S(),it(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),C(t,n),it(r)}e&&await _e.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{rt(t,o.newContent),C(t,n),_S(),it(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),C(t,n),it(r)}e&&await _e.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{rt(t,o.newContent),C(t,o.newContent),_S(),vS(),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),C(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await _e.recordDiskUpsert(t,n);break}case`refused`:{vS();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Se.documents.get(t);if(!n){await _e.recordDiskDelete(t),He(`files`),Ye(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=S(t)??``,i=nt(t)??``,a=i!==r;if(a&&ve.current){let e=ve.current,n=mt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{iC(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{bS(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),w(t),await _e.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Se.closeConnections(t),await Re(n),He(`files`),Ye(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=Se.documents.get(t);if(w(t),C(n,r),await _e.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),He(`files`),Je(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=Se.documents.get(t);if(!n)return;let r=nt(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):C(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:pe.add(e.relativePath),He(`files`),st(zl(e.relativePath));break;case`asset-delete`:pe.remove(e.relativePath),He(`files`),st(zl(e.relativePath));break;case`folder-create`:case`folder-delete`:He(`files`);break;case`file-create`:case`file-update`:case`file-delete`:He(`files`);break;default:KH(e)}}catch(t){let n=ct(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let ut=[];async function dt(e){if(ee()){ut.push(e);return}await lt(e)}async function ft(){let e=ut.splice(0,ut.length);for(let t of e)await lt(t)}let pt=null,mt=null,ht=null,gt=null;async function _t(e){if(Se.documents.size===0)return;let t=!1,n=new Promise(e=>{Se.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Se.documents.keys());Se.closeConnections(),Se.flushPendingStores();for(let e of Se.documents.values())e.getConnectionsCount()===0&&Se.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(Se.documents.keys()),i=[],o=[];if(ve.current){for(let e of n)if(!hC(e))try{let t=nt(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=tt(ve.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:ve.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}eu(I(n),{recursive:!0}),fu(n,t,`utf-8`),bS(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function vt(){return gt||(gt=(async()=>{let e=Date.now(),t=[];Ie=!0;for(let e of Le.splice(0))e();try{await je?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}je=null;try{Ys(ue)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Ue!==null&&(clearTimeout(Ue),Ue=null),We)try{H7(n,Ke.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([Ve.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=Se.documents.size;ye?.destroy();try{try{try{Ee&&=(clearTimeout(Ee),null),mt&&=(await mt.unsubscribe(),null),pt&&=(await pt.unsubscribe(),null);for(let{docName:e,cleanup:t}of $e)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}$e.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Te?.destroy(),ke?.destroy(),Ze&&=(await Ze.disconnect(),null);for(let[e,t]of Qe)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Qe.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Ce.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await bw()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await _t(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}_e.close();let e;try{await Promise.race([(async()=>{await be.flushPendingGitCommit(),await be.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ht&&=(await ht.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ve.current){try{let e=(await Ms({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&fu(z(ve.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{aae(ve.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{zs(ue,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await ys()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),gt)}let yt=[];async function bt(){try{Pe=await R7(n),y.info({principalId:Pe.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ve.current)try{ve.current=await WS(n),y.info({gitDir:ve.current.gitDir},`[server] history repo initialized at ${ve.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),yt.push(`shadow-repo`)}if(ve.current){let e=null;try{e=fq(ve.current.gitDir),Fq(ve.current.gitDir,e),_q(ve.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([Iq(ve.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ye?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ve.current)try{await HS(ve.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ve.current=await WS(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),ve.current=void 0,yt.includes(`shadow-repo`)||yt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(ve.current)try{let e=z(ve.current.gitDir,`last-known-head`),t=null;try{t=H(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Ms({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Ms({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await tC(ve.current,f??``,t,r,e),yS()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{fu(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=QK(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),yt.push(`managed-rename-recovery`)}try{let e=EV(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),yt.push(`upload-tempfile-sweep`)}try{Ze=await Se.openDirectConnection(cr),Te?.emitServerInfo(le,x())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),yt.push(`cc1-push`)}let r=v?[]:De;for(let e of r)try{let t=await Se.openDirectConnection(e);Qe.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),yt.push(`config-doc:${e}`)}let i=new Map([[xi,Xo(`project`,n)],[D,Xo(`project-local`,n)],[bn,Xo(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await Z5(t,t=>{let n=Se.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=s7(n??null,e,t,be.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),ce(e)});$e.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),yt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=DK(e,be.managedArtifactCtx);if(!n)return;let r=MK(Se.documents.get(n)??null,n,t,be.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),He(`files`),Rn(n)&&_e.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=DK(e,be.managedArtifactCtx);He(`files`),t&&Rn(t)&&_e.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=SK(be.managedArtifactCtx),r=await T7(n,e,void 0,t);$e.push({docName:`__skill-files__`,cleanup:r}),y.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),yt.push(`managed-artifact-watcher:skills`)}try{let e=z(yK(be.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await Z5(e,()=>{He(`files`)});$e.push({docName:`__skill-state__`,cleanup:t}),y.info({path:e},`[skill-state-watcher] started`)}catch(e){y.warn({err:e},`[skill-state-watcher] failed to start`),yt.push(`skill-state-watcher`)}try{let t=new Set([``]);try{for(let e of lP(n).templates)t.add(e.source_folder)}catch(e){y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?z(n,e,`.ok`,`templates`):z(n,`.ok`,`templates`)),i=await T7(r,e,Qxe);$e.push({docName:`__template-files__`,cleanup:i}),y.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),yt.push(`managed-artifact-watcher:templates`)}}try{let e=z(t,`.okignore`),r=z(n,`.gitignore`),i=null;try{let e=Ll(`git`,[`rev-parse`,`--git-common-dir`],ZF({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=L(z(n,e.stdout.trim()),`info`,`exclude`);V(I(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await vxe(a,(t,r)=>{(async()=>{if(t===e)try{let e=s7(Se.documents.get(`__config__/okignore`)??null,et,r,be.configPersistenceCtx);o.info({docName:et,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 ge.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:R(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Te?.signal(`files`);else{let e=R(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Te?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:R(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&($e.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),yt.push(`ignore-files-watcher`)}let a=f7(n).branch??`main`;T(a);let o=_e.beginStartup(a),s=!1,c=performance.now();try{await Qo(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&&yt.push(`backlink-index`);let i=0;for(let t of e)hC(t)||Ke.peek(t)?.kind!==`renamed`&&(Ke.setDeleted(t),i++);i>0&&y.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,u=ge?oV(t):new Set,d=e=>{e.some(e=>c.test(R(t,e).split(B).join(`/`)))&&(Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{Ee=null;try{UJ(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),Te?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=oV(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,ge.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),Te?.signal(`files`)):y.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>y.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){y.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};pt=await Qo(`ok.boot.seed-walk`,void 0,async()=>MU(t,dt,ge,{onRawBatch:d})),UJ(n,t).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=l??gu();UJ(e,e,rV(e)).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] global copy re-sync failed`))}fH(`seedWalkMs`,Math.round(performance.now()-a));{let e=z(t),n=0;for(let[t]of Ke.entries()){if(!DZ(t))continue;let r=z(e,`${t}${EC(t)}`);Dj(r,e)&&V(r)&&(Ke.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await _e.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&yt.push(`tag-index`);let p=0;try{_===void 0?await MZ({contentDir:t,contentFilter:ge,basenameIndex:pe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):jZ({contentDir:t,basenameIndex:pe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(y.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),yt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),yt.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),yt.push(`file-watcher`),!s){let e=await _e.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&yt.push(`tag-index`)}}finally{fH(`indexesMs`,Math.round(performance.now()-c)),pt&&pH(`fileCount`,pt.getFileIndex().size)}try{mt=await Nxe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),Vre(),Se.flushPendingStores(),await be.flushPendingGitCommit(),E(!0),ve.current){let e=x(),t=f7(n).branch??e,r=[];for(let[e,t]of Se.documents){if(hC(e))continue;let n=null;if(t.transact(()=>{n=nt(e)},ZSe),n===null)continue;let i=S(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await hae(ve.current,e,$S.id,r,t);n&&(Wre(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=ut.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(E(!1),await ft(),e.headMoved&&e.newHead){let r=$Se(n,z(t),e.oldHead,e.newHead);if(r.size>0){Cse(r.keys());for(let[e,t]of r)yF(e,ste(t.email),t.name,t.email,Cd(e));await be.flushContributors()}}if(await be.flushDeferredStores(`within-branch`),ht!==null)try{await ht.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Ure(),ut.splice(0,ut.length);let n=!1,r;try{T(i),r=await _e.beginBranchSwitch(i),ge.rebuildDirCount();try{let e=0;pe.clear(),await MZ({contentDir:t,contentFilter:ge,basenameIndex:pe,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),yt.includes(`basename-index-partial`)||yt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of Se.documents)if(!hC(e))try{let r=Oj(e,t);if(!V(r)){let t=S(e)??``,r=nt(e)??``;if(r!==t&&ve.current){let t=ve.current;queueMicrotask(()=>{iC(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{bS(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=H(r,`utf-8`);rt(e,a),C(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:Se.documents.size},`[branch-switch] loaded branch ${i} (${Se.documents.size} docs)`);try{await _e.settleBranchFromDisk(r)}catch(e){_e.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(ve.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Se.documents)if(!hC(t))try{let n=await _ae(ve.current,i,$S.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=S(t);if(!r)continue;let a=NH({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:rt(t,a.newContent),C(t,a.newContent),e++;break;case`conflicts`:rt(t,a.newContent),C(t,a.newContent),vS(),e++;{let e=Se.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&ve.current)try{let t=HS(ve.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await RS(ve.current).withMutator(async()=>{for(let e of n.split(`
|
|
2028
|
-
`))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}E(!1),await be.flushDeferredStores(`discard-stale`),n=!0,Te?.emitBranchSwitched(i)}finally{_e.abortBranchSwitch(r),n||(E(!1),await be.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ve.current&&r>0){let t=f??`.`;try{let n=await tC(ve.current,t,e.oldHead,e.newHead,i);yS(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),yt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Ej(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=xC(e),a=Se.documents.get(i);if(!a)continue;let o=nt(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):C(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=Ej(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Se.documents.get(xC(e));i&&it(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=QSe(m),h=ne();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ht=new JSe({projectDir:n,contentDir:t,contentFilter:ge,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:Te,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{E(e),e||be.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ve.current;n&&await rC(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ve.current;n&&await rC(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await cs({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:xo(t.error),configPath:Xo(`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 ht.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ht=null}He(`files`),_e.announceReadyViews();let g=dH();g!==void 0&&fH(`readyMs`,g)}return bt().then(ze,e=>{_e.close(),Be(e)}),{hocuspocus:Se,durabilityState:b,sessionManager:Ce,cc1Broadcaster:Te,agentFocusBroadcaster:Oe,agentPresenceBroadcaster:ke,maintenanceCoordinator:ye,contentFilter:ge,basenameIndex:pe,serverInstanceId:le,destroy:vt,ready:Ve,degraded:yt,lockDir:ue,get syncEngine(){return ht},resolveEmbed:me,acpRegistry:de,acpPermissions:fe}}function m9(e){return e/1048576}function eCe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:m9(e.rss),heapTotalMb:m9(e.heapTotal),heapUsedMb:m9(e.heapUsed),externalMb:m9(e.external),arrayBuffersMb:m9(e.arrayBuffers)}}}let h9=null,g9=null,_9=null;const v9=1e6;let y9=null,b9=null;Zo(()=>{h9=null,g9=null,_9=null,y9?.disable(),y9=null,b9=null});function tCe(){if(h9)return;let e=xs().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=eCe();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`})}),h9=e}function nCe(){if(!g9){let e=xs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!y9){y9=Hu({resolution:20}),y9.enable();return}e.observe(y9.percentile(50)/v9,{stat:`p50`}),e.observe(y9.percentile(99)/v9,{stat:`p99`}),y9.reset()}),g9=e}if(!_9){let e=xs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=b9;if(b9={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`}))}),_9=e}}const x9=F(`skill-migrate`);function S9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=uO.indexOf(e.host),r=uO.indexOf(t.host);return(n===-1?uO.length:n)-(r===-1?uO.length:r)||e.host.localeCompare(t.host)})}const rCe=S9(be),iCe=S9(Ve);function aCe(e,t){ls(I(t),{recursive:!0});try{ns(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;fs(e,t,{recursive:!0}),ps(e,{recursive:!0,force:!0})}}function oCe(e,t,n){let r;try{r=$l(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return U(e)===t?{kind:`ok-link`}:{kind:`foreign-link`}}catch{return{kind:`foreign-link`}}return r.isDirectory()&&iO(e)?.contentHash===n?{kind:`same-copy`}:{kind:`different`}}function C9(e,t){let n;try{n=U(z(e,`.ok`,`skills`))}catch{n=z(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(z(e,t.dir)).startsWith(n+B)}catch{return!0}}).map(e=>e.name))}async function w9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??rCe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=au(n)}catch{return a}let s=R(t,n).split(B).join(`/`),c=new Set;for(let[e,n]of Object.entries(BJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!nt.test(e)||hz.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=z(n,e);if(!V(L(o,`SKILL.md`)))continue;let s=iO(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=z(t,r);return{host:n,root:r,path:L(i,e),escapes:gB(t,i),state:oCe(L(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`ok-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind!==`different`&&e.state.kind!==`foreign-link`&&V(z(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`different`||d.state.kind===`foreign-link`){a.skipped.push({name:e,reason:`target-occupied:${d.root}`});continue}d.state.kind===`same-copy`?ps(o,{recursive:!0,force:!0}):(d.state.kind===`ok-link`&&ps(d.path,{recursive:!0,force:!0}),aCe(o,d.path));for(let e of u)e===d||e.state.kind!==`ok-link`||(ps(e.path,{recursive:!0,force:!0}),fs(d.path,e.path,{recursive:!0}));await EI(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),x9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),x9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const T9=F(`skill-reconcile`),sCe=hz;function E9(){let e=[];for(let t of Rt){let n=be[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function cCe(e,t){let n=R(e,z(t));return Hl(n)?z(t):n}function D9(e){let{frontmatter:t,body:n}=rr(e),r={};if(t!==``)try{let e=(0,rj.parse)(dr(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function lCe(e,t){let n=D9(e),r=D9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function O9(e,t){let n=k9(e),r=k9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=L(e,o),c=L(t,o);if(i+=uu(s).size+uu(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!lCe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function k9(e,t=``){let n=[];for(let r of au(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...k9(L(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function A9(e,t,n){ps(t,{recursive:!0,force:!0}),ls(e,{recursive:!0}),as(cCe(e,n),t,`dir`)}function j9(e,t){try{let n=ou(e);return z(Hl(n)?n:z(I(e),n))===z(t)}catch{return!1}}function uCe(e,t){try{let n=ou(e),r=Hl(n)?z(n):z(I(e),n);if(!V(r))return!1;let i=R(z(t),r);return i!==``&&(i.startsWith(`..`)||Hl(i))}catch(t){return T9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const dCe=[...Rt,`agents`];function fCe(e){for(let t of dCe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function pCe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=au(n)}catch{return}let i=E9();for(let e of r){let r=fCe(e);if(r===null)continue;let a=z(n,e),o=z(n,r);if(V(o))try{let n=$l(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(L(a,`SKILL.md`))||!V(L(o,`SKILL.md`))||!O9(o,a))continue;for(let{rel:n}of i){let r=z(t,n);if(gB(t,r))continue;let i=L(r,e);j9(i,a)&&A9(r,i,o)}ps(a,{recursive:!0,force:!0}),T9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){T9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function mCe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of E9()){let o=z(t,e);if(!V(o)||gB(t,o))continue;let s;try{s=au(o)}catch(e){T9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(sCe.has(e))continue;let t=L(o,e),s=z(n,e),c=V(s);try{let l=$l(t);if(l.isSymbolicLink()){if(j9(t,s)&&c)continue;if(uCe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(A9(o,t,s),r.healed.push({name:e,editor:i})):(ps(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!nt.test(e)){T9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&O9(t,s)){A9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){T9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=CI(t);for(let[r,a]of i){let i=z(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await TI(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??uB(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){T9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{pCe({projectDir:t,skillsRoot:n})}catch(e){T9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}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=iN(e);M9=new ks({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),lr(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(){lr(null),await M9?.drain(),M9=null,N9=!1}Vo();const hCe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],gCe=[`cache`,`tmp`];function _Ce(e){let t=z(e,wo);if(!(()=>{if(!V(t))return!0;try{return au(t).length===0}catch{return!0}})())return[];let n=[];for(let t of hCe)V(z(e,t))&&n.push(t);for(let t of gCe){let r=z(e,t);try{V(r)&&uu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function vCe(e){let t=cd(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 yCe(e){uH();let t=e.projectDir??e.contentDir,n=nQ({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}`)}Ts.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}bs({localSink:n?.telemetry}),F9(t),tCe(),nCe();let{kind:r,gitdir:i}=vCe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ds(i));let o=JZ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Qo(`ok.boot`,{attributes:a},async()=>bCe(e)),l=()=>{if(s)try{let e=Bo.extract(Ho.active(),{traceparent:s});return Ho.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 bCe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??F(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?_j(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new gj("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-DTx_HmnT.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(!V(z(m,`config.yml`)))throw new X8(V(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);V(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??LG;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof PG||e instanceof FG){let t=e instanceof FG?e.detected:``,n=e instanceof FG?`too_old`:`not_available`;nK(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 ys(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let _=_Ce(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${wo}/.`);let v=p9({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:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee}=v,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ne=e.port??0,re=e.ephemeral?void 0:W8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${te}:${ne}`,log:r}),ie=c();ie.headersTimeout=3e4,ie.requestTimeout=6e4;let ae=e.serveContentAssets===!1?void 0:dM({contentFilter:v.contentFilter,contentSirv:ec(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Ro,assetExtensions:Qa,blocklistExtensions:Ja}),oe=!1;if(e.reactShellDistDir)try{fV(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),oe=!0}catch(e){if(e instanceof dV)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 se=e.reactShellDistDir?ec(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ce=e.ephemeral?null:new ND({contentDir:e.contentDir,localDir:C,globalDir:z(gu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:E,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://${te}:${ne}`,getMcpStdioCommand:()=>MD(e.localOpCliArgs,ne),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ce!==null&&await ce.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let le=K8({httpServer:ie,hocuspocus:y,mcpHttpHandler:re,remoteAccess:i,log:r,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ae,reactShellMiddleware:se,ephemeral:e.ephemeral,acpThreadManager:ce}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},de=null;a!==null&&(de=YZ({httpServer:ie,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ue()})})),await R9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);ie.once(`error`,r),ie.listen(e.port,e.host,()=>{ie.removeListener(`error`,r),t()})})}catch(e){if(oe)try{hV(C)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await b().catch(()=>{}),u(C),e}let fe=dH();fe!==void 0&&fH(`httpListenMs`,fe);let pe=ie.address(),me=typeof pe==`object`&&pe?pe.port:e.port??0;if(ne=me,d(C,me),oe&&pV(C,me),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:C,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let he=!1,ge=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)}};ue=async()=>{if(he)return;he=!0;let e=[],t=async(t,n)=>{try{await ge(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(C),oe&&gV(C)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{de?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ce!==null&&await t(`acpThreads.destroy`,()=>ce.destroy()),await t(`mount.shutdown`,()=>le.shutdown()),re!==void 0&&await t(`mcpHttpHandler.close`,()=>re.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{ie.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ie.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),oe&&await t(`releaseUiLock`,async()=>hV(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ys()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Ts.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await w9({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`),inPlaceNames:C9(e.contentDir,nV(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`store-skill-migration-failed`,error:String(e)},`Store-skill in-place migration failed (non-fatal).`)}try{let e=gu(),t=await w9({projectDir:e,skillsRoot:z(e,`.ok`,`skills`),hostRoots:iCe,inPlaceNames:C9(e,rV(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`global-store-skill-migration-failed`,error:String(e)},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await mCe({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.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:ie,destroy:ue,lockDir:C,contentDir:e.contentDir,port:me,ready:x,degraded:S,didAutoInit:f,serverInstance:v,acpThreadManager:ce}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new HZ(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=ld(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!V(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Ps({baseDir:n,timeout:{block:5e3}});s=new Set(await gS(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=xC(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 xCe=lo;function SCe(e={}){let t=e.home??gu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(L(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(L(r.APPDATA??L(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(Os(),1);const B9=L(gu(),`.ok`,`logs`),CCe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function wCe(){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 TCe(e){eu(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function ECe(e){try{if(uu(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{su(n,r)}catch{}}try{du(`${e}.3`)}catch{}}function DCe(e){try{let t=Date.now(),n=10080*60*1e3,r=au(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=uu(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{du(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{du(L(e,t.name)),a-=t.size}catch{}}}catch{}}function OCe(e){TCe(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);ECe(n),(e._setTimeout??setTimeout)(()=>DCe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:wCe(),name:e.name,redact:{paths:CCe,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 kCe(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 ACe(e){return L(B9,`${e}.${V9()}.log`)}function jCe(){return B9}function MCe(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=V(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=Ju(Pl),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function NCe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],ZF({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function PCe(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(V(n)){if(!uu(n).isDirectory()||V(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=LG()}catch(e){throw e instanceof PG||e instanceof FG?(nK(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof FG?`too_old`:`not_available`,detectedVersion:e instanceof FG?e.detected:``},e instanceof FG?`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 NCe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],ZF({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(!V(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}$/,FCe=Fa.map(e=>e.replace(/\/$/,``));async function ICe(e){let t=ld(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(BCe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Fs(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ns(async()=>{let t=await LCe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await RCe(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=Fs(e,{gitIndexFile:L(yu(),`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 zCe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await ZU(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Ls(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 \`${y}\` 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 FCe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function LCe(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 RCe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function zCe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function BCe(e){return V(L(e,`MERGE_HEAD`))||V(L(e,`rebase-merge`))||V(L(e,`rebase-apply`))||V(L(e,`CHERRY_PICK_HEAD`))||V(L(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function VCe(e,t){let n;try{n=Nl(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(V(n))try{let t=JSON.parse(await wu(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 HCe=[{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 HCe)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 UCe(e){if(!yC(e))throw new $9(e);let t;try{t=U(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!uu(t).isFile())throw new Q9(e);let n=I(t),r=FU(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:xC(R(WCe(e),t).split(B).join(`/`)),canonicalFilePath:t}}let i=zl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:xC(i)}}function WCe(e){return z(e,qo({absPath:Xo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function GCe(e){let t=tu(z(yu(),`ok-ephemeral-`)),n=z(t,`.ok`);return eu(n,{recursive:!0}),fu(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),fu(z(n,`.gitignore`),`local/
|
|
2028
|
+
`))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}E(!1),await be.flushDeferredStores(`discard-stale`),n=!0,Te?.emitBranchSwitched(i)}finally{_e.abortBranchSwitch(r),n||(E(!1),await be.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ve.current&&r>0){let t=f??`.`;try{let n=await tC(ve.current,t,e.oldHead,e.newHead,i);yS(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),yt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Ej(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=xC(e),a=Se.documents.get(i);if(!a)continue;let o=nt(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):C(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=Ej(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Se.documents.get(xC(e));i&&it(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=QSe(m),h=ne();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ht=new JSe({projectDir:n,contentDir:t,contentFilter:ge,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:Te,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{E(e),e||be.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ve.current;n&&await rC(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ve.current;n&&await rC(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await cs({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:xo(t.error),configPath:Xo(`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 ht.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ht=null}He(`files`),_e.announceReadyViews();let g=dH();g!==void 0&&fH(`readyMs`,g)}return bt().then(ze,e=>{_e.close(),Be(e)}),{hocuspocus:Se,durabilityState:b,sessionManager:Ce,cc1Broadcaster:Te,agentFocusBroadcaster:Oe,agentPresenceBroadcaster:ke,maintenanceCoordinator:ye,contentFilter:ge,basenameIndex:pe,serverInstanceId:le,destroy:vt,ready:Ve,degraded:yt,lockDir:ue,get syncEngine(){return ht},resolveEmbed:me,acpRegistry:de,acpPermissions:fe}}function m9(e){return e/1048576}function eCe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:m9(e.rss),heapTotalMb:m9(e.heapTotal),heapUsedMb:m9(e.heapUsed),externalMb:m9(e.external),arrayBuffersMb:m9(e.arrayBuffers)}}}let h9=null,g9=null,_9=null;const v9=1e6;let y9=null,b9=null;Zo(()=>{h9=null,g9=null,_9=null,y9?.disable(),y9=null,b9=null});function tCe(){if(h9)return;let e=xs().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=eCe();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`})}),h9=e}function nCe(){if(!g9){let e=xs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!y9){y9=Hu({resolution:20}),y9.enable();return}e.observe(y9.percentile(50)/v9,{stat:`p50`}),e.observe(y9.percentile(99)/v9,{stat:`p99`}),y9.reset()}),g9=e}if(!_9){let e=xs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=b9;if(b9={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`}))}),_9=e}}const x9=F(`skill-migrate`);function S9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=uO.indexOf(e.host),r=uO.indexOf(t.host);return(n===-1?uO.length:n)-(r===-1?uO.length:r)||e.host.localeCompare(t.host)})}const rCe=S9(be),iCe=S9(Ve);function aCe(e,t){ls(I(t),{recursive:!0});try{ns(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;fs(e,t,{recursive:!0}),ps(e,{recursive:!0,force:!0})}}function oCe(e,t,n){let r;try{r=$l(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return U(e)===t?{kind:`ok-link`}:{kind:`foreign-link`}}catch{return{kind:`foreign-link`}}return r.isDirectory()&&iO(e)?.contentHash===n?{kind:`same-copy`}:{kind:`different`}}function C9(e,t){let n;try{n=U(z(e,`.ok`,`skills`))}catch{n=z(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(z(e,t.dir)).startsWith(n+B)}catch{return!0}}).map(e=>e.name))}async function w9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??rCe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=au(n)}catch{return a}let s=R(t,n).split(B).join(`/`),c=new Set;for(let[e,n]of Object.entries(BJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!nt.test(e)||hz.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=z(n,e);if(!V(L(o,`SKILL.md`)))continue;let s=iO(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=z(t,r);return{host:n,root:r,path:L(i,e),escapes:gB(t,i),state:oCe(L(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`ok-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind!==`different`&&e.state.kind!==`foreign-link`&&V(z(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`different`||d.state.kind===`foreign-link`){a.skipped.push({name:e,reason:`target-occupied:${d.root}`});continue}d.state.kind===`same-copy`?ps(o,{recursive:!0,force:!0}):(d.state.kind===`ok-link`&&ps(d.path,{recursive:!0,force:!0}),aCe(o,d.path));for(let e of u)e===d||e.state.kind!==`ok-link`||(ps(e.path,{recursive:!0,force:!0}),fs(d.path,e.path,{recursive:!0}));await EI(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),x9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),x9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const T9=F(`skill-reconcile`),sCe=hz;function E9(){let e=[];for(let t of Rt){let n=be[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function cCe(e,t){let n=R(e,z(t));return Hl(n)?z(t):n}function D9(e){let{frontmatter:t,body:n}=rr(e),r={};if(t!==``)try{let e=(0,rj.parse)(dr(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function lCe(e,t){let n=D9(e),r=D9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function O9(e,t){let n=k9(e),r=k9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=L(e,o),c=L(t,o);if(i+=uu(s).size+uu(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!lCe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function k9(e,t=``){let n=[];for(let r of au(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...k9(L(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function A9(e,t,n){ps(t,{recursive:!0,force:!0}),ls(e,{recursive:!0}),as(cCe(e,n),t,`dir`)}function j9(e,t){try{let n=ou(e);return z(Hl(n)?n:z(I(e),n))===z(t)}catch{return!1}}function uCe(e,t){try{let n=ou(e),r=Hl(n)?z(n):z(I(e),n);if(!V(r))return!1;let i=R(z(t),r);return i!==``&&(i.startsWith(`..`)||Hl(i))}catch(t){return T9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const dCe=[...Rt,`agents`];function fCe(e){for(let t of dCe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function pCe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=au(n)}catch{return}let i=E9();for(let e of r){let r=fCe(e);if(r===null)continue;let a=z(n,e),o=z(n,r);if(V(o))try{let n=$l(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(L(a,`SKILL.md`))||!V(L(o,`SKILL.md`))||!O9(o,a))continue;for(let{rel:n}of i){let r=z(t,n);if(gB(t,r))continue;let i=L(r,e);j9(i,a)&&A9(r,i,o)}ps(a,{recursive:!0,force:!0}),T9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){T9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function mCe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of E9()){let o=z(t,e);if(!V(o)||gB(t,o))continue;let s;try{s=au(o)}catch(e){T9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(sCe.has(e))continue;let t=L(o,e),s=z(n,e),c=V(s);try{let l=$l(t);if(l.isSymbolicLink()){if(j9(t,s)&&c)continue;if(uCe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(A9(o,t,s),r.healed.push({name:e,editor:i})):(ps(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!nt.test(e)){T9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&O9(t,s)){A9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){T9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=CI(t);for(let[r,a]of i){let i=z(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await TI(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??uB(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){T9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{pCe({projectDir:t,skillsRoot:n})}catch(e){T9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}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=iN(e);M9=new ks({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),lr(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(){lr(null),await M9?.drain(),M9=null,N9=!1}Vo();const hCe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],gCe=[`cache`,`tmp`];function _Ce(e){let t=z(e,wo);if(!(()=>{if(!V(t))return!0;try{return au(t).length===0}catch{return!0}})())return[];let n=[];for(let t of hCe)V(z(e,t))&&n.push(t);for(let t of gCe){let r=z(e,t);try{V(r)&&uu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function vCe(e){let t=cd(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 yCe(e){uH();let t=e.projectDir??e.contentDir,n=nQ({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}`)}Ts.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}bs({localSink:n?.telemetry}),F9(t),tCe(),nCe();let{kind:r,gitdir:i}=vCe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ds(i));let o=JZ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Qo(`ok.boot`,{attributes:a},async()=>bCe(e)),l=()=>{if(s)try{let e=Bo.extract(Ho.active(),{traceparent:s});return Ho.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 bCe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??F(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?_j(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new gj("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-9cnBGhAH.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(!V(z(m,`config.yml`)))throw new X8(V(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);V(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??LG;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof PG||e instanceof FG){let t=e instanceof FG?e.detected:``,n=e instanceof FG?`too_old`:`not_available`;nK(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 ys(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let _=_Ce(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${wo}/.`);let v=p9({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:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee}=v,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ne=e.port??0,re=e.ephemeral?void 0:W8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${te}:${ne}`,log:r}),ie=c();ie.headersTimeout=3e4,ie.requestTimeout=6e4;let ae=e.serveContentAssets===!1?void 0:dM({contentFilter:v.contentFilter,contentSirv:ec(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Ro,assetExtensions:Qa,blocklistExtensions:Ja}),oe=!1;if(e.reactShellDistDir)try{fV(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),oe=!0}catch(e){if(e instanceof dV)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 se=e.reactShellDistDir?ec(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ce=e.ephemeral?null:new ND({contentDir:e.contentDir,localDir:C,globalDir:z(gu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:E,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://${te}:${ne}`,getMcpStdioCommand:()=>MD(e.localOpCliArgs,ne),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ce!==null&&await ce.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let le=K8({httpServer:ie,hocuspocus:y,mcpHttpHandler:re,remoteAccess:i,log:r,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ae,reactShellMiddleware:se,ephemeral:e.ephemeral,acpThreadManager:ce}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},de=null;a!==null&&(de=YZ({httpServer:ie,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ue()})})),await R9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);ie.once(`error`,r),ie.listen(e.port,e.host,()=>{ie.removeListener(`error`,r),t()})})}catch(e){if(oe)try{hV(C)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await b().catch(()=>{}),u(C),e}let fe=dH();fe!==void 0&&fH(`httpListenMs`,fe);let pe=ie.address(),me=typeof pe==`object`&&pe?pe.port:e.port??0;if(ne=me,d(C,me),oe&&pV(C,me),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:C,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let he=!1,ge=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)}};ue=async()=>{if(he)return;he=!0;let e=[],t=async(t,n)=>{try{await ge(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(C),oe&&gV(C)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{de?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ce!==null&&await t(`acpThreads.destroy`,()=>ce.destroy()),await t(`mount.shutdown`,()=>le.shutdown()),re!==void 0&&await t(`mcpHttpHandler.close`,()=>re.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{ie.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ie.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),oe&&await t(`releaseUiLock`,async()=>hV(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ys()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Ts.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await w9({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`),inPlaceNames:C9(e.contentDir,nV(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`store-skill-migration-failed`,error:String(e)},`Store-skill in-place migration failed (non-fatal).`)}try{let e=gu(),t=await w9({projectDir:e,skillsRoot:z(e,`.ok`,`skills`),hostRoots:iCe,inPlaceNames:C9(e,rV(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`global-store-skill-migration-failed`,error:String(e)},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await mCe({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.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:ie,destroy:ue,lockDir:C,contentDir:e.contentDir,port:me,ready:x,degraded:S,didAutoInit:f,serverInstance:v,acpThreadManager:ce}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new HZ(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=ld(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!V(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Ps({baseDir:n,timeout:{block:5e3}});s=new Set(await gS(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=xC(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 xCe=lo;function SCe(e={}){let t=e.home??gu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(L(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(L(r.APPDATA??L(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(Os(),1);const B9=L(gu(),`.ok`,`logs`),CCe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function wCe(){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 TCe(e){eu(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function ECe(e){try{if(uu(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{su(n,r)}catch{}}try{du(`${e}.3`)}catch{}}function DCe(e){try{let t=Date.now(),n=10080*60*1e3,r=au(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=uu(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{du(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{du(L(e,t.name)),a-=t.size}catch{}}}catch{}}function OCe(e){TCe(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);ECe(n),(e._setTimeout??setTimeout)(()=>DCe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:wCe(),name:e.name,redact:{paths:CCe,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 kCe(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 ACe(e){return L(B9,`${e}.${V9()}.log`)}function jCe(){return B9}function MCe(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=V(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=Ju(Pl),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function NCe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],ZF({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function PCe(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(V(n)){if(!uu(n).isDirectory()||V(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=LG()}catch(e){throw e instanceof PG||e instanceof FG?(nK(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof FG?`too_old`:`not_available`,detectedVersion:e instanceof FG?e.detected:``},e instanceof FG?`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 NCe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],ZF({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(!V(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}$/,FCe=Fa.map(e=>e.replace(/\/$/,``));async function ICe(e){let t=ld(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(BCe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Fs(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ns(async()=>{let t=await LCe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await RCe(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=Fs(e,{gitIndexFile:L(yu(),`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 zCe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await ZU(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Ls(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 \`${y}\` 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 FCe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function LCe(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 RCe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function zCe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function BCe(e){return V(L(e,`MERGE_HEAD`))||V(L(e,`rebase-merge`))||V(L(e,`rebase-apply`))||V(L(e,`CHERRY_PICK_HEAD`))||V(L(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function VCe(e,t){let n;try{n=Nl(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(V(n))try{let t=JSON.parse(await wu(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 HCe=[{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 HCe)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 UCe(e){if(!yC(e))throw new $9(e);let t;try{t=U(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!uu(t).isFile())throw new Q9(e);let n=I(t),r=FU(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:xC(R(WCe(e),t).split(B).join(`/`)),canonicalFilePath:t}}let i=zl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:xC(i)}}function WCe(e){return z(e,qo({absPath:Xo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function GCe(e){let t=tu(z(yu(),`ok-ephemeral-`)),n=z(t,`.ok`);return eu(n,{recursive:!0}),fu(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),fu(z(n,`.gitignore`),`local/
|
|
2029
2029
|
`,`utf-8`),t}export{qfe as $,rC as $i,Kz as $n,CF as $r,PG as $t,X7 as A,OT as Ai,gU as An,ole as Ar,EZ as At,f7 as B,hC as Bi,sH as Bn,tI as Br,aJ as Bt,p9 as C,MD as Ci,QH as Cn,GL as Cr,zZ as Ct,Z7 as D,eE as Di,ZH as Dn,VL as Dr,HX as Dt,J7 as E,aE as Ei,uU as En,HL as Er,yX as Et,Kxe as F,IC as Fi,jH as Fn,lI as Fr,eJ as Ft,q8 as G,$S as Gi,hV as Gn,rce as Gr,uJ as Gt,Y8 as H,oC as Hi,dV as Hn,KF as Hr,gJ as Ht,x7 as I,vC as Ii,NH as In,sI as Ir,mJ as It,j8 as J,KS as Ji,Xz as Jn,tce as Jr,Zq as Jt,W8 as K,JS as Ki,pV as Kn,ece as Kr,oJ as Kt,b7 as L,fC as Li,MH as Ln,cI as Lr,fJ as Lt,R7 as M,HT as Mi,LH as Mn,RI as Mr,DJ as Mt,F7 as N,LC as Ni,RH as Nn,oI as Nr,wJ as Nt,K7 as O,tE as Oi,_U as On,xle as Or,UX as Ot,y7 as P,K as Pi,AH as Pn,aI as Pr,yJ as Pt,Z2 as Q,aC as Qi,Gz as Qn,Ese as Qr,nK as Qt,Pxe as R,gC as Ri,OH as Rn,rI as Rr,hJ as Rt,I9 as S,OD as Si,$H as Sn,KL as Sr,LZ as St,G7 as T,nE as Ti,hU as Tn,Sle as Tr,bX as Tt,X8 as U,ZS as Ui,fV as Un,GF as Ur,cJ as Ut,l7 as V,dC as Vi,$V as Vn,ZF as Vr,pJ as Vt,K8 as W,QS as Wi,mV as Wn,HF as Wr,sJ as Wt,G2 as X,sC as Xi,qz as Xn,jF as Xr,iK as Xt,W2 as Y,XS as Yi,tB as Yn,Wse as Yr,oK as Yt,K2 as Z,WS as Zi,Uz as Zn,RF as Zr,tK as Zt,xCe as _,fd as _a,kO as _i,fW as _n,QL as _r,PZ as _t,UCe as a,jS as aa,iN as ai,UG as an,Nz as ar,Ife as at,F9 as b,rd as ba,ID as bi,KH as bn,Dle as br,IZ as bt,ICe as c,Jh as ca,dM as ci,OG as cn,Az as cr,T2 as ct,MCe as d,Yh as da,gj as di,lW as dn,mz as dr,X$ as dt,iC as ea,wse as ei,FG as en,Vz as er,R2 as et,OCe as f,Bd as fa,wj as fi,uW as fn,yz as fr,eue as ft,SCe as g,pd as ga,mj as gi,rW as gn,ZL as gr,BZ as gt,jCe as h,Nd as ha,hj as hi,dW as hn,dR as hr,YZ as ht,GCe as i,NS as ia,bF as ii,IG as in,Mz as ir,Ffe as it,W7 as j,kT as ji,YH as jn,zI as jr,PX as jt,Y7 as k,YT as ki,MU as kn,hL as kr,kZ as kt,W9 as l,qh as la,Oj as li,TG as ln,_z as lr,K0 as lt,ACe as m,Vd as ma,_j as mi,mW as mn,GR as mr,_1 as mt,Z9 as n,HS as na,yF as ni,LG as nn,Wz as nr,M2 as nt,X9 as o,wS as oa,rN as oi,zG as on,jz as or,E2 as ot,kCe as p,Pd as pa,Sj as pi,aW as pn,bz as pr,m1 as pt,V8 as q,tC as qi,iB as qn,nce as qr,Xq as qt,$9 as r,FS as ra,xF as ri,eK as rn,Hz as rr,Pfe as rt,VCe as s,Qie as sa,aN as si,kG as sn,wz as sr,w2 as st,Q9 as t,cC as ta,SF as ti,MG as tn,Bz as tr,L2 as tt,PCe as u,Xh as ua,Tj as ui,tW as un,vz as ur,x1 as ut,yCe as v,jd as va,RD as vi,FU as vn,$L as vr,RZ as vt,f9 as w,WT as wi,yU as wn,UL as wr,MZ as wt,P9 as x,nd as xa,ND as xi,vU as xn,WL as xr,FZ as xt,R9 as y,ud as ya,LD as yi,PU as yn,XL as yr,NZ as yt,p7 as z,pC as zi,xH as zn,QF as zr,iJ as zt};
|
|
2030
|
-
//# sourceMappingURL=src-
|
|
2030
|
+
//# sourceMappingURL=src-zLMYDmwT.mjs.map
|