@inkeep/open-knowledge 0.35.0-beta.3 → 0.35.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/assets/skills/discovery/SKILL.md +1 -1
  2. package/dist/assets/skills/project/SKILL.md +1 -1
  3. package/dist/cli.mjs +60 -60
  4. package/dist/constants-Drub4pPA.mjs +2 -0
  5. package/dist/{gh-detect-DRUIjmmd.mjs → gh-detect-NeyKGq5X.mjs} +2 -2
  6. package/dist/{git-handle-BCwv1aYd.mjs → git-handle-DNIGP-oX.mjs} +2 -2
  7. package/dist/git-handle-Dw3ybSQC.mjs +1 -0
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-BmIx3rNc.mjs → init-BpIMP05m.mjs} +3 -3
  10. package/dist/init-BzZ1nxgc.mjs +1 -0
  11. package/dist/{launch-json-removal-B9zm_MX5.mjs → launch-json-removal-BBUlOEXh.mjs} +2 -2
  12. package/dist/{loader-Bcf1hE1A.mjs → loader-BSaPrY-r.mjs} +2 -2
  13. package/dist/loader-CTDxw6gm.mjs +1 -0
  14. package/dist/{open-browser-nDAvg8ub.mjs → open-browser-caZ15VIJ.mjs} +2 -2
  15. package/dist/{preview-C9sqezQo.mjs → preview-BTH12odP.mjs} +2 -2
  16. package/dist/preview-Du6otyQk.mjs +1 -0
  17. package/dist/public/assets/{ActivityModeContent-B2deO8yQ.js → ActivityModeContent-DfzmUeDO.js} +1 -1
  18. package/dist/public/assets/{CodeMirrorPropInput-zdjDMuBA.js → CodeMirrorPropInput-BjR5mZym.js} +1 -1
  19. package/dist/public/assets/{DocumentContext-DawLAets.js → DocumentContext-2GME3A_0.js} +1 -1
  20. package/dist/public/assets/{EnableSyncConfirmDialog-CsbyPhST.js → EnableSyncConfirmDialog-BI2lTjur.js} +1 -1
  21. package/dist/public/assets/{GraphPanel-SyI9uG66.js → GraphPanel-oQRsCFcH.js} +1 -1
  22. package/dist/public/assets/{ManagedArtifactProperties-Ddr2nWTJ.js → ManagedArtifactProperties-D5M9d2dE.js} +1 -1
  23. package/dist/public/assets/{McpConsentDialogBody-BwgO2quE.js → McpConsentDialogBody-CB8Pv4O3.js} +1 -1
  24. package/dist/public/assets/{MermaidDocEditor-DoVPqV5s.js → MermaidDocEditor-BrFN810i.js} +1 -1
  25. package/dist/public/assets/{PropertyPanel-BfnQsy8K.js → PropertyPanel-B2WnrblN.js} +1 -1
  26. package/dist/public/assets/{ReportBugDialogBody-memFSmPS.js → ReportBugDialogBody-CellR0ZX.js} +1 -1
  27. package/dist/public/assets/{SettingsDialogBody-C7AsycvW.js → SettingsDialogBody-D98MzPrp.js} +1 -1
  28. package/dist/public/assets/{ShareBranchSwitchDialog-DI52ZkaG.js → ShareBranchSwitchDialog-CW_UJ-eO.js} +1 -1
  29. package/dist/public/assets/{ShareReceiveDialog-C8u6PgdG.js → ShareReceiveDialog-BzuwQHnF.js} +1 -1
  30. package/dist/public/assets/{ShareReceiveMissDialog-CXqnNDhM.js → ShareReceiveMissDialog-DrMwfK1b.js} +1 -1
  31. package/dist/public/assets/{SkillEditorActions-BERDSEkZ.js → SkillEditorActions-Cm5y2BZ4.js} +1 -1
  32. package/dist/public/assets/{SourceEditor-DRutRGBw.js → SourceEditor-CxWhYgNu.js} +1 -1
  33. package/dist/public/assets/{TerminalPanel-CXlIRGsk.js → TerminalPanel-Bk_BIYB8.js} +1 -1
  34. package/dist/public/assets/{agent-presence-CTUYlsSf.js → agent-presence-C64mZp_D.js} +1 -1
  35. package/dist/public/assets/{auth-state-cache-d-zc-KCt.js → auth-state-cache-DZs1ca2M.js} +1 -1
  36. package/dist/public/assets/{config-provider-CBrCc3Qp.js → config-provider-BT8vrkBg.js} +1 -1
  37. package/dist/public/assets/{dist-Dz1jo1x3.js → dist-C_VH1iMJ.js} +1 -1
  38. package/dist/public/assets/{dist-GfBYAWEU.js → dist-DG3yL_C_.js} +125 -125
  39. package/dist/public/assets/{doc-hash-Dpsv2KHX.js → doc-hash-DrUpeaJl.js} +1 -1
  40. package/dist/public/assets/{documents-events-DfKb4QSL.js → documents-events-P3hSJ6Kz.js} +1 -1
  41. package/dist/public/assets/{file-tree-adapter-CRpi38tj.js → file-tree-adapter-pWfTpD2d.js} +1 -1
  42. package/dist/public/assets/{index-Dgd8jjsU.js → index-BUFSuf64.js} +8 -8
  43. package/dist/public/assets/{lint-config-client-Cb7hYxEp.js → lint-config-client-DZwnvq7N.js} +1 -1
  44. package/dist/public/assets/{navigation-targets-BIH36ypL.js → navigation-targets-BsQBQGV7.js} +1 -1
  45. package/dist/public/assets/{open-managed-artifact-tab-DVygAONh.js → open-managed-artifact-tab-DK8Jplpz.js} +1 -1
  46. package/dist/public/assets/{pending-receive-nav-store-DVu1Va5x.js → pending-receive-nav-store-aLzlqydZ.js} +1 -1
  47. package/dist/public/assets/{prop-types-CbG7lwjT.js → prop-types-RJ22xYJ0.js} +1 -1
  48. package/dist/public/assets/{receive-store-B3-FInQ9.js → receive-store-CME4iACT.js} +1 -1
  49. package/dist/public/assets/{selection-context-hg8BypGZ.js → selection-context-BslGcXrj.js} +1 -1
  50. package/dist/public/assets/{skill-actions-CL3HYjOq.js → skill-actions-DVBy5dkK.js} +1 -1
  51. package/dist/public/assets/{skills-api-B0n4rKvF.js → skills-api-BGJ5gi1m.js} +1 -1
  52. package/dist/public/assets/{src-CjaySKVy.js → src-B-CycTJG.js} +1 -1
  53. package/dist/public/assets/{target-navigation-intent-Cz-oavji.js → target-navigation-intent-B7lBmAwE.js} +1 -1
  54. package/dist/public/assets/{typing-burst-detector-BVRmpsr-.js → typing-burst-detector-DRJpkieP.js} +1 -1
  55. package/dist/public/assets/{use-apply-config-color-theme-JH4tQfHA.js → use-apply-config-color-theme-CRAlCusI.js} +1 -1
  56. package/dist/public/assets/{workspace-paths-DtvYoBMA.js → workspace-paths-D1ZDD_2q.js} +1 -1
  57. package/dist/public/index.html +26 -26
  58. package/dist/{repair-launch-json-D6sRyNdF.mjs → repair-launch-json-DuPIIQQJ.mjs} +2 -2
  59. package/dist/{repair-mcp-configs-BW03uo6x.mjs → repair-mcp-configs-BH2W878J.mjs} +2 -2
  60. package/dist/repair-skills-7xPVXQFY.mjs +1 -0
  61. package/dist/{repair-skills-tJI8shk3.mjs → repair-skills-BwnStR-o.mjs} +2 -2
  62. package/dist/server-lock-478F0EVr.mjs +1 -0
  63. package/dist/{server-lock-CRw6jjM3.mjs → server-lock-DSGcGl-f.mjs} +2 -2
  64. package/dist/{src-BI8S8yWC.mjs → src-BaGHU9u4.mjs} +4 -4
  65. package/dist/{src-Z2z9ztGi.mjs → src-BraMZxHk.mjs} +1 -1
  66. package/dist/{src-C64mVogw.mjs → src-Bt_ZQ19J.mjs} +2 -2
  67. package/dist/{src-CFHcsBtV.mjs → src-QHqwclDn.mjs} +113 -113
  68. package/dist/start-DqOohUBC.mjs +1 -0
  69. package/dist/{start-CcshG5At.mjs → start-FlVzAWGV.mjs} +2 -2
  70. package/dist/{write-project-skill-Bg3yDMEj.mjs → write-project-skill-Do7JRTxt.mjs} +2 -2
  71. package/package.json +4 -4
  72. package/dist/constants-Bw9f4zC6.mjs +0 -2
  73. package/dist/git-handle-DcVL5mrG.mjs +0 -1
  74. package/dist/init-CGMdYLMe.mjs +0 -1
  75. package/dist/loader-lLJosWiU.mjs +0 -1
  76. package/dist/preview-BpU2BNy1.mjs +0 -1
  77. package/dist/repair-skills-Drky8zkq.mjs +0 -1
  78. package/dist/server-lock-KfTPtASZ.mjs +0 -1
  79. package/dist/start-oDoKOo6p.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./chunk-DTipWd-i.mjs";import{$ as o,$a as s,$i as c,$n as l,$r as u,$t as d,A as f,Aa as p,Ai as m,An as h,Ao as g,Ar as _,At as v,B as y,Ba as b,Bi as x,Bn as S,Bo as C,Br as w,Bt as ee,C as T,Ca as E,Ci as te,Cn as ne,Co as D,Cr as O,Ct as k,D as re,Da as A,Di as j,Dn as M,Do as ie,Dr as N,Dt as ae,E as oe,Ea as se,Ei as P,En as ce,Er as le,Et as ue,F as de,Fa as fe,Fi as pe,Fn as me,Fo as he,Fr as ge,Ft as _e,G as ve,Gi as ye,Gn as be,Gr as F,Gt as xe,H as Se,Ha as Ce,Hn as we,Ho as Te,Hr as Ee,Ht as De,I as Oe,Ia as ke,Ii as Ae,In as je,Io as Me,Ir as Ne,It as Pe,J as Fe,Ja as Ie,Ji as Le,Jn as Re,Jr as ze,Jt as Be,K as Ve,Ki as He,Kn as Ue,Ko as We,Kr as Ge,Kt as Ke,L as qe,La as Je,Li as Ye,Ln as Xe,Lo as Ze,Lr as Qe,Lt as eee,Ma as $e,Mn as tee,Mo as et,Mr as tt,Mt as nee,Na as nt,Nn as ree,No as rt,Nr as iee,Nt as aee,O as it,Oa as at,On as oee,Oo as ot,Or as see,Ot as cee,P as st,Pa as ct,Pi as lt,Pn as lee,Po as ut,Pr as dt,Pt as ft,Q as pt,Qi as mt,Qn as uee,Qr as ht,Qt as dee,R as gt,Ra as _t,Ri as vt,Rn as yt,Ro as bt,Rr as xt,Rt as St,Sa as Ct,Si as fee,Sn as pee,So as wt,Sr as mee,St as hee,T as gee,Ta as Tt,Ti as _ee,Tn as vee,To as Et,Tr as yee,Tt as Dt,U as Ot,Ui as kt,Un as At,Uo as jt,Ur as Mt,Ut as bee,V as Nt,Va as Pt,Vi as Ft,Vn as xee,Vr as It,Vt as See,W as Lt,Wi as Rt,Wn as Cee,Wr as zt,Wt as wee,X as Bt,Xa as Tee,Xi as Eee,Xn as Vt,Xr as Dee,Xt as Oee,Y as kee,Ya as Ht,Yi as Ut,Yn as Aee,Yr as jee,Yt as Mee,Z as Nee,Za as Wt,Zn as Gt,Zr as Pee,Zt as Fee,_ as Kt,_a as qt,_i as Iee,_n as Lee,_o as Jt,_r as Yt,_t as Xt,a as Zt,aa as Qt,ai as $t,an as en,ao as tn,ar as nn,at as rn,b as an,ba as on,bi as Ree,bn as zee,bo as sn,br as Bee,bt as Vee,c as cn,ca as ln,ci as Hee,cn as Uee,co as un,cr as dn,ct as fn,d as pn,di as mn,dn as Wee,do as hn,dr as gn,dt as _n,ei as vn,en as yn,eo as bn,er as xn,et as Sn,f as Cn,fa as wn,fi as Tn,fn as Gee,fo as En,fr as Kee,ft as Dn,g as On,ga as kn,gi as qee,gn as An,go as jn,gr as Jee,gt as Yee,h as Mn,ha as Nn,hi as Xee,hn as Zee,ho as Pn,hr as Qee,ht as $ee,i as Fn,ii as ete,in as In,io as Ln,ir as tte,it as Rn,ji as zn,jn as Bn,jo as Vn,jr as nte,jt as rte,k as Hn,ka as Un,ki as ite,kn as ate,kr as ote,kt as ste,l as Wn,la as Gn,li as Kn,ln as cte,lo as qn,lr as lte,lt as Jn,m as Yn,ma as Xn,mi as Zn,mn as ute,mo as Qn,mr as $n,mt as er,n as tr,na as nr,ni as rr,nn as ir,no as ar,nr as dte,nt as or,o as sr,oa as cr,oi as fte,on as pte,or as mte,ot as lr,p as ur,pa as dr,pi as hte,pn as gte,po as fr,pr as _te,pt as pr,q as mr,qa as hr,qi as gr,qn as _r,qr as vr,qt as vte,r as yr,ra as br,ri as xr,rn as Sr,ro as Cr,rr as yte,rt as wr,s as Tr,sa as Er,si as bte,sn as xte,so as Dr,sr as Or,st as kr,t as Ar,ti as jr,tn as Mr,to as Nr,tr as Ste,tt as Pr,u as Fr,ua as Ir,ui as Cte,un as Lr,ur as Rr,ut as zr,v as Br,va as Vr,vi as Hr,vn as Ur,vo as Wr,vr as Gr,vt as wte,w as Kr,wa as qr,wi as Tte,wn as Ete,wo as Jr,wr as Dte,wt as Ote,x as Yr,xa as Xr,xi as kte,xn as Ate,xo as Zr,xr as jte,xt as Mte,y as Qr,ya as $r,yi as ei,yn as Nte,yo as I,yr as Pte,yt as ti,z as ni,za as ri,zi as ii,zn as Fte,zo as ai,zr as oi,zt as Ite}from"./src-CFHcsBtV.mjs";import{a as si,c as ci,i as li,l as Lte,n as L,o as ui,r as di,s as fi,t as pi}from"./esm-DxvI2ZVA.mjs";import{a as mi,i as hi,o as gi,r as _i,s as vi,t as yi}from"./git-handle-BCwv1aYd.mjs";import{t as bi}from"./libesm-Ob3yvbRV.mjs";import{a as xi,b as Si,c as Ci,d as wi,f as Ti,g as Ei,h as Di,i as Oi,l as ki,m as Ai,n as ji,r as Mi,y as Ni}from"./server-lock-CRw6jjM3.mjs";import{n as Pi,t as Fi}from"./build-BGRQ9c88.mjs";import{t as Ii}from"./yazl-BucAN8Ez.mjs";import{t as Li}from"./chunk-B74TABJS-OU1nB5-d.mjs";import{a as Ri,c as zi,d as Bi,f as Vi,h as Hi,i as Ui,l as Wi,m as Gi,n as Ki,o as qi,p as Ji,r as Yi,s as Xi,t as Zi,u as Qi}from"./chunk-GFQRA5P5-CkMj9l7f.mjs";import{A as $i,B as ea,C as ta,D as na,E as ra,F as ia,H as aa,I as oa,L as sa,M as ca,N as la,O as ua,P as da,S as fa,T as pa,V as ma,_ as ha,a as ga,b as _a,c as va,d as ya,f as ba,g as xa,h as Sa,i as Ca,j as wa,k as Ta,l as Ea,m as Da,n as Oa,o as ka,p as Aa,r as ja,s as Ma,t as Na,u as Pa,v as Fa,w as Ia,x as La,y as Ra,z as za}from"./chunk-BGSUD5R5-B06UWAeH.mjs";import{a as Ba,c as Va,d as Ha,i as Ua,l as Wa,n as Ga,o as Ka,r as qa,s as Ja,t as Ya,u as Xa}from"./chunk-KX3P26DQ-BkUgp16C.mjs";import{n as Za,r as Qa,t as $a}from"./chunk-R6VWJ2ZL-DSqbA7Rj.mjs";import{r as eo}from"./chunk-CWQS3NFK-BQ5SUtd7.mjs";import{t as to}from"./chunk-DXB73IDG-fleZWn-g.mjs";import{n as no,t as ro}from"./chunk-5QMZ5MUS-BXTAb4Zq.mjs";import{n as io,t as ao}from"./chunk-A5O5YHGN-DTlknXj1.mjs";import{n as oo,r as so,t as co}from"./chunk-OJDRYQWQ-D4lSWh0K.mjs";import{r as lo,t as uo}from"./chunk-24IMIIXA-CV7UFJel.mjs";import{n as fo}from"./chunk-3THT3N7L-DrzOuTpA.mjs";import{t as po}from"./chunk-44UOCSGV-BbZqjKvt.mjs";import{t as mo}from"./wrapper-DkhhSWAE.mjs";import{createRequire as ho}from"node:module";import{execFile as go,spawn as _o,spawnSync as vo}from"node:child_process";import*as yo from"node:path";import{basename as bo,delimiter as xo,dirname as So,extname as Co,isAbsolute as wo,join as R,normalize as To,posix as Eo,relative as z,resolve as B,sep as Do,win32 as Oo}from"node:path";import*as ko from"node:fs";import{appendFileSync as Ao,chmodSync as jo,closeSync as Mo,cpSync as No,createReadStream as Po,createWriteStream as Fo,existsSync as V,linkSync as Io,lstatSync as Lo,mkdirSync as Ro,mkdtempSync as zo,openSync as Bo,readFile as Vo,readFileSync as H,readSync as Ho,readdirSync as Uo,readlinkSync as Wo,realpathSync as Go,renameSync as Ko,rmSync as qo,rmdirSync as Jo,statSync as Yo,symlinkSync as Xo,unlinkSync as Zo,writeFileSync as Qo}from"node:fs";import{homedir as $o,hostname as es,platform as ts,tmpdir as ns}from"node:os";import{URLSearchParams as rs,fileURLToPath as is}from"node:url";import{Transform as as,Writable as os}from"node:stream";import{Readable as ss}from"stream";import{access as cs,constants as ls,lstat as us,mkdir as ds,readFile as fs,readdir as ps,realpath as ms,rename as hs,stat as gs,unlink as Rte,writeFile as _s}from"node:fs/promises";import zte from"crypto";import vs,{createHash as ys,randomUUID as bs,webcrypto as xs}from"node:crypto";import*as Bte from"zlib";import{pipeline as Ss}from"node:stream/promises";import{setTimeout as Cs}from"node:timers/promises";import{promisify as ws}from"node:util";import{lookup as Vte}from"node:dns/promises";import{request as Hte}from"node:http";import{request as Ute}from"node:https";import{createBrotliDecompress as Wte,createGunzip as Gte,createInflate as Kte}from"node:zlib";import{Http2ServerRequest as Ts,constants as qte}from"http2";import{AsyncLocalStorage as Jte}from"node:async_hooks";import{lookup as Yte}from"node:dns";function Xte(e){return`git-author-${We(e.trim().toLowerCase())}`}const Zte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Es(e,t,n){let r;try{r=Yo(e)}catch(t){let n=t.code;return n===`ENOENT`||n===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let i=Qte(t,n);if(r.isDirectory())return{kind:`directory`,path:e,projectSubPath:i};if(r.isFile()){let n;try{n=H(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let r=n.match(/^gitdir:\s*(.+)$/);return r?{kind:`linked`,path:B(t,r[1]),gitPath:e,projectSubPath:i}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function Qte(e,t){let n=z(e,t);return n===``||n===`.`||n.startsWith(`..`)||wo(n)?``:n}function $te(e){let t=$o(),n=B(e);for(let e=0;e<64;e++){if(n===t)return null;let e=So(n);if(e===n||e===t)return null;let r=B(e,`.git`);try{let t=Yo(r);if(t.isDirectory()||t.isFile())return{gitPath:r,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${r} (${t??`unknown`}); skipping ancestor`)}n=e}return null}function Ds(e){let t=B(e),n=Es(B(t,`.git`),t,t);if(n.kind!==`absent`)return n;let r=$te(t);return r===null?{kind:`absent`}:Es(r.gitPath,r.workTreeRoot,t)}function Os(e){let t=Ds(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ks(e){let t=Ds(e);switch(t.kind){case`directory`:return B(t.path,As(t.projectSubPath));case`linked`:if(!V(t.path))throw new js(t.gitPath,t.path);return B(t.path,As(t.projectSubPath));case`malformed-pointer`:throw new js(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Ms(t.gitPath,{cause:t.cause});case`absent`:return B(e,`.git/ok`)}}function As(e){return e===``?`ok`:`ok-${ene(e)}`}function ene(e){let t=e.split(Do).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=tne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function tne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var js=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}},Ms=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 nne(e){let t;try{t=ks(e)}catch(e){if(e instanceof js||e instanceof Ms)return null;throw e}return V(B(t,`HEAD`))?t:null}function Ns(e){return`refs/wip/${e}/`}function rne(e){if(!e)return[];let t=[];for(let n of e.split(`
1
+ import{a as e,i as t,n,o as r,r as i,t as a}from"./chunk-DTipWd-i.mjs";import{$ as o,$a as s,$i as c,$n as l,$r as u,$t as d,A as f,Aa as p,Ai as m,An as h,Ao as g,Ar as _,At as v,B as y,Ba as b,Bi as x,Bn as S,Bo as C,Br as w,Bt as ee,C as T,Ca as E,Ci as te,Cn as ne,Co as D,Cr as O,Ct as k,D as re,Da as A,Di as j,Dn as M,Do as ie,Dr as N,Dt as ae,E as oe,Ea as se,Ei as P,En as ce,Er as le,Et as ue,F as de,Fa as fe,Fi as pe,Fn as me,Fo as he,Fr as ge,Ft as _e,G as ve,Gi as ye,Gn as be,Gr as F,Gt as xe,H as Se,Ha as Ce,Hn as we,Ho as Te,Hr as Ee,Ht as De,I as Oe,Ia as ke,Ii as Ae,In as je,Io as Me,Ir as Ne,It as Pe,J as Fe,Ja as Ie,Ji as Le,Jn as Re,Jr as ze,Jt as Be,K as Ve,Ki as He,Kn as Ue,Ko as We,Kr as Ge,Kt as Ke,L as qe,La as Je,Li as Ye,Ln as Xe,Lo as Ze,Lr as Qe,Lt as eee,Ma as $e,Mn as tee,Mo as et,Mr as tt,Mt as nee,Na as nt,Nn as ree,No as rt,Nr as iee,Nt as aee,O as it,Oa as at,On as oee,Oo as ot,Or as see,Ot as cee,P as st,Pa as ct,Pi as lt,Pn as lee,Po as ut,Pr as dt,Pt as ft,Q as pt,Qi as mt,Qn as uee,Qr as ht,Qt as dee,R as gt,Ra as _t,Ri as vt,Rn as yt,Ro as bt,Rr as xt,Rt as St,Sa as Ct,Si as fee,Sn as pee,So as wt,Sr as mee,St as hee,T as gee,Ta as Tt,Ti as _ee,Tn as vee,To as Et,Tr as yee,Tt as Dt,U as Ot,Ui as kt,Un as At,Uo as jt,Ur as Mt,Ut as bee,V as Nt,Va as Pt,Vi as Ft,Vn as xee,Vr as It,Vt as See,W as Lt,Wi as Rt,Wn as Cee,Wr as zt,Wt as wee,X as Bt,Xa as Tee,Xi as Eee,Xn as Vt,Xr as Dee,Xt as Oee,Y as kee,Ya as Ht,Yi as Ut,Yn as Aee,Yr as jee,Yt as Mee,Z as Nee,Za as Wt,Zn as Gt,Zr as Pee,Zt as Fee,_ as Kt,_a as qt,_i as Iee,_n as Lee,_o as Jt,_r as Yt,_t as Xt,a as Zt,aa as Qt,ai as $t,an as en,ao as tn,ar as nn,at as rn,b as an,ba as on,bi as Ree,bn as zee,bo as sn,br as Bee,bt as Vee,c as cn,ca as ln,ci as Hee,cn as Uee,co as un,cr as dn,ct as fn,d as pn,di as mn,dn as Wee,do as hn,dr as gn,dt as _n,ei as vn,en as yn,eo as bn,er as xn,et as Sn,f as Cn,fa as wn,fi as Tn,fn as Gee,fo as En,fr as Kee,ft as Dn,g as On,ga as kn,gi as qee,gn as An,go as jn,gr as Jee,gt as Yee,h as Mn,ha as Nn,hi as Xee,hn as Zee,ho as Pn,hr as Qee,ht as $ee,i as Fn,ii as ete,in as In,io as Ln,ir as tte,it as Rn,ji as zn,jn as Bn,jo as Vn,jr as nte,jt as rte,k as Hn,ka as Un,ki as ite,kn as ate,kr as ote,kt as ste,l as Wn,la as Gn,li as Kn,ln as cte,lo as qn,lr as lte,lt as Jn,m as Yn,ma as Xn,mi as Zn,mn as ute,mo as Qn,mr as $n,mt as er,n as tr,na as nr,ni as rr,nn as ir,no as ar,nr as dte,nt as or,o as sr,oa as cr,oi as fte,on as pte,or as mte,ot as lr,p as ur,pa as dr,pi as hte,pn as gte,po as fr,pr as _te,pt as pr,q as mr,qa as hr,qi as gr,qn as _r,qr as vr,qt as vte,r as yr,ra as br,ri as xr,rn as Sr,ro as Cr,rr as yte,rt as wr,s as Tr,sa as Er,si as bte,sn as xte,so as Dr,sr as Or,st as kr,t as Ar,ti as jr,tn as Mr,to as Nr,tr as Ste,tt as Pr,u as Fr,ua as Ir,ui as Cte,un as Lr,ur as Rr,ut as zr,v as Br,va as Vr,vi as Hr,vn as Ur,vo as Wr,vr as Gr,vt as wte,w as Kr,wa as qr,wi as Tte,wn as Ete,wo as Jr,wr as Dte,wt as Ote,x as Yr,xa as Xr,xi as kte,xn as Ate,xo as Zr,xr as jte,xt as Mte,y as Qr,ya as $r,yi as ei,yn as Nte,yo as I,yr as Pte,yt as ti,z as ni,za as ri,zi as ii,zn as Fte,zo as ai,zr as oi,zt as Ite}from"./src-QHqwclDn.mjs";import{a as si,c as ci,i as li,l as Lte,n as L,o as ui,r as di,s as fi,t as pi}from"./esm-DxvI2ZVA.mjs";import{a as mi,i as hi,o as gi,r as _i,s as vi,t as yi}from"./git-handle-DNIGP-oX.mjs";import{t as bi}from"./libesm-Ob3yvbRV.mjs";import{a as xi,b as Si,c as Ci,d as wi,f as Ti,g as Ei,h as Di,i as Oi,l as ki,m as Ai,n as ji,r as Mi,y as Ni}from"./server-lock-DSGcGl-f.mjs";import{n as Pi,t as Fi}from"./build-BGRQ9c88.mjs";import{t as Ii}from"./yazl-BucAN8Ez.mjs";import{t as Li}from"./chunk-B74TABJS-OU1nB5-d.mjs";import{a as Ri,c as zi,d as Bi,f as Vi,h as Hi,i as Ui,l as Wi,m as Gi,n as Ki,o as qi,p as Ji,r as Yi,s as Xi,t as Zi,u as Qi}from"./chunk-GFQRA5P5-CkMj9l7f.mjs";import{A as $i,B as ea,C as ta,D as na,E as ra,F as ia,H as aa,I as oa,L as sa,M as ca,N as la,O as ua,P as da,S as fa,T as pa,V as ma,_ as ha,a as ga,b as _a,c as va,d as ya,f as ba,g as xa,h as Sa,i as Ca,j as wa,k as Ta,l as Ea,m as Da,n as Oa,o as ka,p as Aa,r as ja,s as Ma,t as Na,u as Pa,v as Fa,w as Ia,x as La,y as Ra,z as za}from"./chunk-BGSUD5R5-B06UWAeH.mjs";import{a as Ba,c as Va,d as Ha,i as Ua,l as Wa,n as Ga,o as Ka,r as qa,s as Ja,t as Ya,u as Xa}from"./chunk-KX3P26DQ-BkUgp16C.mjs";import{n as Za,r as Qa,t as $a}from"./chunk-R6VWJ2ZL-DSqbA7Rj.mjs";import{r as eo}from"./chunk-CWQS3NFK-BQ5SUtd7.mjs";import{t as to}from"./chunk-DXB73IDG-fleZWn-g.mjs";import{n as no,t as ro}from"./chunk-5QMZ5MUS-BXTAb4Zq.mjs";import{n as io,t as ao}from"./chunk-A5O5YHGN-DTlknXj1.mjs";import{n as oo,r as so,t as co}from"./chunk-OJDRYQWQ-D4lSWh0K.mjs";import{r as lo,t as uo}from"./chunk-24IMIIXA-CV7UFJel.mjs";import{n as fo}from"./chunk-3THT3N7L-DrzOuTpA.mjs";import{t as po}from"./chunk-44UOCSGV-BbZqjKvt.mjs";import{t as mo}from"./wrapper-DkhhSWAE.mjs";import{createRequire as ho}from"node:module";import{execFile as go,spawn as _o,spawnSync as vo}from"node:child_process";import*as yo from"node:path";import{basename as bo,delimiter as xo,dirname as So,extname as Co,isAbsolute as wo,join as R,normalize as To,posix as Eo,relative as z,resolve as B,sep as Do,win32 as Oo}from"node:path";import*as ko from"node:fs";import{appendFileSync as Ao,chmodSync as jo,closeSync as Mo,cpSync as No,createReadStream as Po,createWriteStream as Fo,existsSync as V,linkSync as Io,lstatSync as Lo,mkdirSync as Ro,mkdtempSync as zo,openSync as Bo,readFile as Vo,readFileSync as H,readSync as Ho,readdirSync as Uo,readlinkSync as Wo,realpathSync as Go,renameSync as Ko,rmSync as qo,rmdirSync as Jo,statSync as Yo,symlinkSync as Xo,unlinkSync as Zo,writeFileSync as Qo}from"node:fs";import{homedir as $o,hostname as es,platform as ts,tmpdir as ns}from"node:os";import{URLSearchParams as rs,fileURLToPath as is}from"node:url";import{Transform as as,Writable as os}from"node:stream";import{Readable as ss}from"stream";import{access as cs,constants as ls,lstat as us,mkdir as ds,readFile as fs,readdir as ps,realpath as ms,rename as hs,stat as gs,unlink as Rte,writeFile as _s}from"node:fs/promises";import zte from"crypto";import vs,{createHash as ys,randomUUID as bs,webcrypto as xs}from"node:crypto";import*as Bte from"zlib";import{pipeline as Ss}from"node:stream/promises";import{setTimeout as Cs}from"node:timers/promises";import{promisify as ws}from"node:util";import{lookup as Vte}from"node:dns/promises";import{request as Hte}from"node:http";import{request as Ute}from"node:https";import{createBrotliDecompress as Wte,createGunzip as Gte,createInflate as Kte}from"node:zlib";import{Http2ServerRequest as Ts,constants as qte}from"http2";import{AsyncLocalStorage as Jte}from"node:async_hooks";import{lookup as Yte}from"node:dns";function Xte(e){return`git-author-${We(e.trim().toLowerCase())}`}const Zte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Es(e,t,n){let r;try{r=Yo(e)}catch(t){let n=t.code;return n===`ENOENT`||n===`ENOTDIR`?{kind:`absent`}:{kind:`inaccessible`,gitPath:e,cause:t}}let i=Qte(t,n);if(r.isDirectory())return{kind:`directory`,path:e,projectSubPath:i};if(r.isFile()){let n;try{n=H(e,`utf-8`).trim()}catch(t){return{kind:`malformed-pointer`,gitPath:e,target:``,cause:t}}let r=n.match(/^gitdir:\s*(.+)$/);return r?{kind:`linked`,path:B(t,r[1]),gitPath:e,projectSubPath:i}:{kind:`malformed-pointer`,gitPath:e,target:``}}return{kind:`absent`}}function Qte(e,t){let n=z(e,t);return n===``||n===`.`||n.startsWith(`..`)||wo(n)?``:n}function $te(e){let t=$o(),n=B(e);for(let e=0;e<64;e++){if(n===t)return null;let e=So(n);if(e===n||e===t)return null;let r=B(e,`.git`);try{let t=Yo(r);if(t.isDirectory()||t.isFile())return{gitPath:r,workTreeRoot:e}}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTDIR`&&console.warn(`[shadow-repo-layout] Cannot stat ${r} (${t??`unknown`}); skipping ancestor`)}n=e}return null}function Ds(e){let t=B(e),n=Es(B(t,`.git`),t,t);if(n.kind!==`absent`)return n;let r=$te(t);return r===null?{kind:`absent`}:Es(r.gitPath,r.workTreeRoot,t)}function Os(e){let t=Ds(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ks(e){let t=Ds(e);switch(t.kind){case`directory`:return B(t.path,As(t.projectSubPath));case`linked`:if(!V(t.path))throw new js(t.gitPath,t.path);return B(t.path,As(t.projectSubPath));case`malformed-pointer`:throw new js(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Ms(t.gitPath,{cause:t.cause});case`absent`:return B(e,`.git/ok`)}}function As(e){return e===``?`ok`:`ok-${ene(e)}`}function ene(e){let t=e.split(Do).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=tne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function tne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var js=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}},Ms=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 nne(e){let t;try{t=ks(e)}catch(e){if(e instanceof js||e instanceof Ms)return null;throw e}return V(B(t,`HEAD`))?t:null}function Ns(e){return`refs/wip/${e}/`}function rne(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 Ps=`ok-checkpoint-v1: `;function Fs(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(Ps))continue;let n;try{n=JSON.parse(e.slice(18))}catch{return null}if(typeof n!=`object`||!n)return null;let r=n,i=r.kind,a=r.metadata;if(typeof a!=`object`||!a)return null;let o=typeof r.docName==`string`?r.docName:null,s=typeof r.size==`number`&&Number.isFinite(r.size)?r.size:null;if(i===`bridge-merge-loss`){let e=a;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:o,size:s,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(i===`producer-guard-loss`){let e=a;return typeof e.construct==`string`?{kind:`producer-guard-loss`,docName:o,size:s,metadata:{construct:e.construct}}:null}if(i===`observer-a-duplication`){let e=a;return typeof e.duplicatedLineCount==`number`&&Number.isFinite(e.duplicatedLineCount)?{kind:`observer-a-duplication`,docName:o,size:s,metadata:{duplicatedLineCount:e.duplicatedLineCount}}:null}if(i===`external-change-rescue`){let e=a;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:o,size:s,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}if(i===`auto-consolidation`){let e=a;return typeof e.foldedRefs==`number`&&Number.isFinite(e.foldedRefs)&&typeof e.trigger==`string`?{kind:`auto-consolidation`,docName:o,size:s,metadata:{foldedRefs:e.foldedRefs,trigger:e.trigger}}:null}return null}return null}function Is(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${Ps}${JSON.stringify(t)}`}const Ls=`ok-actor: `;function Rs(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),`${Ls}${JSON.stringify(i)}`}function zs(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=ine(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 ine(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 ane(e){if(!e)return null;for(let t of e.split(`
4
4
  `)){let e=t.trim();if(!e.startsWith(Ls))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:zs(n)}return null}function Bs(e){if(!e)return[];let t=[];for(let n of e.split(`
@@ -1263,7 +1263,7 @@ tags: [lore, history]
1263
1263
  `),i=n.nextFenced+(r?`
1264
1264
  `:``)+t;YI(y.dc.document,i,`agent`),OL(`mcp-write`),w=!0}C=!0},y.origin)})}finally{he?.touchMode(c,`idle`)}if(S){let e;switch(S.kind){case`invalid_value`:e={[S.key]:S.reason};break;case`reserved_key`:e={[S.key]:`'${S.key}' is reserved`};break;case`unknown_key`:e={[S.key]:`'${S.key}' is not a recognized key`};break;case`duplicate_target`:e={[S.key]:`'${S.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${S.expected.join(`, `)}; got: ${S.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${S.bytes} > ${S.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${S.reason}`};break;case`invalid_path`:e={[S.path.map(String).join(`.`)||`__path__`]:S.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(S)})`}}G(a,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(C&&ee.length>0){if(Oz(s,c,l,u,void 0,vn({clientName:d,clientVersion:f,label:p}),v),bk(),wn(g),w){let e=await xt(s);if(e?.kind===`failure`){wt(a,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Tt(a,`frontmatter-patch`);return}}bt(s,`frontmatter-patch`)}pe?.setFocus(c,{agentName:l,currentDoc:s,writeKind:`write`,ts:Date.now()}),ge?.();let T=_t(s),E=yt();E===0&&sQ().add(1,{"shadow.writer":`agent`,"agent.type":ec(d)});let te=Et(b);Pt(s,y.dc.document.getText(`source`).toString());let ne=kt();ne.add(s);let D=hX(y.dc.document.getText(`source`).toString(),s,ne,Nt);q(a,200,dt,{timestamp:x,subscriberCount:T,systemSubscriberCount:E,appliedKeys:ee,..._?{summary:_}:{},...te?{warning:te,warnings:[te]}:{},brokenLinks:D},{handler:`frontmatter-patch`})}catch(e){if(e instanceof ML){G(a,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}vQ.error({err:e},`[frontmatter-patch] handler failed`),G(a,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Ln(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 Rn=J(M,async(e,n)=>{try{let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!QQ(i)){G(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let a=gt(i);if(ZI(a)||QI(a)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`document-read`});return}let o=t.documents.get(a);if(o){q(n,200,Gr,{docName:a,content:o.getText(`source`).toString(),lifecycle:Ln(o)},{handler:`document-read`});return}if(!V(PQ(r,`file`,a))){G(n,404,`urn:ok:error:doc-not-found`,`Document not found: ${a}.`,{handler:`document-read`});return}let s=await t.openDirectConnection(a);try{let e=s.document;if(!e){G(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}q(n,200,Gr,{docName:a,content:e.getText(`source`).toString(),lifecycle:Ln(e)},{handler:`document-read`})}finally{await s.disconnect()}}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),zn=J(M,async(e,t)=>{try{Ee&&await Ee.catch(e=>{vQ.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`}`),i=n.searchParams.get(`dir`),o=n.searchParams.get(`showAll`)===`true`,c=n.searchParams.get(`showOk`)===`true`,l=n.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{xQ(r,i)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(o&&Ce&&Jve(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=vL(t,`document-list`),a=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=wQ(),n=OQ({contentDir:r,contentFilter:Ce,dirFilter:i,maxEntries:t,maxDepth:l,showOk:c,signal:e.signal}),o=0,s=await n.next();for(;!s.done;)await a(`${JSON.stringify(s.value)}\n`),o+=1,s=await n.next();let{truncated:u}=s.value;u&&vQ.info({handler:`document-list`,maxEntries:t,count:o},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:o})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):vQ.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(o&&Ce){let e=`showAll:${l===1?`d1:`:``}${c?`ok:`:``}${i??``}`,n=Je.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=wQ(),{truncated:a}=await Yve({contentDir:r,contentFilter:Ce,dirFilter:i,documents:e,maxEntries:n,maxDepth:l,showOk:c,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)}),a&&vQ.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();n={promise:a,controller:t,waiters:0};let o=n;Je.set(e,o),a.finally(()=>{Je.get(e)===o&&Je.delete(e)})}let a=n;a.waiters+=1;let o=!1,s=()=>{t.writableEnded||o||(o=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),Je.get(e)===a&&Je.delete(e)))};t.on(`close`,s);try{let{documents:e,truncated:n}=await a.promise;if(o)return;q(t,200,Yt,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(o)return;G(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,s)}return}let u=a(),d=s(),f=p?.()??new Map,m=[];for(let[e,t]of f)i&&!e.startsWith(`${i}/`)&&e!==i||m.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let h=[];try{let e=it(u);Qe?.signature!==e&&(Qe={signature:e,assets:fpe({contentDir:r,fileIndex:u,readMarkdown:e=>{try{return H(e,`utf-8`)}catch{return null}},isExcluded:Ce?e=>Ce.isPathIgnored(e):void 0})}),h=Qe?.assets??[]}catch(e){Qe=null,console.warn(`[document-list] asset collection failed; returning documents only:`,e)}let g=new Set;for(let e of h)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(g.add(e.path),m.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 d){if(t.kind===`markdown`){if(i&&!e.startsWith(`${i}/`)&&e!==i)continue;let n=dL(e);m.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let a of t.aliases){if(i&&!a.startsWith(`${i}/`)&&a!==i)continue;let o=yB(z(r,t.canonicalPath));m.push({kind:`document`,docName:a,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o})}continue}if((!i||e===i||e.startsWith(`${i}/`))&&!g.has(e)){let n=SQ(e);m.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(!(!i||n===i||n.startsWith(`${i}/`))||g.has(n))continue;let a=yB(z(r,t.canonicalPath)),o=SQ(n);m.push({kind:`file`,docName:n,path:n,docExt:`.${o}`,assetExt:o,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}let _=b?.()??new Map;if(_.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of _){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,i]of t){let t=f.get(n),a=t?yB(z(r,t.canonicalPath)):n;for(let r of i)e(r)&&m.push({kind:`folder`,path:r,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:a})}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 f)n(e,n=>{m.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:yB(z(r,t.canonicalPath))})});for(let[e,t]of d)n(e,n=>{let i=yB(z(r,t.canonicalPath));if(t.kind===`markdown`)m.push({kind:`document`,docName:n,docExt:dL(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i});else{let r=SQ(n);m.push({kind:`file`,docName:n,path:n,docExt:`.${r}`,assetExt:r,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}})}m.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),q(t,200,Yt,{documents:m},{handler:`document-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Vn=J(M,async(e,t)=>{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!QQ(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}q(t,200,Jee,{docName:n,backlinks:P.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:ct(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Hn=J(M,async(e,t)=>{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!QQ(t)||(r[t]=P.getBacklinkCount(t))}q(t,200,Qee,{counts:r},{handler:`backlink-counts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Gn=J(M,async(e,t)=>{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!QQ(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=kt();q(t,200,Pte,{docName:n,forwardLinks:P.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:lt(e.target,r),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Kn=J(M,async(e,t)=>{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!QQ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){G(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){G(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:a,links:o}=P.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=P.getLinkGraph());let s=kt();q(t,200,Bee,{nodes:a.map(e=>{if(e.kind===`doc`){let t=mt(e.docName,s);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:lt(e.docName,s),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o},{handler:`link-graph`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),qn=J(M,async(e,t)=>{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!Eee(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}q(t,200,yte,{orphans:P.getOrphans([...a().keys()],n).map(e=>({docName:e,title:ct(e)}))},{handler:`orphans`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),Jn=J(M,async(e,t)=>{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20,a=kt();q(t,200,dte,{hubs:P.getHubs(i).map(e=>({docName:e.docName,title:lt(e.docName,a),count:e.count}))},{handler:`hubs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),Yn=J(M,async(e,t)=>{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!QQ(e))){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>gt(e)))]:void 0;q(t,200,Ste,{deadLinks:P.getDeadLinks(kt(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:ct(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),Xn=J(Dte,async(i,a,o)=>{try{let{find:i,replace:s,offset:c}=o,l=MQ(o.docName,a,`agent-patch`);if(l===null)return;let u=gt(l),{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:h,label:g}=_n(o);if(Ave(i)){lQ().add(1,{result:`rejected`}),G(a,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(ZI(u)||QI(u)){G(a,400,`urn:ok:error:reserved-doc-name`,`'${u}' is a reserved document name.`,{handler:`agent-patch`});return}let _=MR(o.summary),v=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),y=dB(t,u,r,e.resolveEmbed),b=new Date().toISOString(),x=!1,S=!1,C=!1,w;try{let t=pn(m),n=cn[t]??Wn(p??d);if(he?.setPresence(d,{displayName:f,icon:t,color:n,currentDoc:u,mode:`writing`,ts:Date.now()}),kR(v.dc.document.getText(`source`),d,p,m),v.dc.document.transact(()=>{let{frontmatter:t,body:n}=Ye(v.dc.document.getText(`source`).toString()),r=Ae(t,n),a=c==null?r.indexOf(i):r.slice(c,c+i.length)===i?c:-1;if(a===-1){c==null?x=!0:S=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":u,findLength:i.length,replaceLength:s.length,hadOffset:c!=null})),iae();return}if(a<t.length){C=!0;return}let{body:o}=Ye(r.slice(0,a)+s+r.slice(a+i.length));w=jL(v.dc.document,o,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:u}:void 0),v.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Patched (${f}): ${i.slice(0,50)}`})},v.origin),w!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":u,position:`patch`,intendedBytes:w.intendedBytes,actualBytes:w.actualBytes,byteDelta:w.byteDelta,"agent.id":d,"agent.client_name":m})),!x&&!S&&!C){let{stored:e}=Sn(_);Oz(u,d,f,p,void 0,vn({clientName:m,clientVersion:h,label:g}),e),bk(),wn(_),hQ(`agent-patch`,w)}}finally{he?.touchMode(d,`idle`)}if(S){G(a,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(x){G(a,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(C){lQ().add(1,{result:`rejected`}),G(a,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ee=await xt(u);if(ee?.kind===`failure`){wt(a,ee.failure,`agent-patch`);return}if(ee?.kind===`divergence`){Tt(a,`agent-patch`);return}bt(u,`agent-patch`),pe?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`edit`,ts:Date.now()}),ge?.();let T=_t(u),E=yt();E===0&&sQ().add(1,{"shadow.writer":`agent`,"agent.type":ec(m)});let{response:te}=Sn(_),ne=v.dc.document.getText(`source`).toString();Pt(u,ne);let D=await dq(ne,u),O=kt();O.add(u);let k=hX(ne,u,O,Nt),re=Et(y),A=w===void 0?void 0:wL(w),j=[...A?[A]:[],...re?[re]:[],...D??[],...await qo(v.dc.document.getText(`source`).toString(),u)];q(a,200,yee,{timestamp:b,subscriberCount:T,systemSubscriberCount:E,...te?{summary:te}:{},...A?{warning:A}:re?{warning:re}:{},...j.length>0?{warnings:j}:{},brokenLinks:k},{handler:`agent-patch`})}catch(e){if(e instanceof bL){xL(a,e,`agent-patch`);return}if(e instanceof TL){EL(a,e,`agent-patch`);return}if(e instanceof ML){G(a,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}vQ.error({err:e},`[agent-patch] handler failed`),G(a,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),Zn=J(le,async(t,r,i)=>{try{let t=MQ(i.docName,r,`agent-undo`);if(t===null)return;let a=gt(t),{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=_n(i);if(ZI(a)||QI(a)){G(r,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=i,p=i.scope===`session`||i.scope===`file`?`session`:`last`;if(!n.hasSession(a,f)){G(r,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let m=await n.getSession(a,f),h=!1;try{let t=pn(l),n=cn[t]??Wn(c??o);he?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:a,mode:`writing`,ts:Date.now()}),h=Ole(m,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0),h&&Oz(a,f,s,c,void 0,vn({clientName:l,clientVersion:u,label:d}))}finally{he?.touchMode(o,`idle`)}if(h){let e=await xt(a);if(e?.kind===`failure`){wt(r,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Tt(r,`agent-undo`);return}bt(a,`agent-undo`)}pe?.setFocus(f,{agentName:f,currentDoc:a,writeKind:`undo`,ts:Date.now()}),q(r,200,N,{docName:a,scope:p,undone:h},{handler:`agent-undo`})}catch(e){if(e instanceof bL){xL(r,e,`agent-undo`);return}vQ.error({err:e},`[agent-undo] handler failed`),G(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Qn=J(M,async(e,t)=>{try{let r=Zs(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){G(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}q(t,200,je,ade(n,r),{handler:`agent-activity`})}catch(e){vQ.error({err:e},`[agent-activity] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:e})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),tr=J(M,async(e,t)=>{try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=Zs(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`stackIndex`);if(i===null){G(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!a||a.trim()===``){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!QQ(a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=gt(a);if(ZI(s)||QI(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!o||Number.isNaN(Number(o))){G(t,400,`urn:ok:error:invalid-request`,`StackIndex must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){G(t,400,`urn:ok:error:invalid-request`,`stackIndex must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=n.getLiveSession(s,i);if(!l){G(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let u=l.um;if(c>=u.undoStack.length){G(t,404,`urn:ok:error:not-found`,`stackIndex ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let d=u.undoStack[c];q(t,200,Xe,{diff:nde(d,l.dc.document.getText(`source`),s),generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(e){vQ.error({err:e},`[agent-burst-diff] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:e})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),nr=J(M,async(e,t)=>{try{await E?.(),q(t,200,At,{},{handler:`test-flush-git`})}catch(e){vQ.error({err:e},`[test-flush-git] flush failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:e})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),rr=J(M,async(e,i)=>{try{let a=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),o=gt(a.searchParams.get(`docName`)??`test-doc`),s;try{s=JV(o,r)}catch(e){vQ.error({err:e,docName:o},`[test-reset] safeContentPath rejected docName`),G(i,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await n.closeAll(o),t.closeConnections(o);let c=`onStoreDocument-${o}`;t.debouncer.isDebounced(c)&&await t.debouncer.executeNow(c);let l=t.documents.get(o);if(l&&await(Te??t.unloadDocument.bind(t))(l),Qo(s,``,`utf-8`),P&&(P.deleteDocument(o),P.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${o}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),a.searchParams.get(`reset-okignore`)!==`false`)try{let e=B(r,`.okignore`),n=t.documents.get(dr);if(n){let e=n.getText(`source`);e.length>0&&n.transact(()=>{e.delete(0,e.length)},QR)}V(e)&&Qo(e,``,`utf-8`),Ce&&await Ce.rebuildIgnorePatterns()}catch(e){console.warn(`[test-reset] okignore reset partial failure:`,e)}fe?.(`files`),q(i,200,Ue,{},{handler:`test-reset`})}catch(e){G(i,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),ir=J(M,async(e,t)=>{try{if(!P){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await P.rebuildFromDisk(),await P.ingestGlobalSkillBundles([B(la,`.ok`,`skills`)]),P.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),fe?.(`backlinks`),fe?.(`graph`),q(t,200,Cee,{},{handler:`test-rescan-backlinks`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),or=J(M,async(e,t)=>{try{if(!x){G(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await x(),fe?.(`files`),q(t,200,be,{},{handler:`test-rescan-files`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),sr=J(gn,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=_n(n),o=w?.current;if(!o){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let s=/^[a-zA-Z0-9_-]+$/,c=[],l=!1;if(Array.isArray(n.writers))try{c=n.writers.map(e=>{let t=e.id??`unknown`;if(!s.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){G(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=ie?.()??`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 Uz(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[Xz],l=!0}let d=se??`.`,f=MR(typeof n.summary==`string`?n.summary:void 0),p=await aB(o,d,c,u,f.kind===`value`?f.value:void 0,l?{includeUpstream:!1}:void 0);U(`history`).info({checkpointRef:p.checkpointRef},`checkpoint`);try{await DV(o,hV(o.gitDir))}catch(e){console.warn(`[rename-log] post-saveVersion GC failed:`,e)}q(t,200,Kee,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(e){vQ.error({err:e},`[save-version] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:e})}},{handler:`save-version`,method:`POST`}),cr=J(M,async(e,t)=>{let n=w?.current;if(!n){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}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`)??ie?.()??`main`;if(!i&&a===null){G(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(o.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=Wi(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}=Ze.run(u,()=>Ove(n,e.folderRel,se??`.`,{branch:o,limit:s,offset:l}));f&&YZ(`folder`),q(t,200,dn,{...await d},{handler:`history`});return}let s=se??`.`,c=yQ(i,s);if(`error`in c){G(t,400,`urn:ok:error:invalid-request`,c.error,{handler:`history`});return}let l=Number(r.searchParams.get(`limit`)??`50`),u=Number(r.searchParams.get(`offset`)??`0`),d=Math.min(200,Number.isFinite(l)?l:50),f=Number.isFinite(u)?u:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=r.searchParams.get(`includeAutoCheckpoints`)===`true`,_=`doc\0${o}\0${i}\0${d}\0${f}\0${p??``}\0${m??``}\0${h??``}\0${g?`1`:`0`}`,v=Date.now();try{let{promise:e,coalesced:r}=Ze.run(_,()=>Dve(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&YZ(`doc`);let a=await e,c=Date.now()-v;U(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),q(t,200,dn,{...a},{handler:`history`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function lr(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=w?.current;if(!r){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,a=se??`.`,o=yQ(i,a);if(`error`in o){G(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=Hz(r),c=ie?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await OV(r,i,n,c,hV(r.gitDir),e=>{let t=yQ(e,a);return`error`in t?`${e}.md`:t.path},vV());if(e===null){G(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let o=await s.raw(`show`,`${n}:${e}`),[l=``,u=``]=(await s.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);q(t,200,lte,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let ur=J(tee,async(n,r,i)=>{let a=xX(i,xe);if(a.kind===`invalid-summary`){G(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=t.documents.get(i.docName);if(o&&yL(o)){xL(r,new bL({file:fL(i.docName)}),`rollback`);return}let s=w?.current;if(!s){G(r,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=i,u=se??`.`,d=yQ(c,u);if(`error`in d){G(r,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=Hz(s),p=Date.now();try{let n=hV(s.gitDir),i=vV(),o=await OV(s,c,l,ie?.()??`main`,n,e=>{let t=yQ(e,u);return`error`in t?`${e}.md`:t.path},i);if(o===null){G(r,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let d=await f.raw(`show`,`${l}:${o}`),m=new Date().toISOString();await eB(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=t.documents.get(c);if(!h){G(r,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let g=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:c}:void 0,_;h.transact(()=>{XI(h,d,g),_=CL(h.getText(`source`).toString(),d,`rollback`)},gQ),_!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:_.intendedBytes,actualBytes:_.actualBytes,byteDelta:_.byteDelta,"actor.kind":a.kind,...a.kind===`agent`||a.kind===`principal`?{"actor.writer_id":a.writerId}:{}})),hQ(`rollback`,_);let v;switch(a.kind){case`agent`:{let e=l.slice(0,8),t=a.summary.kind===`value`,n=t?a.summary:MR(`Restored to ${e}`),r=Sn(n);v=t||!r.response?r.response:Cn(r.response),Oz(c,a.writerId,a.displayName,a.colorSeed,Ws(c,l),a.actor,r.stored),bk(),wn(n,!t);break}case`principal`:{let e=Sn(a.summary);v=e.response,Oz(c,a.writerId,a.displayName,a.colorSeed,Ws(c,l),a.actor,e.stored),wn(a.summary,!1);break}case`anonymous`:vQ.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(a.kind)}`)}dQ().add(1,{kind:`rollback`,attribution_kind:a.kind});let y=await xt(c);if(y?.kind===`failure`){wt(r,y.failure,`rollback`);return}if(y?.kind===`divergence`){Tt(r,`rollback`);return}bt(c,`rollback`);let b=Date.now()-p;U(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:b},`rollback`),a.kind===`agent`&&pe?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let x=_===void 0?void 0:wL(_);q(r,200,ree,{restoredFrom:l,timestamp:m,...v?{summary:v}:{},...x?{warning:x,warnings:[x]}:{}},{handler:`rollback`})}catch(e){G(r,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),fr=J(M,async(e,t)=>{try{q(t,200,xee,kk(),{handler:`metrics-reconciliation`})}catch(e){vQ.error({err:e},`[metrics-reconciliation] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:e})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),pr=J(M,async(e,t)=>{try{q(t,200,S,ete(),{handler:`metrics-parse-health`})}catch(e){vQ.error({err:e},`[metrics-parse-health] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:e})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),mr=J(M,async(e,t)=>{try{Ee&&await Ee.catch(e=>{vQ.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=$V(),n=oe?.(),r=cge();q(t,200,Cte,{serverInstanceId:i,currentBranch:e,...n===void 0?{}:{currentDiskAckSVs:n},...r===void 0?{}:{boot:r}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0});async function hr(e,t){if(!lZ(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=xe?.()??null;if(!n){G(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}q(t,200,Hee,n,{handler:`principal`})}async function gr(e,t){if(!lZ(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=he?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);q(t,200,Fte,{presence:r},{handler:`metrics-agent-presence`})}catch(e){vQ.error({err:e},`[metrics-agent-presence] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:e})}}async function yr(e,t){if(!lZ(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=jU.read();q(t,200,$n,{entries:n,count:n.length,detection:bme(n[0])},{handler:`embed-detect`})}async function xr(e,t){if(!lZ(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=B(r),i=n,a=!0;try{i=Go(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),G(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}q(t,200,_te,{contentDir:i,pathSeparator:Do,symlinkResolved:a},{handler:`workspace`})}let Sr=J(M,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let i=ppe(n),a=Co(n).slice(1).toLowerCase();if(!i||!Wt.has(a)){G(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let o=Go(r),s=B(o,n),c;try{c=Go(s)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!YV(c,o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let l;try{l=Yo(c)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!l.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let u=pH(o,c);if(u!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(Ce?.isPathIgnored(u)){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let d=Cr.has(a),f={"Content-Type":i,"Content-Length":String(l.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":bn.has(a)||d?`inline`:`attachment`,"Cache-Control":`no-store`};a===`svg`?f[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:d&&(f[`Content-Security-Policy`]=ar),t.writeHead(200,f);try{await Ss(Po(c),t)}catch(e){vQ.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:n,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),wr=1048576,Tr=J(M,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let i=Go(r),a=B(i,n),o;try{o=Go(a)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!YV(o,i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let s;try{s=Yo(o)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!s.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(pH(i,o)!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(s.size>wr){G(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${wr}-byte text-viewer cap.`,{handler:`asset-text`});return}let c=(await fs(o)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(c)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Er=J(M,async(e,t)=>{try{if(!w?.current){q(t,200,Rr,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=B(w.current.gitDir,`rescue`);if(V(r))try{let t=Uo(r).filter(e=>iL(e));for(let i of t){let t=B(r,i),a=Yo(t);if(e-a.mtimeMs>864e5){try{Zo(t)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}n.push({docName:oL(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){vQ.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=ie?.()??`main`,t=await nB(w.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){vQ.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}q(t,200,Rr,n,{handler:`rescue-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Dr=J(Ate,async(e,t,n)=>{try{let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let i=n.path;if(!iL(i)){G(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(i.includes(`..`)||i.startsWith(`/`)||i.includes(`\0`)||i.includes(`\\`)){G(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let a=B(r),o=B(a,i);if(!bB(o,a)){G(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let s=oL(i);if(ZI(s)||QI(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`create-page`});return}if(AQ(i)||Ct(s)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let l=typeof n.template==`string`?n.template.trim():``,u=``,d;if(l.length>0){if(!/^[A-Za-z0-9_-]+$/.test(l)){G(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let n=i.includes(`/`)?i.slice(0,i.lastIndexOf(`/`)):``,r=YH(a,n),o=r.find(e=>e.name===l);if(!o){let e=r.length===0?`(none)`:r.map(e=>`"${e.name}" (${e.scope})`).join(`, `);G(t,400,`urn:ok:error:invalid-request`,`Template "${l}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let s=B(a,o.path),c;try{c=H(s,`utf-8`)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=Mn(c),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;u=xU(f,{date:CU(),user:p}),d=o.scope}Ro(So(o),{recursive:!0});try{Qo(o,u,{encoding:`utf-8`,flag:`wx`})}catch(e){if(zQ(e)){G(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let f=oL(i);switch(Oe?.delete(f),Ce&&Ce.incrementMdDir(So(f)),TB(o,DB(u)),e.kind){case`agent`:case`principal`:Oz(f,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}c?.({kind:`create`,path:o,docName:f,content:u}),P&&(P.updateDocumentFromMarkdown(f,u),P.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${f}:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),d!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:l,templateScope:d,docName:f})),q(t,200,pee,{docName:f},{handler:`create-page`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),kr=J(Nte,async(e,t,n)=>{try{if(xX(n,xe).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!kQ(e)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(AQ(e)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(Ce?.isDirExcluded(e)){G(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let i=PQ(r,`folder`,e);if(V(i)){G(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}lz(i,{recursive:!0}),tt(e),fe?.(`files`),q(t,200,zee,{path:e},{handler:`create-folder`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Ar=J(vee,async(e,n,i)=>{try{let e=xX(i,xe);if(e.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=i,o=i.path,s=a===`file`?oL(o):o;if(!kQ(o)){G(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(AQ(o)||a===`file`&&(ZI(s)||QI(s))||a===`folder`&&jQ(o)){G(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&UQ(r,o);let l=PQ(r,a,o);if(!V(l)){if(a===`file`){let e=PQ(r,`folder`,o);if(V(e)&&Yo(e).isDirectory()){G(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return}}G(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return}let u=Yo(l);if(a===`file`&&!u.isFile()||a===`folder`&&!u.isDirectory()){G(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return}let d=a===`file`?[HQ(r,o)]:ln(PQ(r,`folder`,o)),f=ve?.(),p=new Set(f?f.getConflicts().map(e=>e.file):[]);for(let e of d){let r=e,i=t.documents.get(r),a=fL(r),o=i!==void 0&&yL(i),s=p.has(a);if(o||s){xL(n,new bL({file:a}),`duplicate-path`);return}}let m,h=[];if(a===`file`){let e=Co(l);if(m=tye(r,s).docName,ZI(m)||QI(m)||Ce?.isExcluded(`${m}${e}`)){G(n,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=eye(r,m,e),i=H(l,`utf-8`),a=So(t),o=V(a);try{lz(a,{recursive:!0}),sz(t,i,{encoding:`utf-8`,flag:`wx`})}catch(e){if(zQ(e)){G(n,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!o)try{gz(a)}catch(e){let t=e.code;t!==`ENOENT`&&t!==`ENOTEMPTY`&&console.warn(`[duplicate-path] failed to clean duplicate parent directory:`,{destinationDir:a,err:e})}throw e}let u=!1;try{uL(m,e),Oe?.delete(m),Ce&&(Ce.incrementMdDir(So(m)),u=!0),TB(t,DB(i)),c?.({kind:`create`,path:t,docName:m,content:i}),P?.updateDocumentFromMarkdown(m,i),h=[m]}catch(e){try{hz(t,{force:!0})}catch(e){console.warn(`[duplicate-path] failed to clean partial file duplicate:`,{destinationPath:t,err:e})}throw pL(m),Ce&&u&&Ce.decrementMdDir(So(m)),c?.({kind:`delete`,path:t,docName:m}),e}}else{if(m=nye(r,o).folderPath,Ce?.isDirExcluded(m)){G(n,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=PQ(r,`folder`,m);try{dz(l,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(zQ(e)){G(n,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of iye(r,m))tt(e);let e=rye(r,m);h=e.map(e=>e.docName);for(let t of e){let e=Co(t.fullPath);uL(oL(t.docName),e),Oe?.delete(t.docName),Ce&&Ce.incrementMdDir(So(t.docName)),TB(t.fullPath,DB(t.content)),c?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),P?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{hz(e,{recursive:!0,force:!0})}catch(t){console.warn(`[duplicate-path] failed to clean partial folder duplicate:`,{destinationPath:e,err:t})}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of h)Oz(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)}`)}P&&h.length>0&&(P.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist duplicate-path cache:`,e)}),fe?.(`backlinks`),fe?.(`graph`)),fe?.(`files`),q(n,200,ce,{kind:a,path:m,duplicatedDocNames:h},{handler:`duplicate-path`})}catch(e){if(e instanceof RQ){G(n,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let t=Qve(e);if(t){G(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}G(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),jr=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){G(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!QQ(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=st(n);if(!r){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!V(r)){G(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}q(t,200,oee,{docName:n,headings:oye(H(r,`utf-8`))},{handler:`page-headings`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Mr=J(h,async(e,n,i)=>{try{let e=xX(i,xe);if(e.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:a,fromPath:o,toPath:s}=i;if(!kQ(o)||!kQ(s)){G(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(a===`file`&&(ZI(o)||ZI(s)||QI(o)||QI(s))){G(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(AQ(o)||AQ(s)){G(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(o===s){q(n,200,Bn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let c=a===`asset`&&iL(o)&&iL(s)?`file`:a;if(c===`asset`){let t;try{t=iL(o)&&!iL(s)?await mn(o,s):await fn(o,s)}catch(e){if(e instanceof bL){xL(n,e,`rename-path`);return}let{status:t,type:r,error:i}=Rt(e);G(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&at();let r;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${o} → ${s}`;r=Dn(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{vQ.debug({kind:`asset`,fromPath:o,toPath:s,affectedDocs:t.rewrittenDocs.length,affectedAssets:t.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(dQ().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),D)try{await D()}catch(e){console.warn(`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,e)}q(n,200,Bn,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}c===`file`&&UQ(r,o);let l=c===`file`?[HQ(r,o)]:ln(PQ(r,`folder`,o)),u=ve?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of l){let r=e,i=t.documents.get(r),a=fL(r),o=i!==void 0&&yL(i),s=d.has(a);if(o||s){xL(n,new bL({file:a}),`rename-path`);return}}if(Ce){let e=iL(o)?Co(o):dL(o);if(c===`file`?Ce.isExcluded(iL(s)?s:`${s}${e}`):Ce.isDirExcluded(s)){G(n,400,`urn:ok:error:invalid-request`,`Destination ${c===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let f=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,p;try{p=await hn(o,s,c,f?{actor:f}:{})}catch(e){if(e instanceof oG){G(n,409,`urn:ok:error:doc-already-exists`,Lt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(p.renamed.length===0&&p.renamedAssets.length===0){q(n,200,Bn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&at();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=Dn(e,`Renamed ${o} → ${s}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Gs(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{vQ.debug({kind:a,fromPath:o,toPath:s,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),dQ().add(1,{kind:`rename-${c}`,attribution_kind:e.kind}),D)try{await D()}catch(e){console.warn(`[rename-path] flushContributors failed (commitSha backfill may be deferred):`,e)}q(n,200,Bn,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=Rt(e);G(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Pr=J(ne,async(e,n,i)=>{try{_n(i);let{kind:e,path:a}=i;if(!kQ(a)){G(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let o=e===`asset`?sn(a):{path:a,ambiguous:!1};if(o.ambiguous){G(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let s=o.path,l=e===`asset`&&iL(s)?`file`:e;if(l===`file`&&UQ(r,s),AQ(s)){G(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let u=l===`asset`?PQ(r,`folder`,s):PQ(r,l,s);if(!V(u)){G(n,404,`urn:ok:error:doc-not-found`,`${l} does not exist.`,{handler:`delete-path`});return}let d=Yo(u);if(l===`file`&&!d.isFile()||l===`asset`&&!d.isFile()||l===`folder`&&!d.isDirectory()){G(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${l}.`,{handler:`delete-path`});return}let f=l===`asset`?[]:l===`file`?[HQ(r,s)]:ln(PQ(r,`folder`,s)),p=ve?.(),m=new Set(p?p.getConflicts().map(e=>e.file):[]);for(let e of f){let r=e,i=t.documents.get(r),a=fL(r),o=i!==void 0&&yL(i),s=m.has(a);if(o||s){xL(n,new bL({file:a}),`delete-path`);return}}if(await zt(f,`deleted-upstream`),Oe)for(let e of f)ZI(e)||QI(e)||(Oe.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));l===`file`||l===`asset`?fz(u):(hz(u,{recursive:!0,force:!1}),nt(s)),at();for(let e of f)c?.({kind:`delete`,path:B(r,fL(e)),docName:e});fe?.(`files`),q(n,200,Ete,{deletedDocNames:f},{handler:`delete-path`})}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Fr=J(lee,async(e,t,n)=>GI(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":ez(n.path),"ok.cleanup.path.role":tz(n.path)}},async()=>{try{if(xX(n,xe).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:i}=n;if(!kQ(i)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let o=e===`asset`&&iL(i)?`file`:e,s=oL(i);o===`file`&&UQ(r,i);let l=o===`folder`&&jQ(i);if(o===`file`&&(ZI(s)||QI(s))||l||AQ(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(o===`asset`){at(),fe?.(`files`),q(t,200,me,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let u=a(),d=o===`file`?u.has(s)?[s]:[]:Xve(u,o,i);if(at(),d.length===0){q(t,200,me,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await zt(d,`deleted-upstream`),Oe)for(let e of d)ZI(e)||QI(e)||(Oe.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of d)c?.({kind:`delete`,path:B(r,fL(e)),docName:e});o===`folder`&&nt(i),fe?.(`files`),q(t,200,me,{deletedDocNames:d},{handler:`trash-cleanup`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),zr=J(M,async(e,t)=>{try{let e=a(),n=[];for(let[t,i]of e){let e=dL(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let n=H(B(r,`${t}${e}`),`utf-8`);a=_B(n,t),o=vB(n)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}}n.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),q(t,200,ate,{pages:n},{handler:`pages`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Br=J(M,async(e,n)=>{try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){G(n,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!QQ(r)){G(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(ZI(r)||QI(r)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`suggest-links`});return}q(n,200,tte,await hve({hocuspocus:t,fileIndex:a(),docName:r}),{handler:`suggest-links`})}catch(e){if(e instanceof HZ){G(n,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}G(n,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 qr(e,t){if(e.method!==`POST`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let n;try{n=await Wve(e,F??r)}catch(e){if(e instanceof UY){G(t,WY(e.reason),e.reason,KY(e.reason),{handler:`upload-asset`,cause:e});return}G(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:i,tempPath:a,sha:s,byteLength:c,parentDocName:l,placement:u}=n,d=()=>{if(V(a))try{Zo(a)}catch{}},f=aW(hte,{parentDocName:l,placement:u||void 0},t,{handler:`upload-asset`});if(!f.ok){d();return}let{parentDocName:p,placement:m}=f.value,{agentId:h,agentName:g}=_n(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(c===0){d(),G(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(p.includes(`\0`)||p.includes(`..`)||p.startsWith(`/`)){d(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let _=B(r),v;try{v=m===`parent-dir`?`./`:o?.()??`./`}catch(e){d(),vQ.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),G(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!Ht(v)){d(),G(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let y=Bve(p,Tee(v),_);if(!YV(y,_)){d(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{NQ(y,_)}catch(e){if(d(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}vQ.error({err:e,destDir:y},`[upload] failed to validate destination directory`),G(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{Ro(y,{recursive:!0})}catch(e){if(!zQ(e)){d();let n=GY(e);G(t,WY(n),n,KY(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=Go(y),n;try{n=Go(_)}catch{n=_}if(!YV(e,n)){d(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(e.code!==`ENOENT`){d(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let b=Vve(a,4100),x=await Zue(b),S=x?.mime,C=x?.ext;if(!S){let e=b.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(S=`image/svg+xml`,C=`svg`)}{let n=await Uve(y,s,c);if(n){d();let i=yB(z(r,B(y,n)));vQ.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!0,mime:S??null,size:c,destPath:i,httpStatus:200},`[upload] dedup hit`),q(t,200,Tn,{src:n,path:i,deduped:!0},{handler:`upload-asset`});return}}let w;if(!i||i===`upload`||Ive.test(i)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=i?Co(i).slice(1):``,n=C??t??``;w=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else w=zve(i);try{let n=Xhe(a,y,w),i=yB(z(r,B(y,n)));vQ.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!1,mime:S??null,size:c,destPath:i,httpStatus:200},`[upload] write ok`),q(t,200,Tn,{src:n,path:i,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof UY?n.reason:`urn:ok:error:storage-error`;vQ.error({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,filename:w,size:c,reason:r,httpStatus:WY(r),err:n},`[upload] write failed`),G(t,WY(r),r,KY(r),{handler:`upload-asset`,cause:n})}}let Jr=`/api/local-op/clone`,Yr=`/api/local-op/ok-init`,Xr=600*1e3,Zr={stdio:[`ignore`,`ignore`,`pipe`]},Qr={stdio:[`ignore`,`pipe`,`pipe`]},$r={stdio:`ignore`},ni=`local-op-clone`,ri=J(bte,ii,{handler:ni,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:ni})});async function ii(e,t,n){let{url:r,dir:i,branch:a}=n;if(!ZX(r)){G(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:ni,cause:Error(`url=${r}`)});return}if(!$X(i)){G(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:ni,cause:Error(`dir=${i}`)});return}if(!qe.tryAcquire(Jr)){G(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:ni,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=vL(t,ni),s=null,c=cZ({cliArgs:ye,url:r,dir:i,branch:a,timeoutMs:Xr,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&vQ.warn({stderr:qq(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=g_e(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(qq(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 ai(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}):vQ.error({err:e,handler:ni},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),qe.release(Jr)}})(),t.on(`close`,()=>{c.cancel()})}async function ai(e,t){let n=B(QX(e)),r=gH(n),i=VY(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=ye,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=_o(a,s(e),nV({...Zr,cwd:n,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),i=[];t.stderr?.on(`data`,t=>{i.push(t),vQ.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,vQ.error({cwd:n,cliCmd:e,err:t.message},`[local-op/clone] failed to spawn child`)}),t.unref();let u=Date.now()+45e3;for(;Date.now()<u;){await Cs(500);let t=VY(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=Oi(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=Oi(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 oi=`local-op-ok-init`,si=J(l,async(e,t,n)=>{let{projectPath:r}=n;if(!wo(r)){G(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:oi,cause:Error(`projectPath=${r}`)});return}let i;try{i=Go(r)}catch(e){q(t,200,xn,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:oi});return}if(!$X(i)){G(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:oi,cause:Error(`projectPath=${r}`)});return}let a=Ds(i).kind;if(a!==`directory`&&a!==`linked`){console.warn(`[ok-init] action=init project=${bo(i)} result=not-a-git-worktree kind=${a}`),q(t,200,xn,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:oi});return}if(SX(i)){console.warn(`[ok-init] action=init project=${bo(i)} result=already-initialized`),q(t,200,xn,{ok:!0,projectPath:i},{handler:oi});return}if(!qe.tryAcquire(Yr)){G(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:oi,extraHeaders:{"Retry-After":`2`}});return}try{await hi(async()=>{IX(i)}),console.warn(`[ok-init] action=init project=${bo(i)} result=success`),q(t,200,xn,{ok:!0,projectPath:i},{handler:oi})}catch(e){let n=e instanceof Error?e.message:String(e);console.warn(`[ok-init] action=init project=${bo(i)} result=failed reason=${n}`),q(t,200,xn,{ok:!1,reason:`init-failed`,message:n},{handler:oi})}finally{qe.release(Yr)}},{handler:oi,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:oi})}),L=`/api/local-op/auth/login`,ui=`/api/local-op/auth/status`,di=`/api/local-op/auth/repos`,pi=`/api/local-op/auth/signout`,gi=()=>kq(F??r),_i=null,vi=`local-op-auth-login`,yi=J(Re,bi,{handler:vi,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:vi})});async function bi(e,t,n){let r=n.host??gi();if(!qe.tryAcquire(L)){let e=_i;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-login-slot-no-controller`,channel:`auth`,transport:`http`})),G(t,429,`urn:ok:error:concurrent-operation`,`An auth login operation is already in progress.`,{handler:vi,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),_i=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=vL(t,vi),a=nZ({cliArgs:ye,host:r,timeoutMs:Xr,onEvent:e=>{if(e.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth subprocess reported an error.`,{cause:e.message?Error(e.message):void 0});return}if(Pve(e,ve),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});_i=a;let o=()=>{a.cancel(),_i===a&&(_i=null,qe.release(L))};t.on(`close`,o),a.done.finally(()=>{if(t.off(`close`,o),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}_i===a&&(_i=null,qe.release(L))})}let xi=`local-op-auth-status`,Si=J(Re,async(e,t,n)=>{let r=n.host??gi();if(!qe.tryAcquire(ui)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:xi,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ye,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=_o(e,i,nV({...Qr,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(`
1265
1265
  `).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{}o===null?q(t,200,Vt,{authenticated:!1},{handler:xi}):q(t,200,Vt,o,{handler:xi})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:xi,cause:e})}finally{qe.release(ui)}},{handler:xi,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:xi})}),Ci=`local-op-auth-repos`,wi=J(Re,Ti,{handler:Ci,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Ci})});async function Ti(e,t,n){let r=n.host??gi();if(!qe.tryAcquire(di)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Ci,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=vL(t,Ci),[a,...o]=ye,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=_o(a,s,nV({...Qr,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},Xr);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
1266
- `);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=>{vQ.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(),qe.release(di))}),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()),qe.release(di))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),qe.release(di))})}let Ei=`local-op-auth-signout`,Di=J(Re,async(e,t,n)=>{let r=n.host??gi();if(!qe.tryAcquire(pi)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Ei,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ye,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=_o(e,i,nV({...$r,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),q(t,200,_r,{},{handler:Ei})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Ei,cause:e})}finally{qe.release(pi)}},{handler:Ei,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Ei})}),ki=`/api/local-op/auth/set-identity`,Ai=`local-op-auth-set-identity`,ji=J(Aee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!F){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ai});return}if(!qe.tryAcquire(ki)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ai,extraHeaders:{"Retry-After":`5`}});return}try{yge(F,r,i),ve?.()?.refreshIdentity().catch(()=>{}),q(t,200,_r,{},{handler:Ai})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ai,cause:e})}finally{qe.release(ki)}},{handler:Ai,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Ai})});async function Mi(e,t){if(eZ(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){q(t,200,An,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),q(t,200,An,e.getStatus(),{handler:`sync-status`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Ni=J(Lee,async(e,t,n)=>{let r=ve?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,Ur,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`sync-trigger`})?ve?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Pi(e,t){if(eZ(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();q(t,200,gte,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Fi=J(ute,async(e,t,n)=>{let r=ve?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,Zee,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Ii(e,n){if(!eZ(e,n,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!F){G(n,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`file`);if(!i){G(n,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(n,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=oL(i),o=t.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=ve?.(),c=s?s.getConflicts().some(e=>e.file===i):!1;if(!o&&!c){G(n,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let l=r.searchParams.get(`source`),u=mi({baseDir:F,timeout:{block:15e3}});async function d(e){try{return{present:!0,content:await u.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,r,a]=await Promise.all([d(1),d(2),d(3)]),o=e.present?e.content:``,s=a.present?a.content:``,c=r.present&&a.present?`both-modified`:!r.present&&a.present?`delete-modify`:r.present&&!a.present?`modify-delete`:`both-modified`,u=r.present?r.content:``,f=null;if(l===`ytext`){let e=oL(i),n=t.documents.get(e);if(n){let t=n.getMap(`lifecycle`).get(`status`);if(f=typeof t==`string`&&t.length>0?t:null,c!==`delete-modify`){let t=ke?ke(e):null;t!==null&&!Fve(t)?u=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(n,200,Gee,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:f},{handler:`sync-conflict-content`})}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Li(e,t){if(!eZ(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=AZ(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,Wee,{plan:await LZ({projectDir:r,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof yZ){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof bZ){G(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Ri=J(Uee,async(e,t,n)=>{let i=n.plan;if(!i||typeof i!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let a=i,o=n.packId,s=AZ(o);if(typeof o==`string`&&o.length>0&&s===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${o}" is not registered.`});return}try{q(t,200,cte,{result:await FZ(a,{projectDir:r,packId:s})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`seed-apply`})});async function zi(e,t){if(eZ(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,Lr,{packs:jZ()},{handler:`seed-packs`})}}let Bi=J(pte,async(e,t,n)=>{if(n.out!==void 0&&!$X(n.out)){G(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{q(t,200,xte,await WJ({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`install-skill`})});async function Vi(e,t){if(eZ(e,t,{handler:`installed-agents`}))try{await Qme(e,t,ot.probeAll)}catch(e){t.headersSent||(vQ.error({err:e},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Hi=J(M,async(e,t)=>{if(!de){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,vte,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Ui(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let r;try{r=decodeURIComponent(n)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){G(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:ct(e),matchingTags:t,snippet:null}));q(t,200,Ke,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Wi(e,t,n=`path`,i=`folder-config`){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:i}),null;let o=B(r),s=a===``?o:B(o,a);return s!==o&&!s.startsWith(`${o}${Do}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:i}),null):{folderRel:a,resolvedContentDir:o}}let Gi=/^[A-Za-z0-9_-]+$/;function Ki(e,t,n=`template`){return!e||!Gi.test(e)?(G(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function qi(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:B(e,i);if(a!==e&&!a.startsWith(`${e}${Do}`))continue;let o=B(a,`.ok`,`templates`,`${n}.md`);if(V(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Ji(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}async function Yi(e,t){if(e.method===`GET`)return Xi(e,t);if(e.method===`PUT`)return Zi(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Xi=J(M,async(e,t)=>{try{let n=Wi(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await aU(n.folderRel,{projectDir:n.resolvedContentDir}),i=B(B(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(V(i))try{let e=(0,YN.parse)(await fs(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}q(t,200,er,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Zi=J($ee,async(e,t,n)=>{try{if(Ve){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Wi(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=Zpe({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(jn(e,kn(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Nn(`folder-config-put`))}q(t,200,Yee,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Qi(e,n,r,i){if(!n)return!1;let a=e===``?`.ok/templates/${n}`:`${e.replace(/\/$/,``)}/.ok/templates/${n}`,o=t.documents.get(a);return o&&yL(o)?(xL(i,new bL({file:`${a}.md`}),r),!0):!1}function $i(e,n,r){let i=t.documents.get(e);return i&&yL(i)?(xL(r,new bL({file:`${e}.md`}),n),!0):!1}let ea=J(M,async(e,t)=>{try{let e=XH(B(r));q(t,200,yn,{templates:e.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:e.truncated},{handler:`templates-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ta(e,t){if(e.method===`GET`)return ra(e,t);if(e.method===`PUT`)return ia(e,t);if(e.method===`POST`)return oa(e,t);if(e.method===`DELETE`)return aa(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let na=e=>{let{frontmatter:t,body:n}=Ye(e),r={};if(t!==``)try{let e=(0,YN.parse)(vt(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{frontmatter:r,body:n}},ra=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ki(r,t,`template-get`))return;let i=Wi(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=qi(o,a,r);if(!s){G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=On(await fs(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,Mee,{template:{name:r,folder:l,scope:u,path:z(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),ia=J(dee,async(e,t,r)=>{try{if(Ve){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let i=r.name;if(!Ki(i,t,`template-put`))return;let a=Wi(r.folder,t,`folder`,`template-put`);if(!a||Qi(a.folderRel,i,`template-put`,t))return;let o=TU({name:i,body:typeof r.body==`string`?r.body:``,frontmatter:Ji(r.frontmatter)});if(!o.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:o.error.code,cause:Error(o.error.message)});return}let s=B(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`),c=!V(s),l=z(a.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=ha(a.folderRel,i),{agentId:f,agentName:p,colorSeed:m,clientName:h}=_n(r),g=await n.getSession(u,f,{displayName:p,colorSeed:m,clientName:h});g.dc.document.transact(()=>{YI(g.dc.document,o.content,`agent`)},g.origin);let _=await xt(u);if(_?.kind===`failure`){wt(t,_.failure,`template-put`);return}if(_?.kind===`divergence`){Tt(t,`template-put`);return}jn(e,kn(`template`,a.folderRel,i),`${c?`template-create`:`template-edit`}: ${l}`),await Nn(`template-put`),q(t,200,d,{path:l,created:c,warnings:o.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),aa=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ki(r,t,`template-delete`))return;let i=Wi(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=xX({agentId:a.get(`agentId`)??void 0,agentName:a.get(`agentName`)??void 0,colorSeed:a.get(`colorSeed`)??void 0,clientName:a.get(`clientName`)??void 0,clientVersion:a.get(`clientVersion`)??void 0,label:a.get(`label`)??void 0,summary:a.get(`summary`)??void 0},xe);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Qi(i.folderRel,r,`template-delete`,t))return;await zt([ha(i.folderRel,r)],`deleted-upstream`);let s=dme({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!s.ok){let e=s.error.code===`WRITE_ERROR`||s.error.code===`UNLINK_FAILED`||s.error.code===`BAD_PROJECT_DIR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:s.error.code,cause:Error(s.error.message)});return}s.existed&&(jn(o,kn(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Nn(`template-delete`)),q(t,200,Be,{existed:s.existed,path:s.path},{handler:`template-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),oa=J(Oee,async(e,t,n)=>{try{let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Ki(n.fromName,t,`template-move`)||!Ki(n.toName,t,`template-move`))return;let r=Wi(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Wi(n.toFolder,t,`folder`,`template-move`);if(!i||Qi(r.folderRel,n.fromName,`template-move`,t))return;await zt([ha(r.folderRel,n.fromName)],`renamed`);let a=await fme({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await XQ(F,e,t);return n||YQ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=qi(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){G(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}let o=null;if(n.body!==void 0||n.frontmatter!==void 0){let e;if(typeof n.body==`string`)e=n.body;else try{e=Mn(H(B(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=ume({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Ji(n.frontmatter)});t.ok||(o=t.error)}}if(jn(e,kn(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Nn(`template-move`),fe?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,Fee,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`});function sa(e,t,n){return!e||e.length>64||!Xt.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function ca(e,t,n){let r=Pe.safeParse(e??`project`);return r.success?r.data:(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let la=Se??$o();function ua(e){return B(e===`global`?la:r,`.ok`,`skills`)}let da=Qq.project;function fa(){if(!F)return null;let e=[],t=null;for(let n of Qt){let r=br[n];if(!r)continue;let i=B(F,...r.split(`/`),da);V(B(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=B(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:z(F,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function pa(){let e=fa();if(!e)return null;let t;try{let{frontmatter:n}=na(H(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:da,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function ma(e,t,n){return eJ(e)?(G(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is a built-in skill managed by OpenKnowledge and can't be edited, renamed, or deleted.`,{handler:n}),!0):!1}function ha(e,t){return`${Vr}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function ga(e){return e===`navigation`||e===`relevance`?e:void 0}function _a(e,t){return z(t===`global`?la:r,e).split(/[\\/]/).filter(Boolean).join(`/`)}function va(e){return e===`global`?la:F}async function ya(e,t){let n=await kW(e,t);return vY(t,e,Qt),n!==null}function ba(e,t){let n=[];if(!V(e))return{skills:n,truncated:!1};let r;try{r=Uo(e,{withFileTypes:!0})}catch(r){return U(`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()||!Xt.test(a.name))continue;if(n.length>=500){i=!0;break}let r=B(e,a.name,`SKILL.md`);if(!V(r))continue;let o,s;try{let{frontmatter:e}=na(H(r,`utf-8`));typeof e.description==`string`&&(o=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(s=e.version)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:_a(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let xa=J(M,async(e,t)=>{try{let e=ba(ua(`project`),`project`),n=ba(ua(`global`),`global`),r=F?EW(F).skills:{},i=EW(la).skills,a=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=Rhe(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),o=e.skills.some(e=>e.name===da)?null:pa();q(t,200,wee,{skills:[...a(e,r),...a(n,i),...o?[o]:[]],truncated:e.truncated||n.truncated},{handler:`skills-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function Sa(e,t){if(e.method===`GET`)return Oa(e,t);if(e.method===`PUT`)return ka(e,t);if(e.method===`POST`)return ja(e,t);if(e.method===`DELETE`)return Aa(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Ca=I({managed:En().nullable(),importable:Wr().int().nonnegative()}),wa=()=>({managed:F?qJ(F)?.manageEditorSkills??null:null,importable:F?Hhe({projectDir:F,skillsRoot:ua(`project`)}):0}),Ta=J(M,async(e,t)=>{if(!F){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Ca,wa(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),Ea=J(I({manageEditorSkills:En()}),async(e,t,n)=>{if(!F){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await JJ(F,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await PY({projectDir:F,skillsRoot:ua(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}q(t,200,Ca,wa(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function Da(e,t){if(e.method===`GET`)return Ta(e,t);if(e.method===`PUT`)return Ea(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let Oa=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!sa(r,t,`skill-get`))return;let i=ca(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===da&&i===`project`){let e=fa();if(e){let{frontmatter:n,body:a}=na(await fs(e.skillMd,`utf-8`));q(t,200,ue,{skill:{name:r,scope:i,path:e.relPath,frontmatter:{name:typeof n.name==`string`?n.name:r,description:typeof n.description==`string`?n.description:``},body:a,files:bY(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=ua(i),o=B(a,r,`SKILL.md`);if(!V(o)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${r}" not found in ${i} scope.`});return}let{frontmatter:s,body:c}=na(await fs(o,`utf-8`));q(t,200,ue,{skill:{name:r,scope:i,path:_a(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:bY(B(a,r))}},{handler:`skill-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),ka=J(nee,async(e,t,r)=>{try{let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!sa(r.name,t,`skill-put`)||ma(r.name,t,`skill-put`))return;let i=fU({name:r.name,body:typeof r.body==`string`?r.body:``,frontmatter:{name:r.frontmatter.name,description:r.frontmatter.description}});if(!i.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:i.error.code,cause:Error(i.error.message)});return}let a=ua(r.scope),o=B(a,r.name,`SKILL.md`),s=!V(o),c=z(a,o).split(/[\\/]/).filter(Boolean).join(`/`),l=Un(r.scope,r.name);if($i(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=_n(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{YI(m.dc.document,i.content,`agent`)},m.origin);let h=await xt(l);if(h?.kind===`failure`){wt(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){Tt(t,`skill-put`);return}r.scope===`project`&&(jn(e,kn(`skill`,``,r.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Nn(`skill-put`)),fe?.(`files`),q(t,200,aee,{path:c,created:s,warnings:i.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),Aa=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!sa(r,t,`skill-delete`)||ma(r,t,`skill-delete`))return;let i=ca(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=ua(i),o=n.searchParams,s=xX({agentId:o.get(`agentId`)??void 0,agentName:o.get(`agentName`)??void 0,colorSeed:o.get(`colorSeed`)??void 0,clientName:o.get(`clientName`)??void 0,clientVersion:o.get(`clientVersion`)??void 0,label:o.get(`label`)??void 0,summary:o.get(`summary`)??void 0},xe);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await zt([Un(i,r)],`deleted-upstream`);let c=rme({skillsRoot:a,name:r});if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(jn(s,kn(`skill`,``,r),`skill-delete: ${c.path}`),await Nn(`skill-delete`)),fe?.(`files`));let l=va(i);l&&await ya(l,r),q(t,200,Mte,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),ja=J(v,async(e,t,n)=>{try{let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!sa(n.fromName,t,`skill-move`)||!sa(n.toName,t,`skill-move`)||ma(n.fromName,t,`skill-move`)||ma(n.toName,t,`skill-move`))return;let r=ua(n.scope);await zt([Un(n.scope,n.fromName)],`renamed`);let i=await ime({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await XQ(F,e,t);return n||YQ(e,t),n}});if(!i.ok){if(i.error.code===`SKILL_NOT_FOUND`){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:i.error.message});return}if(i.error.code===`SKILL_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,i.error.message,{handler:`skill-move`,detail:i.error.code});return}let e=i.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:i.error.code,cause:Error(i.error.message)});return}let a=null,o=B(r,n.toName,`SKILL.md`),s=``,c=``;try{let e=na(H(o,`utf-8`));s=e.body,typeof e.frontmatter.description==`string`&&(c=e.frontmatter.description)}catch{}let l=typeof n.body==`string`?n.body:s,u=n.frontmatter===void 0?c:n.frontmatter.description,d=eme({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{Ia(r,n.fromName,n.toName)}catch(e){U(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let f=_a(B(r,n.fromName),n.scope),p=_a(B(r,n.toName),n.scope);n.scope===`project`&&(jn(e,kn(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Nn(`skill-move`));let m=va(n.scope);if(m){let e=await kW(m,n.fromName);if(e){let t=uY(e.hosts);vY(n.fromName,m,t);let i=_Y(B(r,n.toName),n.toName,m,t);await OW(m,n.toName,{...e,hosts:i})}}if(fe?.(`files`),a){let e=a.code===`WRITE_ERROR`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:a.code,cause:Error(a.message)});return}q(t,200,rte,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function Ma(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Na(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Pa(e,t){let n=t.replace(/\.md$/i,``);return`${A(e).replace(/\/SKILL$/,``)}/${n}`}function Fa(e,t){let n=B(e,t,`references`);if(!V(n))return[];let r=[],i=(e,t)=>{for(let n of Uo(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(B(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}function Ia(e,t,n){if(!P)return;let r=(e,t,n)=>{let r;try{r=H(n,`utf-8`)}catch{P.deleteDocument(e),de?.deleteDocument(e);return}P.renameDocument(e,t,r),de?.renameDocument(e,t,r)};r(A(t),A(n),B(e,n,`SKILL.md`));for(let i of Fa(e,n))r(Pa(t,i),Pa(n,i),B(e,n,i));fe?.(`backlinks`),fe?.(`graph`)}let La=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!sa(r,t,`skill-file-get`))return;let i=ca(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===da&&i===`project`?fa():null,s=o&&a===`SKILL.md`?`reference`:Ma(a);if(s===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let c=o?o.dir:B(ua(i),r),l=B(c,a);if(l!==c&&!l.startsWith(`${c}${Do}`)){G(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let u=l,d=a;if(!V(u)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Ir.map(t=>`${e[1]}${t}`).find(e=>e!==a&&V(B(c,e))):void 0;if(n===void 0){G(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}d=n,u=B(c,n)}let f=await fs(u);if(f.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,k,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Ra=J(Ote,async(e,t,r)=>{try{let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!sa(r.name,t,`skill-file-put`)||ma(r.name,t,`skill-file-put`))return;let i=Ma(r.path);if(i===null){G(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(r.content,`utf-8`)>262144){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let a=ua(r.scope);if(!V(B(a,r.name,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${r.name}" before adding bundle files.`});return}let o=r.path.replace(/\\/g,`/`),s=Na(r.scope,i,o),c;if(s){let e=Pa(r.name,o);if($i(e,`skill-file-put`,t))return;if(c=!V(B(a,r.name,o)),c&&mU(B(a,r.name))>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${r.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:i,agentName:s,colorSeed:l,clientName:u}=_n(r),d=await n.getSession(e,i,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{YI(d.dc.document,r.content,`agent`)},d.origin);let f=await xt(e);if(f?.kind===`failure`){wt(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){Tt(t,`skill-file-put`);return}}else{let e=tme({skillsRoot:a,name:r.name,relPath:o,content:r.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}r.scope===`project`&&(jn(e,kn(`skill`,``,r.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${r.name}/${o}`),await Nn(`skill-file-put`)),fe?.(`files`),q(t,200,Dt,{path:o,created:c,kind:i,content:s},{handler:`skill-file-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),za=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!sa(r,t,`skill-file-delete`)||ma(r,t,`skill-file-delete`))return;let i=ca(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=Ma(a);if(o===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let s=xX({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},xe);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=ua(i);Na(i,o,a)&&await zt([Pa(r,a)],`deleted-upstream`);let l=nme({skillsRoot:c,name:r,relPath:a});if(!l.ok){let e=l.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:l.error.code,cause:Error(l.error.message)});return}l.existed&&i===`project`&&(jn(s,kn(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Nn(`skill-file-delete`)),l.existed&&fe?.(`files`),q(t,200,hee,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function Ba(e,t){if(e.method===`GET`)return La(e,t);if(e.method===`PUT`)return Ra(e,t);if(e.method===`DELETE`)return za(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Va=J(ae,async(e,t,n)=>{try{let e=ua(n.scope);if(!sa(n.name,t,`skill-install`)||ma(n.name,t,`skill-install`))return;if(n.scope===`project`&&!F){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=va(n.scope),i=B(e,n.name);if(!V(i)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}let a=pY(i,n.name);if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${a.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let o=n.scope===`global`?n.targets?Qt.filter(e=>n.targets?.some(t=>t===e)):[...Qt]:n.targets===void 0?mY(r,LY(r)??void 0):Qt.filter(e=>n.targets?.some(t=>t===e)),s=[],c=[];o.length===0&&n.targets===void 0&&(s.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),c.push(`no-targets`)),a.hasScripts&&(s.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),c.push(`scripts-present`));let l=uY(EW(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&vY(n.name,r,l);let u=_Y(i,n.name,r,o);u.length===0?await kW(r,n.name):await OW(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),q(t,200,ste,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Ha=J(ee,async(e,t,n)=>{try{if(!sa(n.name,t,`skill-uninstall`)||ma(n.name,t,`skill-uninstall`))return;let e=va(n.scope);if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await ya(e,n.name);fe?.(`files`),q(t,200,See,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Ua(e,t){if(e.method===`GET`)return Wa(e,t);if(e.method===`PUT`)return Ga(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Wa=J(M,async(e,t)=>{try{let e=F?LY(F):null;q(t,200,eee,{targets:mY(F??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){G(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}),Ga=J(St,async(e,t,n)=>{try{if(!F){G(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=n.targets,r=new Set(e),i=mY(F,LY(F)??void 0),a=ua(`project`);await Khe(F,e);let{reprojected:o,bundleHosts:s}=await Whe({projectDir:F,skillsRoot:a,targets:e});fe?.(`files`),q(t,200,Ite,{targets:e,reprojected:o,bundleHosts:s,removedFrom:i.filter(e=>!r.has(e))},{handler:`skill-targets-put`})}catch(e){G(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`}),Ka=J(ft,async(e,t,n)=>{try{let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!sa(n.name,t,`skill-restore`)||ma(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let i=w?.current;if(!i){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let a=await X_e({shadow:i,contentDir:r,contentRoot:se??`.`,name:n.name,version:n.version});if(!a.ok){let[e,n]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[a.code];G(t,e,n,a.error,{handler:`skill-restore`,detail:a.code});return}let o=[],s=pY(B(r,`.ok`,`skills`,n.name),n.name);s.ok||o.push(`Restored, but the skill no longer validates: ${s.errors.join(` `)}`),o.push("Run `install` to push the restored version to your editors."),jn(e,kn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Nn(`skill-restore`),fe?.(`files`),q(t,200,_e,{name:n.name,version:n.version,restoredFiles:a.restoredFiles,warnings:o},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),qa=J(De,async(e,t,r)=>{try{let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!sa(r.name,t,`skill-update`)||ma(r.name,t,`skill-update`))return;if(!xY(r.name)){G(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(r.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let i=Ihe(r.name);if(i===null||i.version===void 0){G(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let a=B(ua(`project`),r.name,`SKILL.md`);if(!V(a)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let o;try{o=SY(H(a,`utf-8`))}catch{}let s,c=w?.current;if(c)try{let e=ie?.()??`main`;s=(await aB(c,se??`.`,[Xz],e,`Before updating ${r.name} (${o??`unversioned`} → ${i.version})`)).checkpointRef}catch(e){U(`skills`).warn({err:e,skill:r.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=Un(`project`,r.name);if($i(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=_n(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{YI(m.dc.document,i.content,`agent`)},m.origin);let h=await xt(l);if(h?.kind===`failure`){wt(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){Tt(t,`skill-update`);return}jn(e,kn(`skill`,``,r.name),`skill-pack-update: ${r.name} (${o??`unversioned`} → ${i.version})`),await Nn(`skill-update`),fe?.(`files`),q(t,200,bee,{name:r.name,version:i.version,...o===void 0?{}:{previousVersion:o},...s===void 0?{}:{checkpointRef:s}},{handler:`skill-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Ja(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])=>Kr({kind:`folder`,path:e,modifiedTs:t}))}function Ya(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 Xa(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Za(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 Qa(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function $a(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function eo(e,t,n,r){let i=r.documents.filter(e=>!m(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Ne?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Ne.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Ne.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Fe?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Ne.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function to(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`?Ya(e.document.content,t):void 0}}async function no(e){let t=performance.now();if(fo())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await po(),i=await eo(e.query,e.intent,e.semanticParam,n),a=gee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>to(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},Ame({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 ro(){let e=ua(`project`);if(!V(e))return[];let t;try{t=Uo(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!Xt.test(r.name))continue;let t=B(e,r.name,`SKILL.md`);try{let e=Yo(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function io(){let e=[];for(let t of ro()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=na(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(Kr({kind:`page`,path:Un(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function ao(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let oo=new Map;async function so(){let e=[],t=[],n=new Set;for(let[r,i]of s()){if(ZI(r)||QI(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(Kr({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=ao(i),o=oo.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await fs(i.canonicalPath,`utf-8`)}catch(e){l=!0,console.warn(`[search] Failed to read ${r}:`,e)}if(!l)try{c=_B(s,r)}catch(e){console.warn(`[search] Failed to extract title for ${r}:`,e)}let u=Kr({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||oo.set(r,{key:a,doc:u}),e.push(u)}for(let e of oo.keys())n.has(e)||oo.delete(e);let r=Gve(),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),U(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),Nve().add(1)),{documents:[...e,...io(),...i,...Ja([...e,...i])],truncated:a}}function co(){return ro().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function lo(){return f?`gen:${f()}|skills${co()}`:`${[...s()].filter(([e])=>!ZI(e)&&!QI(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${ao(t)}`).join(``)}|skills${co()}`}let uo=Ee===void 0;Ee?.then(()=>{uo=!0},e=>{uo=!0,vQ.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function fo(){return!uo}async function po(){let e=`${r}${F??``}`,t=lo(),n=ZQ.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 i=so().then(({documents:e,truncated:t})=>({corpus:T(e),truncated:t}));ZQ.set(e,{fingerprint:t,pending:i});try{let n=await i;return ZQ.get(e)?.pending===i&&ZQ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw ZQ.get(e)?.pending===i&&ZQ.delete(e),t}}function mo(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{po().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}mo();async function ho(e,t){if(e.method===`GET`)return go(e,t);if(e.method===`POST`)return vo(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let go=J(M,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`limit`),i=n.searchParams.get(`query`)??``,a=Xa(n.searchParams.get(`intent`)),o=ga(n.searchParams.get(`ranking`)),s=Za(n.searchParams.get(`scope`)??n.searchParams.get(`scopes`)),c=Qa(n.searchParams.get(`semantic`)),l=$a(n.searchParams.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{q(t,200,ti,await no({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),vo=J(wte,async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Xa(n.intent),a=ga(n.ranking),o=Za(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Qa(n.semantic),l=$a(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{q(t,200,ti,await no({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),yo=J(M,async(e,t)=>{try{q(t,200,cee,{...await jJ($o())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>eZ(e,t,{handler:`skill-install-state`})});async function xo(e,t){if(eZ(e,t,{handler:`handoff`}))try{await che(e,t,{contentDir:r,platform:process.platform,isSchemeRegistered:ot.probeWithCache})}catch(e){t.headersSent||(vQ.error({err:e},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function R(e,t){if(eZ(e,t,{handler:`spawn-cursor`}))try{await lW(e,t,{contentDir:r,platform:process.platform})}catch(e){t.headersSent||(vQ.error({err:e},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let To=J(Hr,async(e,t,n)=>{try{if(!F){gq(`no-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`no-remote`},{handler:fq});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!pq(e,n.kind)){gq(`invalid-path`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`invalid-path`},{handler:fq});return}let i=Sq(F);if(i===null){if(Oq(F).kind===`no-remote`){gq(`no-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`no-remote`},{handler:fq});return}gq(`detached-head`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`detached-head`},{handler:fq});return}let a=Oq(F);if(a.kind===`no-remote`){gq(`no-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`no-remote`},{handler:fq});return}if(a.kind===`non-github`||a.host!==`github.com`){gq(`non-github-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`non-github-remote`},{handler:fq});return}if(!Mq(F,i)){gq(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,ei,{ok:!1,error:`branch-not-on-origin`,branch:i},{handler:fq});return}let o=WQ(F,r);if(o===null)throw Error(`content dir is not contained within the project dir`);let s=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;o!==``&&s&&U(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=mq(a.owner,a.repo,i,n.docPath);else{let e=n.folderPath===``?o:n.folderPath;c=hq(a.owner,a.repo,i,e)}let l=`https://openknowledge.ai/d/${dne(c)}`,u=await vq(F,i,o===``?e:e===``?o:`${o}/${e}`,n.kind);gq(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,ei,{ok:!0,shareUrl:l,sharedUrl:c,branch:i,freshness:u},{handler:fq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:fq,cause:e})}},{handler:fq,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:fq})}),Eo=J(M,async(e,t)=>{try{if(!F){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:EX});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(!ite(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:EX});return}if(!TX(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:EX});return}q(t,200,Xee,await lge(F,r,i,a),{handler:EX})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:EX,cause:e})}},{handler:EX,method:`GET`,skipBodyParse:!0}),Oo=J(Tte,async(e,t,n)=>{try{if(!F){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Jq});return}if(!TX(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:Jq});return}let e=WQ(F,r);if(e===null)throw Error(`content dir is not contained within the project dir`);let i=e===``?n.path:n.path===``?e:`${e}/${n.path}`;q(t,200,_ee,await Zq(F,n.branch,i,n.kind),{handler:Jq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Jq,cause:e})}},{handler:Jq,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Jq})}),ko=J(qee,async(e,t,n)=>{if(xX(n,xe).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:DX});return}if(!F){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:DX});return}try{q(t,200,Iee,await hi(()=>mge(F,n.branch,{fastForward:n.fastForward===!0})),{handler:DX})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:DX,cause:e})}},{handler:DX,method:`POST`});async function Ao(e){let[t,...n]=ye,r=[...n,...e];return await new Promise((e,n)=>{let i=_o(t,r,nV({...Qr,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},Iq),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 ${Iq}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=qq(Buffer.concat(c).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let jo=J(M,async(e,t)=>{if(!qe.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:Nq,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ao([`share`,`owners`,`--json`]),n=Bq(zq(e));Kq(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,kte,n,{handler:Nq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Nq,cause:e})}finally{qe.release(`/api/share/publish/owners`)}},{handler:Nq,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>eZ(e,t,{handler:Nq})}),Mo=J(M,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!Rq(r)||!Lq(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:Pq});return}if(!qe.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:Pq,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ao([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Hq(zq(e));Kq(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,Ree,n,{handler:Pq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Pq,cause:e})}finally{qe.release(`/api/share/publish/name-check`)}},{handler:Pq,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>eZ(e,t,{handler:Pq})}),No=J(fee,async(e,t,n)=>{if(!F){Kq(`publish-create`,`no-project`),q(t,200,te,{ok:!1,error:`no-project`},{handler:Fq});return}if(!Rq(n.owner)||!Lq(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:Fq});return}if(!qe.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:Fq,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,F,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Ao(e),i=Gq(zq(r));Kq(`publish-create`,i.ok?`ok`:i.error),i.ok&&ve?.()?.refreshRemote().catch(()=>{}),q(t,200,te,i,{handler:Fq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Fq,cause:e})}finally{qe.release(`/api/share/publish`)}},{handler:Fq,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Fq})}),Fo=J(jte,async(e,t,n)=>{try{let e=U(`renderer`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,mee,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`client-logs`})}),Io=F?gH(F):null;async function Lo(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=e.headers.host,r={collabUrl:n?`ws://${n}/collab`:null,previewUrl:null,port:Io?Oi(Io)?.port??0:0,singleFile:Ve};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,fte,r,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let zo=`local-op-embeddings-set-key`,Bo=`local-op-embeddings-clear-key`,Vo=`/api/local-op/embeddings`,Ho=J(uee,async(e,t,n)=>{if(!qe.tryAcquire(Vo)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:zo,extraHeaders:{"Retry-After":`5`}});return}try{await new GU(Ie).set(n.key),q(t,200,Gt,{keyPresent:!0},{handler:zo,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:zo,cause:e})}finally{qe.release(Vo)}},{handler:zo,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:zo})}),Wo=J(M,async(e,t)=>{if(!qe.tryAcquire(Vo)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Bo,extraHeaders:{"Retry-After":`5`}});return}try{await KU(Ie),q(t,200,Gt,{keyPresent:!1},{handler:Bo,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Bo,cause:e})}finally{qe.release(Vo)}},{handler:Bo,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Bo})}),Ko=J(M,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Ne){let t=Ne.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let o=await new GU(Ie).get(),s=process.env.OK_EMBEDDINGS_API_KEY??null,c=o?`file`:s?`env`:null,l=c!==null,u=o??s,d=u&&u.length>=8?u.slice(-4):null,f=0;for(let[e]of a())!ZI(e)&&!QI(e)&&!m(e)&&(f+=1);q(t,200,Vee,{enabled:e,keyPresent:l,keySource:c,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0});async function qo(e,t){let n=Le?.()??u;try{return(await Mt(e,WK(r,n,{docName:t,onProblem:e=>vQ.warn({problem:e,docName:t},`[lint] native config problem`)}),t)).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1}))}catch(e){return vQ.warn({err:e,docName:t},`[lint] advisory lint pass failed post-write; omitting advisories`),[]}}let Jo=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!QQ(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let i=Le?.()??u,a=[],o=HK(r,n??void 0,e=>a.push(e));q(t,200,vr,{effective:UK(i,o),configFile:o?.file??null,configProblems:a},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Xo=J(Pee,async(e,t,n)=>{let i;try{i=iq(B(r),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(i.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${i.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}try{let e=Le?.()??u,n=[],i=HK(r,void 0,e=>n.push(e));q(t,200,vr,{effective:UK(e,i),configFile:i?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),es=e=>{let n=e.replace(/\.(md|mdx)$/i,``),r=t.documents.get(n);return r===void 0?null:r.getText(`source`).toString()},ts=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!QQ(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let i=VQ(r,n);if(i===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let a=Le?.()??u;q(t,200,ze,await GK({projectDir:F??r,contentDir:r,baseConfig:a,docRelPath:i,liveSourceFor:es}),{handler:`lint`})}catch(e){if(e instanceof fG){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),ns=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),i=n===null||n===``?void 0:n;if(i!==void 0&&!kQ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let a=Le?.()??u;q(t,200,Ge,await qK({projectDir:F??r,contentDir:r,baseConfig:a,targetPath:i,liveSourceFor:es}),{handler:`lint-audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),rs=J(jee,async(t,i,a)=>{try{let t=MQ(a.docName,i,`lint-fix`);if(t===null)return;let o=gt(t),s=xX(a,xe);if(s.kind===`invalid-summary`){G(i,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=s.kind===`anonymous`?`principal-anonymous`:s.writerId,l=s.kind===`anonymous`?`Anonymous`:s.displayName,d=s.kind===`anonymous`?c:s.colorSeed,f=s.kind===`agent`?s.clientName:void 0;if(ZI(o)||QI(o)){G(i,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`lint-fix`});return}let p=VQ(r,o);if(p===null){G(i,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}NQ(B(r,p),r);let m=Le?.()??u,{stored:h}=Sn(s.summary),g=await n.getSession(o,c,{displayName:l,colorSeed:d,clientName:f}),_=g.dc.document.getText(`source`).toString(),{cfg:v,before:y,fixed:b}=await KK({projectDir:F??r,contentDir:r,baseConfig:m,docRelPath:p,source:_}),x=y,S;if(b!==_){try{let t=pn(f),n=cn[t]??Wn(d??c);he?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:o,mode:`writing`,ts:Date.now()}),g.dc.document.transact(()=>{jL(g.dc.document,b,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:o}:void 0)},g.origin),s.kind!==`anonymous`&&Oz(o,c,l,d,void 0,s.kind===`agent`?vn({clientName:s.clientName,clientVersion:s.clientVersion,label:s.label}):s.actor,h)}finally{he?.touchMode(c,`idle`)}let t=await xt(o);if(t?.kind===`failure`){wt(i,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Tt(i,`lint-fix`);return}bt(o,`lint-fix`);try{x=await Mt(g.dc.document.getText(`source`).toString(),v,p)}catch(e){S=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,vQ.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),x=y}}let C=x.filter(e=>e.severity===`error`).length,w=x.length-C;q(i,200,Dee,{file:p,fixedCount:Math.max(0,y.length-x.length),diagnostics:x,errorCount:C,warningCount:w,...S?{warning:S}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof fG){G(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof bL){xL(i,e,`lint-fix`);return}if(e instanceof TL){EL(i,e,`lint-fix`);return}if(e instanceof ML){G(i,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}vQ.error({err:e},`[lint-fix] handler failed`),G(i,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),is=`link-preview`,as=new t_e({cacheDir:Ve?null:B(F??r,`.ok`,`local`,`link-previews`)}),os=null,ss=()=>(os??=as.init(),os),cs=He??UX;async function ls(e){let t=await cs(e);return t.ok?{ok:!0,metadata:await $ge({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:cs})}:{ok:!1,reason:t.reason}}let us=()=>{try{return We?.()===!0}catch{return!1}},ds={"/api/config":Lo,"/api/asset":Sr,"/api/asset-text":Tr,"/api/document":Rn,"/api/documents":zn,"/api/backlinks":Vn,"/api/backlink-counts":Hn,"/api/link-preview":J(mte,async(e,t,n)=>{try{if(!us()){vQ.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Or,{ok:!1,reason:`disabled`},{handler:is});return}await ss();let e=!1,r=await as.load(n.url,()=>(e=!0,ls(n.url)));as.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};vQ.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,Or,i,{handler:is})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:is,cause:e})}},{handler:is,method:`POST`,preBodyGate:(e,t)=>{let n=i_e({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:is}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:is}),!1)}}),"/api/forward-links":Gn,"/api/link-graph":Kn,"/api/dead-links":Yn,"/api/orphans":qn,"/api/hubs":Jn,"/api/tags":Hi,"/api/pages":zr,"/api/folder-config":Yi,"/api/template":ta,"/api/templates":ea,"/api/skill":Sa,"/api/skill-file":Ba,"/api/skills":xa,"/api/skills/management":Da,"/api/skill/install":Va,"/api/skill/uninstall":Ha,"/api/skill/restore":Ka,"/api/skill/update":qa,"/api/skill-targets":Ua,"/api/search":ho,"/api/semantic-status":Ko,"/api/lint/config":Jo,"/api/lint/markdownlint-config":Xo,"/api/lint":ts,"/api/lint/audit":ns,"/api/lint/fix":rs,"/api/suggest-links":Br,"/api/page-headings":jr,"/api/create-page":Dr,"/api/create-folder":kr,"/api/duplicate-path":Ar,"/api/rename-path":Mr,"/api/delete-path":Pr,"/api/trash/cleanup":Fr,"/api/upload":qr,"/api/agent-write":Pn,"/api/agent-write-md":Fn,"/api/frontmatter-patch":In,"/api/agent-patch":Xn,"/api/agent-undo":Zn,"/api/agent-activity":Qn,"/api/agent-burst-diff":tr,"/api/save-version":sr,"/api/history":cr,"/api/rollback":ur,"/api/metrics/reconciliation":fr,"/api/metrics/parse-health":pr,"/api/metrics/agent-presence":gr,"/api/__embed-detect":yr,"/api/server-info":mr,"/api/share/construct-url":To,"/api/share/target-status":Oo,"/api/git/branch-info":Eo,"/api/git/checkout":ko,"/api/share/publish/owners":jo,"/api/share/publish/name-check":Mo,"/api/share/publish":No,"/api/principal":hr,"/api/rescue":Er,"/api/workspace":xr,"/api/sync/status":Mi,"/api/sync/trigger":Ni,"/api/sync/conflicts":Pi,"/api/sync/conflict-content":Ii,"/api/sync/resolve-conflict":Fi,"/api/local-op/clone":ri,"/api/local-op/ok-init":si,"/api/local-op/auth/login":yi,"/api/local-op/auth/status":Si,"/api/local-op/auth/repos":wi,"/api/local-op/auth/signout":Di,"/api/local-op/auth/set-identity":ji,"/api/local-op/embeddings/set-key":Ho,"/api/local-op/embeddings/clear-key":Wo,"/api/installed-agents":Vi,"/api/spawn-cursor":R,"/api/handoff":xo,"/api/install-skill":Bi,"/api/skill/install-state":yo,"/api/seed/plan":Li,"/api/seed/apply":Ri,"/api/seed/packs":zi,"/api/client-logs":Fo};C&&(ds[`/api/test-reset`]=rr,ds[`/api/test-flush-git`]=nr,ds[`/api/test-rescan-backlinks`]=ir,ds[`/api/test-rescan-files`]=or);let ps=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/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/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),ms=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;let r=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};if(gme({ts:Date.now(),url:n,method:e.method??``,ua:r(`user-agent`),origin:r(`origin`),referer:r(`referer`),host:r(`host`),remote:e.socket?.remoteAddress,secChUa:r(`sec-ch-ua`),secChUaMobile:r(`sec-ch-ua-mobile`),secChUaPlatform:r(`sec-ch-ua-platform`),secFetchSite:r(`sec-fetch-site`),secFetchDest:r(`sec-fetch-dest`),secFetchMode:r(`sec-fetch-mode`),secFetchUser:r(`sec-fetch-user`)}),n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!NR(n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${jt.protocol}, ${jt.runtime}, ${jt.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(ps.has(n)||ms.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!lZ(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Ve&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!lZ(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!n.startsWith(`/api/`))return;let i=li.extract(fi.active(),e.headers),a=e.method??`GET`,o=n;n.startsWith(`/api/history/`)?o=`/api/history/:sha`:n.startsWith(`/api/tags/`)?o=`/api/tags/:name`:ds[n]||(o=`/api/*`);let s=UI(),c=Date.now();await fi.with(i,()=>s.startActiveSpan(`HTTP ${a} ${o}`,{kind:Lte.SERVER,attributes:{[kw]:a,[Hw]:o,[BE]:n,[HE]:`http`,[UE]:e.headers[`user-agent`]??``}},async r=>{try{let i=ds[n],o=!1;if(i)o=!0,await i(e,t);else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&(o=!0,await lr(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await Ui(e,t,r))}o||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${a} ${n}`});let s=t.statusCode;r.setAttribute(Vw,s),s>=500&&r.setStatus({code:ci.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:ci.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:o,cause:e}),e}finally{r.end();let e=(Date.now()-c)/1e3;kve().record(e,{[kw]:a,[Hw]:o,[Vw]:t.statusCode})}}))}}}function e$(e){let t=e?.code;return typeof t==`string`?t:void 0}function cye(e){let t;try{t=Uo(e.contentDir,{withFileTypes:!0})}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&aL(n.name,Wt)&&e.basenameIndex.add(n.name)}async function t$(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await ps(i,{withFileTypes:!0})}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=R(i,o.name),s=yB(z(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await us(a)}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await ms(a)}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!bB(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await gs(i)}catch(t){let n=e$(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()&&aL(a,Nr)&&!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()&&aL(a,Nr)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}var n$=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const r$=U(`conflict-storage`);var i$=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=R(gH(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){r$.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){r$.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=So(this.storePath);V(e)||Ro(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};Qo(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){r$.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-DcVL5mrG.mjs`),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=B(this.projectDir),r=B(t,e);if(!bB(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);Qo(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),r$.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await zz(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){r$.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}),r$.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}};function a$(e){let t=e.scheduler??Oe,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 o$(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function s$(e){if(!V(e))return{};let t;try{t=(0,YN.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(!o$(t))return{};let n=t.telemetry;if(!o$(n))return{};let r=n.localSink;return o$(r)?r:{}}function c$(e){return typeof e==`boolean`?e:void 0}function lye(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function l$(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function u$(e){if(o$(e))return lye(e.maxBytes)}function uye(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=s$(tP(`project`,e.projectDir)),n=s$(tP(`project-local`,e.projectDir));if((c$(n.enabled)??c$(t.enabled)??!0)===!1)return null;let r=u$(n.spans)??u$(t.spans)??52428800,i=u$(n.logs)??u$(t.logs)??26214400,a=l$(n.attributeDenylist)??l$(t.attributeDenylist)??hr;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var d$;(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})(d$||={});var dye;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(dye||={});const f$=d$.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),p$=e=>{switch(typeof e){case`undefined`:return f$.undefined;case`string`:return f$.string;case`number`:return Number.isNaN(e)?f$.nan:f$.number;case`boolean`:return f$.boolean;case`function`:return f$.function;case`bigint`:return f$.bigint;case`symbol`:return f$.symbol;case`object`:return Array.isArray(e)?f$.array:e===null?f$.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?f$.promise:typeof Map<`u`&&e instanceof Map?f$.map:typeof Set<`u`&&e instanceof Set?f$.set:typeof Date<`u`&&e instanceof Date?f$.date:f$.object;default:return f$.unknown}},Y=d$.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 m$=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,d$.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()}};m$.create=e=>new m$(e);const h$=(e,t)=>{let n;switch(e.code){case Y.invalid_type:n=e.received===f$.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,d$.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:n=`Unrecognized key(s) in object: ${d$.joinValues(e.keys,`, `)}`;break;case Y.invalid_union:n=`Invalid input`;break;case Y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${d$.joinValues(e.options)}`;break;case Y.invalid_enum_value:n=`Invalid enum value. Expected ${d$.joinValues(e.options)}, received '${e.received}'`;break;case Y.invalid_arguments:n=`Invalid function arguments`;break;case Y.invalid_return_type:n=`Invalid function return type`;break;case Y.invalid_date:n=`Invalid date`;break;case Y.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}"`:d$.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Y.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 Y.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 Y.custom:n=`Invalid input`;break;case Y.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Y.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Y.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,d$.assertNever(e)}return{message:n}};let fye=h$;function g$(){return fye}const _$=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 X(e,t){let n=g$(),r=_$({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===h$?void 0:h$].filter(e=>!!e)});e.common.issues.push(r)}var v$=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 y$;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 y$;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 y$=Object.freeze({status:`aborted`}),b$=e=>({status:`dirty`,value:e}),x$=e=>({status:`valid`,value:e}),S$=e=>e.status===`aborted`,C$=e=>e.status===`dirty`,w$=e=>e.status===`valid`,T$=e=>typeof Promise<`u`&&e instanceof Promise;var E$;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(E$||={});var D$=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 O$=(e,t)=>{if(w$(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 m$(e.common.issues);return this._error=t,this._error}}};function k$(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 A$=class{get description(){return this._def.description}_getType(e){return p$(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:p$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v$,ctx:{common:e.parent.common,data:e.data,parsedType:p$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(T$(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:p$(e)};return O$(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:p$(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return w$(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=>w$(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:p$(e)},r=this._parse({data:e,path:n.path,parent:n});return O$(n,await(T$(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:Y.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 c1({schema:this,typeName:Z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return l1.create(this,this._def)}nullable(){return u1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K$.create(this)}promise(){return s1.create(this,this._def)}or(e){return Y$.create([this,e],this._def)}and(e){return Q$.create(this,e,this._def)}transform(e){return new c1({...k$(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new d1({...k$(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new m1({typeName:Z.ZodBranded,type:this,...k$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new f1({...k$(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return h1.create(this,e)}readonly(){return g1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const pye=/^c[^\s-]{8,}$/i,mye=/^[0-9a-z]+$/,hye=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gye=/^[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,_ye=/^[a-z0-9_-]{21}$/i,vye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yye=/^[-+]?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)?)??$/,bye=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let j$;const xye=/^(?:(?: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])$/,Sye=/^(?:(?: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])$/,Cye=/^(([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]))$/,wye=/^(([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])$/,Tye=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Eye=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,M$=`((\\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])))`,Dye=RegExp(`^${M$}$`);function N$(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 Oye(e){return RegExp(`^${N$(e)}$`)}function kye(e){let t=`${M$}T${N$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Aye(e,t){return!!((t===`v4`||!t)&&xye.test(e)||(t===`v6`||!t)&&Cye.test(e))}function jye(e,t){if(!vye.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 Mye(e,t){return!!((t===`v4`||!t)&&Sye.test(e)||(t===`v6`||!t)&&wye.test(e))}var P$=class e extends A${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f$.string){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.string,received:t.parsedType}),y$}let t=new v$,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:Y.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),X(n,{code:Y.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?X(n,{code:Y.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&X(n,{code:Y.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)bye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`email`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)j$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),j$.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`emoji`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)gye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`uuid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)_ye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`nanoid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)pye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`cuid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)mye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`cuid2`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)hye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`ulid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),X(n,{validation:`url`,code:Y.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),X(n,{validation:`regex`,code:Y.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),X(n,{code:Y.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),X(n,{code:Y.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?kye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Dye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Oye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?yye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`duration`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Aye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`ip`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?jye(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`jwt`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Mye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`cidr`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Tye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Eye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64url`,code:Y.invalid_string,message:r.message}),t.dirty()):d$.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Y.invalid_string,...E$.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...E$.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...E$.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...E$.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...E$.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...E$.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...E$.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...E$.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...E$.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...E$.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...E$.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...E$.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...E$.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...E$.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,...E$.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,...E$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...E$.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...E$.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...E$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...E$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...E$.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...E$.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...E$.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...E$.errToObj(t)})}nonempty(e){return this.min(1,E$.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}};P$.create=e=>new P$({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...k$(e)});function Nye(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 F$=class e extends A${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)!==f$.number){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.number,received:t.parsedType}),y$}let t,n=new v$;for(let r of this._def.checks)r.kind===`int`?d$.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),X(t,{code:Y.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),X(t,{code:Y.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),X(t,{code:Y.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Nye(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),X(t,{code:Y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),X(t,{code:Y.not_finite,message:r.message}),n.dirty()):d$.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,E$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E$.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:E$.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:E$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:E$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:E$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:E$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E$.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:E$.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:E$.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:E$.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`&&d$.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)}};F$.create=e=>new F$({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...k$(e)});var I$=class e extends A${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)!==f$.bigint)return this._getInvalidInput(e);let t,n=new v$;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),X(t,{code:Y.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),X(t,{code:Y.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),X(t,{code:Y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):d$.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.bigint,received:t.parsedType}),y$}gte(e,t){return this.setLimit(`min`,e,!0,E$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E$.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:E$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:E$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:E$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:E$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E$.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}};I$.create=e=>new I$({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...k$(e)});var L$=class extends A${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f$.boolean){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.boolean,received:t.parsedType}),y$}return x$(e.data)}};L$.create=e=>new L$({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...k$(e)});var R$=class e extends A${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f$.date){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.date,received:t.parsedType}),y$}if(Number.isNaN(e.data.getTime()))return X(this._getOrReturnCtx(e),{code:Y.invalid_date}),y$;let t=new v$,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:Y.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),X(n,{code:Y.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):d$.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:E$.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:E$.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)}};R$.create=e=>new R$({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...k$(e)});var z$=class extends A${_parse(e){if(this._getType(e)!==f$.symbol){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.symbol,received:t.parsedType}),y$}return x$(e.data)}};z$.create=e=>new z$({typeName:Z.ZodSymbol,...k$(e)});var B$=class extends A${_parse(e){if(this._getType(e)!==f$.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.undefined,received:t.parsedType}),y$}return x$(e.data)}};B$.create=e=>new B$({typeName:Z.ZodUndefined,...k$(e)});var V$=class extends A${_parse(e){if(this._getType(e)!==f$.null){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.null,received:t.parsedType}),y$}return x$(e.data)}};V$.create=e=>new V$({typeName:Z.ZodNull,...k$(e)});var H$=class extends A${constructor(){super(...arguments),this._any=!0}_parse(e){return x$(e.data)}};H$.create=e=>new H$({typeName:Z.ZodAny,...k$(e)});var U$=class extends A${constructor(){super(...arguments),this._unknown=!0}_parse(e){return x$(e.data)}};U$.create=e=>new U$({typeName:Z.ZodUnknown,...k$(e)});var W$=class extends A${_parse(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.never,received:t.parsedType}),y$}};W$.create=e=>new W$({typeName:Z.ZodNever,...k$(e)});var G$=class extends A${_parse(e){if(this._getType(e)!==f$.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.void,received:t.parsedType}),y$}return x$(e.data)}};G$.create=e=>new G$({typeName:Z.ZodVoid,...k$(e)});var K$=class e extends A${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==f$.array)return X(t,{code:Y.invalid_type,expected:f$.array,received:t.parsedType}),y$;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(X(t,{code:e?Y.too_big:Y.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&&(X(t,{code:Y.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&&(X(t,{code:Y.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 D$(t,e,t.path,n)))).then(e=>v$.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new D$(t,e,t.path,n)));return v$.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:E$.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:E$.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:E$.toString(n)}})}nonempty(e){return this.min(1,e)}};K$.create=(e,t)=>new K$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...k$(t)});function q$(e){if(e instanceof J$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=l1.create(q$(r))}return new J$({...e._def,shape:()=>t})}else if(e instanceof K$)return new K$({...e._def,type:q$(e.element)});else if(e instanceof l1)return l1.create(q$(e.unwrap()));else if(e instanceof u1)return u1.create(q$(e.unwrap()));else if(e instanceof $$)return $$.create(e.items.map(e=>q$(e)));else return e}var J$=class e extends A${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=d$.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f$.object){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.object,received:t.parsedType}),y$}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof W$&&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 D$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof W$){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&&(X(n,{code:Y.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 D$(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=>v$.mergeObjectSync(t,e)):v$.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return E$.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:E$.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of d$.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 d$.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return q$(this)}partial(t){let n={};for(let e of d$.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 d$.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof l1;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return i1(d$.objectKeys(this.shape))}};J$.create=(e,t)=>new J$({shape:()=>e,unknownKeys:`strip`,catchall:W$.create(),typeName:Z.ZodObject,...k$(t)}),J$.strictCreate=(e,t)=>new J$({shape:()=>e,unknownKeys:`strict`,catchall:W$.create(),typeName:Z.ZodObject,...k$(t)}),J$.lazycreate=(e,t)=>new J$({shape:e,unknownKeys:`strip`,catchall:W$.create(),typeName:Z.ZodObject,...k$(t)});var Y$=class extends A${_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 m$(e.ctx.common.issues));return X(t,{code:Y.invalid_union,unionErrors:n}),y$}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 m$(e));return X(t,{code:Y.invalid_union,unionErrors:i}),y$}}get options(){return this._def.options}};Y$.create=(e,t)=>new Y$({options:e,typeName:Z.ZodUnion,...k$(t)});const X$=e=>e instanceof n1?X$(e.schema):e instanceof c1?X$(e.innerType()):e instanceof r1?[e.value]:e instanceof a1?e.options:e instanceof o1?d$.objectValues(e.enum):e instanceof d1?X$(e._def.innerType):e instanceof B$?[void 0]:e instanceof V$?[null]:e instanceof l1?[void 0,...X$(e.unwrap())]:e instanceof u1?[null,...X$(e.unwrap())]:e instanceof m1||e instanceof g1?X$(e.unwrap()):e instanceof f1?X$(e._def.innerType):[];var Pye=class e extends A${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$.object)return X(t,{code:Y.invalid_type,expected:f$.object,received:t.parsedType}),y$;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}):(X(t,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),y$)}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=X$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...k$(r)})}};function Z$(e,t){let n=p$(e),r=p$(t);if(e===t)return{valid:!0,data:e};if(n===f$.object&&r===f$.object){let n=d$.objectKeys(t),r=d$.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Z$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===f$.array&&r===f$.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=Z$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===f$.date&&r===f$.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Q$=class extends A${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(S$(e)||S$(r))return y$;let i=Z$(e.value,r.value);return i.valid?((C$(e)||C$(r))&&t.dirty(),{status:t.value,value:i.data}):(X(n,{code:Y.invalid_intersection_types}),y$)};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}))}};Q$.create=(e,t,n)=>new Q$({left:e,right:t,typeName:Z.ZodIntersection,...k$(n)});var $$=class e extends A${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f$.array)return X(n,{code:Y.invalid_type,expected:f$.array,received:n.parsedType}),y$;if(n.data.length<this._def.items.length)return X(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),y$;!this._def.rest&&n.data.length>this._def.items.length&&(X(n,{code:Y.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 D$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>v$.mergeArray(t,e)):v$.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};$$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new $$({items:e,typeName:Z.ZodTuple,rest:null,...k$(t)})};var Fye=class e extends A${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!==f$.object)return X(n,{code:Y.invalid_type,expected:f$.object,received:n.parsedType}),y$;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new D$(n,e,n.path,e)),value:a._parse(new D$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?v$.mergeObjectAsync(t,r):v$.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof A$?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...k$(r)}):new e({keyType:P$.create(),valueType:t,typeName:Z.ZodRecord,...k$(n)})}},e1=class extends A${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!==f$.map)return X(n,{code:Y.invalid_type,expected:f$.map,received:n.parsedType}),y$;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new D$(n,e,n.path,[a,`key`])),value:i._parse(new D$(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 y$;(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 y$;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};e1.create=(e,t,n)=>new e1({valueType:t,keyType:e,typeName:Z.ZodMap,...k$(n)});var t1=class e extends A${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f$.set)return X(n,{code:Y.invalid_type,expected:f$.set,received:n.parsedType}),y$;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(X(n,{code:Y.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&&(X(n,{code:Y.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 y$;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 D$(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:E$.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:E$.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};t1.create=(e,t)=>new t1({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...k$(t)});var Iye=class e extends A${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$.function)return X(t,{code:Y.invalid_type,expected:f$.function,received:t.parsedType}),y$;function n(e,n){return _$({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g$(),h$].filter(e=>!!e),issueData:{code:Y.invalid_arguments,argumentsError:n}})}function r(e,n){return _$({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g$(),h$].filter(e=>!!e),issueData:{code:Y.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof s1){let e=this;return x$(async function(...t){let o=new m$([]),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 x$(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new m$([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new m$([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:$$.create(t).rest(U$.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||$$.create([]).rest(U$.create()),returns:n||U$.create(),typeName:Z.ZodFunction,...k$(r)})}},n1=class extends A${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})}};n1.create=(e,t)=>new n1({getter:e,typeName:Z.ZodLazy,...k$(t)});var r1=class extends A${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return X(t,{received:t.data,code:Y.invalid_literal,expected:this._def.value}),y$}return{status:`valid`,value:e.data}}get value(){return this._def.value}};r1.create=(e,t)=>new r1({value:e,typeName:Z.ZodLiteral,...k$(t)});function i1(e,t){return new a1({values:e,typeName:Z.ZodEnum,...k$(t)})}var a1=class e extends A${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return X(t,{expected:d$.joinValues(n),received:t.parsedType,code:Y.invalid_type}),y$}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return X(t,{received:t.data,code:Y.invalid_enum_value,options:n}),y$}return x$(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})}};a1.create=i1;var o1=class extends A${_parse(e){let t=d$.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f$.string&&n.parsedType!==f$.number){let e=d$.objectValues(t);return X(n,{expected:d$.joinValues(e),received:n.parsedType,code:Y.invalid_type}),y$}if(this._cache||=new Set(d$.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=d$.objectValues(t);return X(n,{received:n.data,code:Y.invalid_enum_value,options:e}),y$}return x$(e.data)}get enum(){return this._def.values}};o1.create=(e,t)=>new o1({values:e,typeName:Z.ZodNativeEnum,...k$(t)});var s1=class extends A${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==f$.promise&&t.common.async===!1?(X(t,{code:Y.invalid_type,expected:f$.promise,received:t.parsedType}),y$):x$((t.parsedType===f$.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};s1.create=(e,t)=>new s1({type:e,typeName:Z.ZodPromise,...k$(t)});var c1=class extends A${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{X(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 y$;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?y$:r.status===`dirty`||t.value===`dirty`?b$(r.value):r});{if(t.value===`aborted`)return y$;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?y$:r.status===`dirty`||t.value===`dirty`?b$(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`?y$:(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`?y$:(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(!w$(e))return y$;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=>w$(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):y$);d$.assertNever(r)}};c1.create=(e,t,n)=>new c1({schema:e,typeName:Z.ZodEffects,effect:t,...k$(n)}),c1.createWithPreprocess=(e,t,n)=>new c1({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...k$(n)});var l1=class extends A${_parse(e){return this._getType(e)===f$.undefined?x$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};l1.create=(e,t)=>new l1({innerType:e,typeName:Z.ZodOptional,...k$(t)});var u1=class extends A${_parse(e){return this._getType(e)===f$.null?x$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};u1.create=(e,t)=>new u1({innerType:e,typeName:Z.ZodNullable,...k$(t)});var d1=class extends A${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};d1.create=(e,t)=>new d1({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...k$(t)});var f1=class extends A${_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 T$(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new m$(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new m$(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};f1.create=(e,t)=>new f1({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...k$(t)});var p1=class extends A${_parse(e){if(this._getType(e)!==f$.nan){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.nan,received:t.parsedType}),y$}return{status:`valid`,value:e.data}}};p1.create=e=>new p1({typeName:Z.ZodNaN,...k$(e)});var m1=class extends A${_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}},h1=class e extends A${_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`?y$:e.status===`dirty`?(t.dirty(),b$(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`?y$:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Z.ZodPipeline})}},g1=class extends A${_parse(e){let t=this._def.innerType._parse(e),n=e=>(w$(e)&&(e.value=Object.freeze(e.value)),e);return T$(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};g1.create=(e,t)=>new g1({innerType:e,typeName:Z.ZodReadonly,...k$(t)}),J$.lazycreate;var Z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Z||={}),P$.create,F$.create,p1.create,I$.create,L$.create,R$.create,z$.create,B$.create,V$.create,H$.create,U$.create,W$.create,G$.create,K$.create;const Lye=J$.create;J$.strictCreate,Y$.create,Pye.create,Q$.create,$$.create,Fye.create,e1.create,t1.create,Iye.create,n1.create,r1.create,a1.create,o1.create,s1.create,c1.create,l1.create,u1.create,c1.createWithPreprocess,h1.create;const Rye=C(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Vn.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>et(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ut(e,t,n),e.parseAsync=async(t,n)=>rt(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>he(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)=>Ze(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),zye=C(`ZodMiniObject`,(e,t)=>{g.init(e,t),Rye.init(e,t),bt(e,`shape`,()=>t.shape)});function _1(e,t){return new zye({type:`object`,shape:e??{},...ai(t)})}function v1(e){return!!e._zod}function y1(e){let t=Object.values(e);if(t.length===0)return _1({});let n=t.every(v1),r=t.every(e=>!v1(e));if(n)return _1(e);if(r)return Lye(e);throw Error(`Mixed Zod versions detected in object shape.`)}function b1(e,t){return v1(e)?ut(e,t):e.safeParse(t)}async function x1(e,t){return v1(e)?await he(e,t):await e.safeParseAsync(t)}function S1(e){if(!e)return;let t;if(t=v1(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function C1(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 y1(e)}}if(v1(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 w1(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 Bye(e){return e.description}function Vye(e){if(v1(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function T1(e){if(v1(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 E1=`2025-11-25`,D1=[E1,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],O1=`io.modelcontextprotocol/related-task`,k1=fr(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),A1=Jr([D(),Wr().int()]),j1=D();Jt({ttl:Wr().optional(),pollInterval:Wr().optional()});const Hye=I({ttl:Wr().optional()}),Uye=I({taskId:D()}),M1=Jt({progressToken:A1.optional(),[O1]:Uye.optional()}),N1=I({_meta:M1.optional()}),P1=N1.extend({task:Hye.optional()}),Wye=e=>P1.safeParse(e).success,F1=I({method:D(),params:N1.loose().optional()}),I1=I({_meta:M1.optional()}),L1=I({method:D(),params:I1.loose().optional()}),R1=Jt({_meta:M1.optional()}),z1=Jr([D(),Wr().int()]),B1=I({jsonrpc:jn(`2.0`),id:z1,...F1.shape}).strict(),V1=e=>B1.safeParse(e).success,H1=I({jsonrpc:jn(`2.0`),...L1.shape}).strict(),Gye=e=>H1.safeParse(e).success,U1=I({jsonrpc:jn(`2.0`),id:z1,result:R1}).strict(),W1=e=>U1.safeParse(e).success;var G1;(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`})(G1||={});const K1=I({jsonrpc:jn(`2.0`),id:z1.optional(),error:I({code:Wr().int(),message:D(),data:Et().optional()})}).strict(),q1=e=>K1.safeParse(e).success,J1=Jr([B1,H1,U1,K1]);Jr([U1,K1]);const Y1=R1.strict(),Kye=I1.extend({requestId:z1.optional(),reason:D().optional()}),X1=L1.extend({method:jn(`notifications/cancelled`),params:Kye}),Z1=I({icons:hn(I({src:D(),mimeType:D().optional(),sizes:hn(D()).optional(),theme:un([`light`,`dark`]).optional()})).optional()}),Q1=I({name:D(),title:D().optional()}),$1=Q1.extend({...Q1.shape,...Z1.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),qye=Zr(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Pn(I({form:Pn(I({applyDefaults:En().optional()}),wt(D(),Et())).optional(),url:k1.optional()}),wt(D(),Et()).optional())),Jye=Jt({list:k1.optional(),cancel:k1.optional(),requests:Jt({sampling:Jt({createMessage:k1.optional()}).optional(),elicitation:Jt({create:k1.optional()}).optional()}).optional()}),Yye=Jt({list:k1.optional(),cancel:k1.optional(),requests:Jt({tools:Jt({call:k1.optional()}).optional()}).optional()}),Xye=I({experimental:wt(D(),k1).optional(),sampling:I({context:k1.optional(),tools:k1.optional()}).optional(),elicitation:qye.optional(),roots:I({listChanged:En().optional()}).optional(),tasks:Jye.optional(),extensions:wt(D(),k1).optional()}),Zye=N1.extend({protocolVersion:D(),capabilities:Xye,clientInfo:$1}),e0=F1.extend({method:jn(`initialize`),params:Zye}),t0=e=>e0.safeParse(e).success,Qye=I({experimental:wt(D(),k1).optional(),logging:k1.optional(),completions:k1.optional(),prompts:I({listChanged:En().optional()}).optional(),resources:I({subscribe:En().optional(),listChanged:En().optional()}).optional(),tools:I({listChanged:En().optional()}).optional(),tasks:Yye.optional(),extensions:wt(D(),k1).optional()}),$ye=R1.extend({protocolVersion:D(),capabilities:Qye,serverInfo:$1,instructions:D().optional()}),n0=L1.extend({method:jn(`notifications/initialized`),params:I1.optional()}),ebe=e=>n0.safeParse(e).success,r0=F1.extend({method:jn(`ping`),params:N1.optional()}),tbe=I({progress:Wr(),total:sn(Wr()),message:sn(D())}),nbe=I({...I1.shape,...tbe.shape,progressToken:A1}),i0=L1.extend({method:jn(`notifications/progress`),params:nbe}),rbe=N1.extend({cursor:j1.optional()}),a0=F1.extend({params:rbe.optional()}),o0=R1.extend({nextCursor:j1.optional()}),ibe=un([`working`,`input_required`,`completed`,`failed`,`cancelled`]),s0=I({taskId:D(),status:ibe,ttl:Jr([Wr(),qn()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:sn(Wr()),statusMessage:sn(D())}),c0=R1.extend({task:s0}),abe=I1.merge(s0),l0=L1.extend({method:jn(`notifications/tasks/status`),params:abe}),u0=F1.extend({method:jn(`tasks/get`),params:N1.extend({taskId:D()})}),d0=R1.merge(s0),f0=F1.extend({method:jn(`tasks/result`),params:N1.extend({taskId:D()})});R1.loose();const p0=a0.extend({method:jn(`tasks/list`)}),m0=o0.extend({tasks:hn(s0)}),h0=F1.extend({method:jn(`tasks/cancel`),params:N1.extend({taskId:D()})}),obe=R1.merge(s0),g0=I({uri:D(),mimeType:sn(D()),_meta:wt(D(),Et()).optional()}),_0=g0.extend({text:D()}),v0=D().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),y0=g0.extend({blob:v0}),b0=un([`user`,`assistant`]),x0=I({audience:hn(b0).optional(),priority:Wr().min(0).max(1).optional(),lastModified:ie({offset:!0}).optional()}),S0=I({...Q1.shape,...Z1.shape,uri:D(),description:sn(D()),mimeType:sn(D()),size:sn(Wr()),annotations:x0.optional(),_meta:sn(Jt({}))}),sbe=I({...Q1.shape,...Z1.shape,uriTemplate:D(),description:sn(D()),mimeType:sn(D()),annotations:x0.optional(),_meta:sn(Jt({}))}),C0=a0.extend({method:jn(`resources/list`)}),cbe=o0.extend({resources:hn(S0)}),w0=a0.extend({method:jn(`resources/templates/list`)}),lbe=o0.extend({resourceTemplates:hn(sbe)}),T0=N1.extend({uri:D()}),ube=T0,E0=F1.extend({method:jn(`resources/read`),params:ube}),dbe=R1.extend({contents:hn(Jr([_0,y0]))}),fbe=L1.extend({method:jn(`notifications/resources/list_changed`),params:I1.optional()}),pbe=T0,mbe=F1.extend({method:jn(`resources/subscribe`),params:pbe}),hbe=T0,gbe=F1.extend({method:jn(`resources/unsubscribe`),params:hbe}),_be=I1.extend({uri:D()}),vbe=L1.extend({method:jn(`notifications/resources/updated`),params:_be}),ybe=I({name:D(),description:sn(D()),required:sn(En())}),bbe=I({...Q1.shape,...Z1.shape,description:sn(D()),arguments:sn(hn(ybe)),_meta:sn(Jt({}))}),D0=a0.extend({method:jn(`prompts/list`)}),xbe=o0.extend({prompts:hn(bbe)}),Sbe=N1.extend({name:D(),arguments:wt(D(),D()).optional()}),O0=F1.extend({method:jn(`prompts/get`),params:Sbe}),k0=I({type:jn(`text`),text:D(),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),A0=I({type:jn(`image`),data:v0,mimeType:D(),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),j0=I({type:jn(`audio`),data:v0,mimeType:D(),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),Cbe=I({type:jn(`tool_use`),name:D(),id:D(),input:wt(D(),Et()),_meta:wt(D(),Et()).optional()}),wbe=I({type:jn(`resource`),resource:Jr([_0,y0]),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),M0=Jr([k0,A0,j0,S0.extend({type:jn(`resource_link`)}),wbe]),Tbe=I({role:b0,content:M0}),Ebe=R1.extend({description:D().optional(),messages:hn(Tbe)}),Dbe=L1.extend({method:jn(`notifications/prompts/list_changed`),params:I1.optional()}),Obe=I({title:D().optional(),readOnlyHint:En().optional(),destructiveHint:En().optional(),idempotentHint:En().optional(),openWorldHint:En().optional()}),kbe=I({taskSupport:un([`required`,`optional`,`forbidden`]).optional()}),N0=I({...Q1.shape,...Z1.shape,description:D().optional(),inputSchema:I({type:jn(`object`),properties:wt(D(),k1).optional(),required:hn(D()).optional()}).catchall(Et()),outputSchema:I({type:jn(`object`),properties:wt(D(),k1).optional(),required:hn(D()).optional()}).catchall(Et()).optional(),annotations:Obe.optional(),execution:kbe.optional(),_meta:wt(D(),Et()).optional()}),P0=a0.extend({method:jn(`tools/list`)}),Abe=o0.extend({tools:hn(N0)}),F0=R1.extend({content:hn(M0).default([]),structuredContent:wt(D(),Et()).optional(),isError:En().optional()});F0.or(R1.extend({toolResult:Et()}));const jbe=P1.extend({name:D(),arguments:wt(D(),Et()).optional()}),I0=F1.extend({method:jn(`tools/call`),params:jbe}),Mbe=L1.extend({method:jn(`notifications/tools/list_changed`),params:I1.optional()});I({autoRefresh:En().default(!0),debounceMs:Wr().int().nonnegative().default(300)});const L0=un([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Nbe=N1.extend({level:L0}),R0=F1.extend({method:jn(`logging/setLevel`),params:Nbe}),Pbe=I1.extend({level:L0,logger:D().optional(),data:Et()}),Fbe=L1.extend({method:jn(`notifications/message`),params:Pbe}),Ibe=I({hints:hn(I({name:D().optional()})).optional(),costPriority:Wr().min(0).max(1).optional(),speedPriority:Wr().min(0).max(1).optional(),intelligencePriority:Wr().min(0).max(1).optional()}),Lbe=I({mode:un([`auto`,`required`,`none`]).optional()}),Rbe=I({type:jn(`tool_result`),toolUseId:D().describe(`The unique identifier for the corresponding tool call.`),content:hn(M0).default([]),structuredContent:I({}).loose().optional(),isError:En().optional(),_meta:wt(D(),Et()).optional()}),zbe=Qn(`type`,[k0,A0,j0]),z0=Qn(`type`,[k0,A0,j0,Cbe,Rbe]),Bbe=I({role:b0,content:Jr([z0,hn(z0)]),_meta:wt(D(),Et()).optional()}),Vbe=P1.extend({messages:hn(Bbe),modelPreferences:Ibe.optional(),systemPrompt:D().optional(),includeContext:un([`none`,`thisServer`,`allServers`]).optional(),temperature:Wr().optional(),maxTokens:Wr().int(),stopSequences:hn(D()).optional(),metadata:k1.optional(),tools:hn(N0).optional(),toolChoice:Lbe.optional()}),Hbe=F1.extend({method:jn(`sampling/createMessage`),params:Vbe}),B0=R1.extend({model:D(),stopReason:sn(un([`endTurn`,`stopSequence`,`maxTokens`]).or(D())),role:b0,content:zbe}),V0=R1.extend({model:D(),stopReason:sn(un([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D())),role:b0,content:Jr([z0,hn(z0)])}),Ube=I({type:jn(`boolean`),title:D().optional(),description:D().optional(),default:En().optional()}),Wbe=I({type:jn(`string`),title:D().optional(),description:D().optional(),minLength:Wr().optional(),maxLength:Wr().optional(),format:un([`email`,`uri`,`date`,`date-time`]).optional(),default:D().optional()}),Gbe=I({type:un([`number`,`integer`]),title:D().optional(),description:D().optional(),minimum:Wr().optional(),maximum:Wr().optional(),default:Wr().optional()}),Kbe=I({type:jn(`string`),title:D().optional(),description:D().optional(),enum:hn(D()),default:D().optional()}),qbe=I({type:jn(`string`),title:D().optional(),description:D().optional(),oneOf:hn(I({const:D(),title:D()})),default:D().optional()}),Jbe=Jr([Jr([I({type:jn(`string`),title:D().optional(),description:D().optional(),enum:hn(D()),enumNames:hn(D()).optional(),default:D().optional()}),Jr([Kbe,qbe]),Jr([I({type:jn(`array`),title:D().optional(),description:D().optional(),minItems:Wr().optional(),maxItems:Wr().optional(),items:I({type:jn(`string`),enum:hn(D())}),default:hn(D()).optional()}),I({type:jn(`array`),title:D().optional(),description:D().optional(),minItems:Wr().optional(),maxItems:Wr().optional(),items:I({anyOf:hn(I({const:D(),title:D()}))}),default:hn(D()).optional()})])]),Ube,Wbe,Gbe]),Ybe=Jr([P1.extend({mode:jn(`form`).optional(),message:D(),requestedSchema:I({type:jn(`object`),properties:wt(D(),Jbe),required:hn(D()).optional()})}),P1.extend({mode:jn(`url`),message:D(),elicitationId:D(),url:D().url()})]),Xbe=F1.extend({method:jn(`elicitation/create`),params:Ybe}),Zbe=I1.extend({elicitationId:D()}),Qbe=L1.extend({method:jn(`notifications/elicitation/complete`),params:Zbe}),H0=R1.extend({action:un([`accept`,`decline`,`cancel`]),content:Zr(e=>e===null?void 0:e,wt(D(),Jr([D(),Wr(),En(),hn(D())])).optional())}),$be=I({type:jn(`ref/resource`),uri:D()}),exe=I({type:jn(`ref/prompt`),name:D()}),txe=N1.extend({ref:Jr([exe,$be]),argument:I({name:D(),value:D()}),context:I({arguments:wt(D(),D()).optional()}).optional()}),U0=F1.extend({method:jn(`completion/complete`),params:txe});function nxe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function rxe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const ixe=R1.extend({completion:Jt({values:hn(D()).max(100),total:sn(Wr().int()),hasMore:sn(En())})}),axe=I({uri:D().startsWith(`file://`),name:D().optional(),_meta:wt(D(),Et()).optional()}),oxe=F1.extend({method:jn(`roots/list`),params:N1.optional()}),W0=R1.extend({roots:hn(axe)}),sxe=L1.extend({method:jn(`notifications/roots/list_changed`),params:I1.optional()});Jr([r0,e0,U0,R0,O0,D0,C0,w0,E0,mbe,gbe,I0,P0,u0,f0,p0,h0]),Jr([X1,i0,n0,sxe,l0]),Jr([Y1,B0,V0,H0,W0,d0,m0,c0]),Jr([r0,Hbe,Xbe,oxe,u0,f0,p0,h0]),Jr([X1,i0,Fbe,vbe,fbe,Mbe,Dbe,l0,Qbe]),Jr([Y1,$ye,ixe,Ebe,xbe,cbe,lbe,dbe,F0,Abe,d0,m0,c0]);var G0=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===G1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new cxe(e.elicitations,n)}return new e(t,n,r)}},cxe=class extends G0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(G1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function K0(e){return e===`completed`||e===`failed`||e===`cancelled`}const lxe=Symbol(`Let zodToJsonSchema decide on which parser to use`),q0={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`},uxe=e=>typeof e==`string`?{...q0,name:e}:{...q0,...e},dxe=e=>{let t=uxe(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 J0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Y0(e,t,n,r,i){e[t]=n,J0(e,t,r,i)}const X0=(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 Z0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?X0(t,e.currentPath):t.join(`/`)}}function fxe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=u2(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&Y0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&Y0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Y0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),Y0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function pxe(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?Y0(n,`minimum`,r.value,r.message,t):Y0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Y0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Y0(n,`maximum`,r.value,r.message,t):Y0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Y0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Y0(n,`multipleOf`,r.value,r.message,t);break}return n}function mxe(){return{type:`boolean`}}function Q0(e,t){return u2(e.type._def,t)}const hxe=(e,t)=>u2(e.innerType._def,t);function $0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>$0(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 gxe(e,t)}}const gxe=(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`:Y0(n,`minimum`,r.value,r.message,t);break;case`max`:Y0(n,`maximum`,r.value,r.message,t);break}return n};function _xe(e,t){return{...u2(e.innerType._def,t),default:e.defaultValue()}}function vxe(e,t){return t.effectStrategy===`input`?u2(e.schema._def,t):Z0(t)}function yxe(e){return{type:`string`,enum:Array.from(e.values)}}const bxe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function xxe(e,t){let n=[u2(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),u2(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(bxe(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 Sxe(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 e2;const t2={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:()=>(e2===void 0&&(e2=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),e2),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 n2(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:Y0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:Y0(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`:i2(n,`email`,r.message,t);break;case`format:idn-email`:i2(n,`idn-email`,r.message,t);break;case`pattern:zod`:a2(n,t2.email,r.message,t);break}break;case`url`:i2(n,`uri`,r.message,t);break;case`uuid`:i2(n,`uuid`,r.message,t);break;case`regex`:a2(n,r.regex,r.message,t);break;case`cuid`:a2(n,t2.cuid,r.message,t);break;case`cuid2`:a2(n,t2.cuid2,r.message,t);break;case`startsWith`:a2(n,RegExp(`^${r2(r.value,t)}`),r.message,t);break;case`endsWith`:a2(n,RegExp(`${r2(r.value,t)}$`),r.message,t);break;case`datetime`:i2(n,`date-time`,r.message,t);break;case`date`:i2(n,`date`,r.message,t);break;case`time`:i2(n,`time`,r.message,t);break;case`duration`:i2(n,`duration`,r.message,t);break;case`length`:Y0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),Y0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:a2(n,RegExp(r2(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&i2(n,`ipv4`,r.message,t),r.version!==`v4`&&i2(n,`ipv6`,r.message,t);break;case`base64url`:a2(n,t2.base64url,r.message,t);break;case`jwt`:a2(n,t2.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&a2(n,t2.ipv4Cidr,r.message,t),r.version!==`v4`&&a2(n,t2.ipv6Cidr,r.message,t);break;case`emoji`:a2(n,t2.emoji(),r.message,t);break;case`ulid`:a2(n,t2.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:i2(n,`binary`,r.message,t);break;case`contentEncoding:base64`:Y0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:a2(n,t2.base64,r.message,t);break}break;case`nanoid`:a2(n,t2.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function r2(e,t){return t.patternStrategy===`escape`?wxe(e):e}const Cxe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function wxe(e){let t=``;for(let n=0;n<e.length;n++)Cxe.has(e[n])||(t+=`\\`),t+=e[n];return t}function i2(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}}})):Y0(e,`format`,t,n,r)}function a2(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:o2(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Y0(e,`pattern`,o2(t,r),n,r)}function o2(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
1266
+ `);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=>{vQ.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(),qe.release(di))}),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()),qe.release(di))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),qe.release(di))})}let Ei=`local-op-auth-signout`,Di=J(Re,async(e,t,n)=>{let r=n.host??gi();if(!qe.tryAcquire(pi)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Ei,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ye,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=_o(e,i,nV({...$r,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),q(t,200,_r,{},{handler:Ei})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Ei,cause:e})}finally{qe.release(pi)}},{handler:Ei,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Ei})}),ki=`/api/local-op/auth/set-identity`,Ai=`local-op-auth-set-identity`,ji=J(Aee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!F){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ai});return}if(!qe.tryAcquire(ki)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ai,extraHeaders:{"Retry-After":`5`}});return}try{yge(F,r,i),ve?.()?.refreshIdentity().catch(()=>{}),q(t,200,_r,{},{handler:Ai})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ai,cause:e})}finally{qe.release(ki)}},{handler:Ai,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Ai})});async function Mi(e,t){if(eZ(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();if(!e){q(t,200,An,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),q(t,200,An,e.getStatus(),{handler:`sync-status`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Ni=J(Lee,async(e,t,n)=>{let r=ve?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,Ur,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`sync-trigger`})?ve?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Pi(e,t){if(eZ(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ve?.();q(t,200,gte,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Fi=J(ute,async(e,t,n)=>{let r=ve?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,Zee,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`sync-resolve-conflict`})?ve?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Ii(e,n){if(!eZ(e,n,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!F){G(n,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`file`);if(!i){G(n,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(n,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=oL(i),o=t.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=ve?.(),c=s?s.getConflicts().some(e=>e.file===i):!1;if(!o&&!c){G(n,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let l=r.searchParams.get(`source`),u=mi({baseDir:F,timeout:{block:15e3}});async function d(e){try{return{present:!0,content:await u.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,r,a]=await Promise.all([d(1),d(2),d(3)]),o=e.present?e.content:``,s=a.present?a.content:``,c=r.present&&a.present?`both-modified`:!r.present&&a.present?`delete-modify`:r.present&&!a.present?`modify-delete`:`both-modified`,u=r.present?r.content:``,f=null;if(l===`ytext`){let e=oL(i),n=t.documents.get(e);if(n){let t=n.getMap(`lifecycle`).get(`status`);if(f=typeof t==`string`&&t.length>0?t:null,c!==`delete-modify`){let t=ke?ke(e):null;t!==null&&!Fve(t)?u=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else console.warn(`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(n,200,Gee,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:f},{handler:`sync-conflict-content`})}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Li(e,t){if(!eZ(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=AZ(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,Wee,{plan:await LZ({projectDir:r,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof yZ){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof bZ){G(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Ri=J(Uee,async(e,t,n)=>{let i=n.plan;if(!i||typeof i!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let a=i,o=n.packId,s=AZ(o);if(typeof o==`string`&&o.length>0&&s===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${o}" is not registered.`});return}try{q(t,200,cte,{result:await FZ(a,{projectDir:r,packId:s})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`seed-apply`})});async function zi(e,t){if(eZ(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,Lr,{packs:jZ()},{handler:`seed-packs`})}}let Bi=J(pte,async(e,t,n)=>{if(n.out!==void 0&&!$X(n.out)){G(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{q(t,200,xte,await WJ({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`install-skill`})});async function Vi(e,t){if(eZ(e,t,{handler:`installed-agents`}))try{await Qme(e,t,ot.probeAll)}catch(e){t.headersSent||(vQ.error({err:e},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:e}))}}let Hi=J(M,async(e,t)=>{if(!de){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,vte,{tags:de.getAllTags()},{handler:`tags-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function Ui(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!de){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let r;try{r=decodeURIComponent(n)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){G(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=de.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:ct(e),matchingTags:t,snippet:null}));q(t,200,Ke,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function Wi(e,t,n=`path`,i=`folder-config`){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:i}),null;let o=B(r),s=a===``?o:B(o,a);return s!==o&&!s.startsWith(`${o}${Do}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:i}),null):{folderRel:a,resolvedContentDir:o}}let Gi=/^[A-Za-z0-9_-]+$/;function Ki(e,t,n=`template`){return!e||!Gi.test(e)?(G(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function qi(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:B(e,i);if(a!==e&&!a.startsWith(`${e}${Do}`))continue;let o=B(a,`.ok`,`templates`,`${n}.md`);if(V(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Ji(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}async function Yi(e,t){if(e.method===`GET`)return Xi(e,t);if(e.method===`PUT`)return Zi(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`folder-config`,extraHeaders:{Allow:`GET, PUT`}})}let Xi=J(M,async(e,t)=>{try{let n=Wi(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await aU(n.folderRel,{projectDir:n.resolvedContentDir}),i=B(B(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(V(i))try{let e=(0,YN.parse)(await fs(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}q(t,200,er,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),Zi=J($ee,async(e,t,n)=>{try{if(Ve){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Wi(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=Zpe({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(jn(e,kn(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Nn(`folder-config-put`))}q(t,200,Yee,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`});function Qi(e,n,r,i){if(!n)return!1;let a=e===``?`.ok/templates/${n}`:`${e.replace(/\/$/,``)}/.ok/templates/${n}`,o=t.documents.get(a);return o&&yL(o)?(xL(i,new bL({file:`${a}.md`}),r),!0):!1}function $i(e,n,r){let i=t.documents.get(e);return i&&yL(i)?(xL(r,new bL({file:`${e}.md`}),n),!0):!1}let ea=J(M,async(e,t)=>{try{let e=XH(B(r));q(t,200,yn,{templates:e.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:e.truncated},{handler:`templates-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list templates.`,{handler:`templates-list`,cause:e})}},{handler:`templates-list`,method:`GET`,skipBodyParse:!0});async function ta(e,t){if(e.method===`GET`)return ra(e,t);if(e.method===`PUT`)return ia(e,t);if(e.method===`POST`)return oa(e,t);if(e.method===`DELETE`)return aa(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`template`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let na=e=>{let{frontmatter:t,body:n}=Ye(e),r={};if(t!==``)try{let e=(0,YN.parse)(vt(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{frontmatter:r,body:n}},ra=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ki(r,t,`template-get`))return;let i=Wi(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=qi(o,a,r);if(!s){G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=On(await fs(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,Mee,{template:{name:r,folder:l,scope:u,path:z(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),ia=J(dee,async(e,t,r)=>{try{if(Ve){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let i=r.name;if(!Ki(i,t,`template-put`))return;let a=Wi(r.folder,t,`folder`,`template-put`);if(!a||Qi(a.folderRel,i,`template-put`,t))return;let o=TU({name:i,body:typeof r.body==`string`?r.body:``,frontmatter:Ji(r.frontmatter)});if(!o.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:o.error.code,cause:Error(o.error.message)});return}let s=B(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`),c=!V(s),l=z(a.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=ha(a.folderRel,i),{agentId:f,agentName:p,colorSeed:m,clientName:h}=_n(r),g=await n.getSession(u,f,{displayName:p,colorSeed:m,clientName:h});g.dc.document.transact(()=>{YI(g.dc.document,o.content,`agent`)},g.origin);let _=await xt(u);if(_?.kind===`failure`){wt(t,_.failure,`template-put`);return}if(_?.kind===`divergence`){Tt(t,`template-put`);return}jn(e,kn(`template`,a.folderRel,i),`${c?`template-create`:`template-edit`}: ${l}`),await Nn(`template-put`),q(t,200,d,{path:l,created:c,warnings:o.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),aa=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ki(r,t,`template-delete`))return;let i=Wi(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=xX({agentId:a.get(`agentId`)??void 0,agentName:a.get(`agentName`)??void 0,colorSeed:a.get(`colorSeed`)??void 0,clientName:a.get(`clientName`)??void 0,clientVersion:a.get(`clientVersion`)??void 0,label:a.get(`label`)??void 0,summary:a.get(`summary`)??void 0},xe);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Qi(i.folderRel,r,`template-delete`,t))return;await zt([ha(i.folderRel,r)],`deleted-upstream`);let s=dme({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!s.ok){let e=s.error.code===`WRITE_ERROR`||s.error.code===`UNLINK_FAILED`||s.error.code===`BAD_PROJECT_DIR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:s.error.code,cause:Error(s.error.message)});return}s.existed&&(jn(o,kn(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Nn(`template-delete`)),q(t,200,Be,{existed:s.existed,path:s.path},{handler:`template-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),oa=J(Oee,async(e,t,n)=>{try{let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Ki(n.fromName,t,`template-move`)||!Ki(n.toName,t,`template-move`))return;let r=Wi(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Wi(n.toFolder,t,`folder`,`template-move`);if(!i||Qi(r.folderRel,n.fromName,`template-move`,t))return;await zt([ha(r.folderRel,n.fromName)],`renamed`);let a=await fme({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await XQ(F,e,t);return n||YQ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=qi(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){G(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}let o=null;if(n.body!==void 0||n.frontmatter!==void 0){let e;if(typeof n.body==`string`)e=n.body;else try{e=Mn(H(B(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=ume({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Ji(n.frontmatter)});t.ok||(o=t.error)}}if(jn(e,kn(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Nn(`template-move`),fe?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,Fee,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`});function sa(e,t,n){return!e||e.length>64||!Xt.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function ca(e,t,n){let r=Pe.safeParse(e??`project`);return r.success?r.data:(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let la=Se??$o();function ua(e){return B(e===`global`?la:r,`.ok`,`skills`)}let da=Qq.project;function fa(){if(!F)return null;let e=[],t=null;for(let n of Qt){let r=br[n];if(!r)continue;let i=B(F,...r.split(`/`),da);V(B(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=B(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:z(F,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function pa(){let e=fa();if(!e)return null;let t;try{let{frontmatter:n}=na(H(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:da,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function ma(e,t,n){return eJ(e)?(G(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is a built-in skill managed by OpenKnowledge and can't be edited, renamed, or deleted.`,{handler:n}),!0):!1}function ha(e,t){return`${Vr}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function ga(e){return e===`navigation`||e===`relevance`?e:void 0}function _a(e,t){return z(t===`global`?la:r,e).split(/[\\/]/).filter(Boolean).join(`/`)}function va(e){return e===`global`?la:F}async function ya(e,t){let n=await kW(e,t);return vY(t,e,Qt),n!==null}function ba(e,t){let n=[];if(!V(e))return{skills:n,truncated:!1};let r;try{r=Uo(e,{withFileTypes:!0})}catch(r){return U(`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()||!Xt.test(a.name))continue;if(n.length>=500){i=!0;break}let r=B(e,a.name,`SKILL.md`);if(!V(r))continue;let o,s;try{let{frontmatter:e}=na(H(r,`utf-8`));typeof e.description==`string`&&(o=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(s=e.version)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:_a(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let xa=J(M,async(e,t)=>{try{let e=ba(ua(`project`),`project`),n=ba(ua(`global`),`global`),r=F?EW(F).skills:{},i=EW(la).skills,a=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=Rhe(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),o=e.skills.some(e=>e.name===da)?null:pa();q(t,200,wee,{skills:[...a(e,r),...a(n,i),...o?[o]:[]],truncated:e.truncated||n.truncated},{handler:`skills-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list skills.`,{handler:`skills-list`,cause:e})}},{handler:`skills-list`,method:`GET`,skipBodyParse:!0});async function Sa(e,t){if(e.method===`GET`)return Oa(e,t);if(e.method===`PUT`)return ka(e,t);if(e.method===`POST`)return ja(e,t);if(e.method===`DELETE`)return Aa(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill`,extraHeaders:{Allow:`GET, PUT, POST, DELETE`}})}let Ca=I({managed:En().nullable(),importable:Wr().int().nonnegative()}),wa=()=>({managed:F?qJ(F)?.manageEditorSkills??null:null,importable:F?Hhe({projectDir:F,skillsRoot:ua(`project`)}):0}),Ta=J(M,async(e,t)=>{if(!F){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Ca,wa(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),Ea=J(I({manageEditorSkills:En()}),async(e,t,n)=>{if(!F){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await JJ(F,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await PY({projectDir:F,skillsRoot:ua(`project`)});e.adopted.length+e.collided.length>0&&fe?.(`files`)}q(t,200,Ca,wa(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`});async function Da(e,t){if(e.method===`GET`)return Ta(e,t);if(e.method===`PUT`)return Ea(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skills-management`,extraHeaders:{Allow:`GET, PUT`}})}let Oa=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!sa(r,t,`skill-get`))return;let i=ca(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===da&&i===`project`){let e=fa();if(e){let{frontmatter:n,body:a}=na(await fs(e.skillMd,`utf-8`));q(t,200,ue,{skill:{name:r,scope:i,path:e.relPath,frontmatter:{name:typeof n.name==`string`?n.name:r,description:typeof n.description==`string`?n.description:``},body:a,files:bY(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=ua(i),o=B(a,r,`SKILL.md`);if(!V(o)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${r}" not found in ${i} scope.`});return}let{frontmatter:s,body:c}=na(await fs(o,`utf-8`));q(t,200,ue,{skill:{name:r,scope:i,path:_a(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:bY(B(a,r))}},{handler:`skill-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),ka=J(nee,async(e,t,r)=>{try{let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!sa(r.name,t,`skill-put`)||ma(r.name,t,`skill-put`))return;let i=fU({name:r.name,body:typeof r.body==`string`?r.body:``,frontmatter:{name:r.frontmatter.name,description:r.frontmatter.description}});if(!i.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:i.error.code,cause:Error(i.error.message)});return}let a=ua(r.scope),o=B(a,r.name,`SKILL.md`),s=!V(o),c=z(a,o).split(/[\\/]/).filter(Boolean).join(`/`),l=Un(r.scope,r.name);if($i(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=_n(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{YI(m.dc.document,i.content,`agent`)},m.origin);let h=await xt(l);if(h?.kind===`failure`){wt(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){Tt(t,`skill-put`);return}r.scope===`project`&&(jn(e,kn(`skill`,``,r.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Nn(`skill-put`)),fe?.(`files`),q(t,200,aee,{path:c,created:s,warnings:i.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),Aa=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!sa(r,t,`skill-delete`)||ma(r,t,`skill-delete`))return;let i=ca(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=ua(i),o=n.searchParams,s=xX({agentId:o.get(`agentId`)??void 0,agentName:o.get(`agentName`)??void 0,colorSeed:o.get(`colorSeed`)??void 0,clientName:o.get(`clientName`)??void 0,clientVersion:o.get(`clientVersion`)??void 0,label:o.get(`label`)??void 0,summary:o.get(`summary`)??void 0},xe);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await zt([Un(i,r)],`deleted-upstream`);let c=rme({skillsRoot:a,name:r});if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(jn(s,kn(`skill`,``,r),`skill-delete: ${c.path}`),await Nn(`skill-delete`)),fe?.(`files`));let l=va(i);l&&await ya(l,r),q(t,200,Mte,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),ja=J(v,async(e,t,n)=>{try{let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!sa(n.fromName,t,`skill-move`)||!sa(n.toName,t,`skill-move`)||ma(n.fromName,t,`skill-move`)||ma(n.toName,t,`skill-move`))return;let r=ua(n.scope);await zt([Un(n.scope,n.fromName)],`renamed`);let i=await ime({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await XQ(F,e,t);return n||YQ(e,t),n}});if(!i.ok){if(i.error.code===`SKILL_NOT_FOUND`){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:i.error.message});return}if(i.error.code===`SKILL_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,i.error.message,{handler:`skill-move`,detail:i.error.code});return}let e=i.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:i.error.code,cause:Error(i.error.message)});return}let a=null,o=B(r,n.toName,`SKILL.md`),s=``,c=``;try{let e=na(H(o,`utf-8`));s=e.body,typeof e.frontmatter.description==`string`&&(c=e.frontmatter.description)}catch{}let l=typeof n.body==`string`?n.body:s,u=n.frontmatter===void 0?c:n.frontmatter.description,d=eme({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{Ia(r,n.fromName,n.toName)}catch(e){U(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let f=_a(B(r,n.fromName),n.scope),p=_a(B(r,n.toName),n.scope);n.scope===`project`&&(jn(e,kn(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Nn(`skill-move`));let m=va(n.scope);if(m){let e=await kW(m,n.fromName);if(e){let t=uY(e.hosts);vY(n.fromName,m,t);let i=_Y(B(r,n.toName),n.toName,m,t);await OW(m,n.toName,{...e,hosts:i})}}if(fe?.(`files`),a){let e=a.code===`WRITE_ERROR`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:a.code,cause:Error(a.message)});return}q(t,200,rte,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`});function Ma(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function Na(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Pa(e,t){let n=t.replace(/\.md$/i,``);return`${A(e).replace(/\/SKILL$/,``)}/${n}`}function Fa(e,t){let n=B(e,t,`references`);if(!V(n))return[];let r=[],i=(e,t)=>{for(let n of Uo(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(B(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}function Ia(e,t,n){if(!P)return;let r=(e,t,n)=>{let r;try{r=H(n,`utf-8`)}catch{P.deleteDocument(e),de?.deleteDocument(e);return}P.renameDocument(e,t,r),de?.renameDocument(e,t,r)};r(A(t),A(n),B(e,n,`SKILL.md`));for(let i of Fa(e,n))r(Pa(t,i),Pa(n,i),B(e,n,i));fe?.(`backlinks`),fe?.(`graph`)}let La=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!sa(r,t,`skill-file-get`))return;let i=ca(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===da&&i===`project`?fa():null,s=o&&a===`SKILL.md`?`reference`:Ma(a);if(s===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let c=o?o.dir:B(ua(i),r),l=B(c,a);if(l!==c&&!l.startsWith(`${c}${Do}`)){G(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let u=l,d=a;if(!V(u)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Ir.map(t=>`${e[1]}${t}`).find(e=>e!==a&&V(B(c,e))):void 0;if(n===void 0){G(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}d=n,u=B(c,n)}let f=await fs(u);if(f.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,k,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),Ra=J(Ote,async(e,t,r)=>{try{let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!sa(r.name,t,`skill-file-put`)||ma(r.name,t,`skill-file-put`))return;let i=Ma(r.path);if(i===null){G(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(r.content,`utf-8`)>262144){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let a=ua(r.scope);if(!V(B(a,r.name,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${r.name}" before adding bundle files.`});return}let o=r.path.replace(/\\/g,`/`),s=Na(r.scope,i,o),c;if(s){let e=Pa(r.name,o);if($i(e,`skill-file-put`,t))return;if(c=!V(B(a,r.name,o)),c&&mU(B(a,r.name))>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${r.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:i,agentName:s,colorSeed:l,clientName:u}=_n(r),d=await n.getSession(e,i,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{YI(d.dc.document,r.content,`agent`)},d.origin);let f=await xt(e);if(f?.kind===`failure`){wt(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){Tt(t,`skill-file-put`);return}}else{let e=tme({skillsRoot:a,name:r.name,relPath:o,content:r.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}r.scope===`project`&&(jn(e,kn(`skill`,``,r.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${r.name}/${o}`),await Nn(`skill-file-put`)),fe?.(`files`),q(t,200,Dt,{path:o,created:c,kind:i,content:s},{handler:`skill-file-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),za=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!sa(r,t,`skill-file-delete`)||ma(r,t,`skill-file-delete`))return;let i=ca(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=Ma(a);if(o===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let s=xX({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},xe);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=ua(i);Na(i,o,a)&&await zt([Pa(r,a)],`deleted-upstream`);let l=nme({skillsRoot:c,name:r,relPath:a});if(!l.ok){let e=l.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:l.error.code,cause:Error(l.error.message)});return}l.existed&&i===`project`&&(jn(s,kn(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Nn(`skill-file-delete`)),l.existed&&fe?.(`files`),q(t,200,hee,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0});async function Ba(e,t){if(e.method===`GET`)return La(e,t);if(e.method===`PUT`)return Ra(e,t);if(e.method===`DELETE`)return za(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-file`,extraHeaders:{Allow:`GET, PUT, DELETE`}})}let Va=J(ae,async(e,t,n)=>{try{let e=ua(n.scope);if(!sa(n.name,t,`skill-install`)||ma(n.name,t,`skill-install`))return;if(n.scope===`project`&&!F){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=va(n.scope),i=B(e,n.name);if(!V(i)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}let a=pY(i,n.name);if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${a.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let o=n.scope===`global`?n.targets?Qt.filter(e=>n.targets?.some(t=>t===e)):[...Qt]:n.targets===void 0?mY(r,LY(r)??void 0):Qt.filter(e=>n.targets?.some(t=>t===e)),s=[],c=[];o.length===0&&n.targets===void 0&&(s.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),c.push(`no-targets`)),a.hasScripts&&(s.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),c.push(`scripts-present`));let l=uY(EW(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&vY(n.name,r,l);let u=_Y(i,n.name,r,o);u.length===0?await kW(r,n.name):await OW(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),fe?.(`files`),q(t,200,ste,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Ha=J(ee,async(e,t,n)=>{try{if(!sa(n.name,t,`skill-uninstall`)||ma(n.name,t,`skill-uninstall`))return;let e=va(n.scope);if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await ya(e,n.name);fe?.(`files`),q(t,200,See,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`});async function Ua(e,t){if(e.method===`GET`)return Wa(e,t);if(e.method===`PUT`)return Ga(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`skill-targets`,extraHeaders:{Allow:`GET, PUT`}})}let Wa=J(M,async(e,t)=>{try{let e=F?LY(F):null;q(t,200,eee,{targets:mY(F??``,e??void 0),configured:e!==null},{handler:`skill-targets-get`})}catch(e){G(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}),Ga=J(St,async(e,t,n)=>{try{if(!F){G(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let e=n.targets,r=new Set(e),i=mY(F,LY(F)??void 0),a=ua(`project`);await Khe(F,e);let{reprojected:o,bundleHosts:s}=await Whe({projectDir:F,skillsRoot:a,targets:e});fe?.(`files`),q(t,200,Ite,{targets:e,reprojected:o,bundleHosts:s,removedFrom:i.filter(e=>!r.has(e))},{handler:`skill-targets-put`})}catch(e){G(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`}),Ka=J(ft,async(e,t,n)=>{try{let e=xX(n,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!sa(n.name,t,`skill-restore`)||ma(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let i=w?.current;if(!i){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let a=await X_e({shadow:i,contentDir:r,contentRoot:se??`.`,name:n.name,version:n.version});if(!a.ok){let[e,n]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[a.code];G(t,e,n,a.error,{handler:`skill-restore`,detail:a.code});return}let o=[],s=pY(B(r,`.ok`,`skills`,n.name),n.name);s.ok||o.push(`Restored, but the skill no longer validates: ${s.errors.join(` `)}`),o.push("Run `install` to push the restored version to your editors."),jn(e,kn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Nn(`skill-restore`),fe?.(`files`),q(t,200,_e,{name:n.name,version:n.version,restoredFiles:a.restoredFiles,warnings:o},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),qa=J(De,async(e,t,r)=>{try{let e=xX(r,xe);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!sa(r.name,t,`skill-update`)||ma(r.name,t,`skill-update`))return;if(!xY(r.name)){G(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(r.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let i=Ihe(r.name);if(i===null||i.version===void 0){G(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let a=B(ua(`project`),r.name,`SKILL.md`);if(!V(a)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let o;try{o=SY(H(a,`utf-8`))}catch{}let s,c=w?.current;if(c)try{let e=ie?.()??`main`;s=(await aB(c,se??`.`,[Xz],e,`Before updating ${r.name} (${o??`unversioned`} → ${i.version})`)).checkpointRef}catch(e){U(`skills`).warn({err:e,skill:r.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=Un(`project`,r.name);if($i(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=_n(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{YI(m.dc.document,i.content,`agent`)},m.origin);let h=await xt(l);if(h?.kind===`failure`){wt(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){Tt(t,`skill-update`);return}jn(e,kn(`skill`,``,r.name),`skill-pack-update: ${r.name} (${o??`unversioned`} → ${i.version})`),await Nn(`skill-update`),fe?.(`files`),q(t,200,bee,{name:r.name,version:i.version,...o===void 0?{}:{previousVersion:o},...s===void 0?{}:{checkpointRef:s}},{handler:`skill-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function Ja(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])=>Kr({kind:`folder`,path:e,modifiedTs:t}))}function Ya(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 Xa(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Za(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 Qa(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function $a(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function eo(e,t,n,r){let i=r.documents.filter(e=>!m(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Ne?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Ne.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Ne.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Fe?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Ne.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function to(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`?Ya(e.document.content,t):void 0}}async function no(e){let t=performance.now();if(fo())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await po(),i=await eo(e.query,e.intent,e.semanticParam,n),a=gee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>to(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},Ame({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 ro(){let e=ua(`project`);if(!V(e))return[];let t;try{t=Uo(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!Xt.test(r.name))continue;let t=B(e,r.name,`SKILL.md`);try{let e=Yo(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function io(){let e=[];for(let t of ro()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=na(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(Kr({kind:`page`,path:Un(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function ao(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let oo=new Map;async function so(){let e=[],t=[],n=new Set;for(let[r,i]of s()){if(ZI(r)||QI(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(Kr({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=ao(i),o=oo.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await fs(i.canonicalPath,`utf-8`)}catch(e){l=!0,console.warn(`[search] Failed to read ${r}:`,e)}if(!l)try{c=_B(s,r)}catch(e){console.warn(`[search] Failed to extract title for ${r}:`,e)}let u=Kr({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||oo.set(r,{key:a,doc:u}),e.push(u)}for(let e of oo.keys())n.has(e)||oo.delete(e);let r=Gve(),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),U(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),Nve().add(1)),{documents:[...e,...io(),...i,...Ja([...e,...i])],truncated:a}}function co(){return ro().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function lo(){return f?`gen:${f()}|skills${co()}`:`${[...s()].filter(([e])=>!ZI(e)&&!QI(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${ao(t)}`).join(``)}|skills${co()}`}let uo=Ee===void 0;Ee?.then(()=>{uo=!0},e=>{uo=!0,vQ.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function fo(){return!uo}async function po(){let e=`${r}${F??``}`,t=lo(),n=ZQ.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 i=so().then(({documents:e,truncated:t})=>({corpus:T(e),truncated:t}));ZQ.set(e,{fingerprint:t,pending:i});try{let n=await i;return ZQ.get(e)?.pending===i&&ZQ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw ZQ.get(e)?.pending===i&&ZQ.delete(e),t}}function mo(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{po().catch(e=>{console.warn(`[search] Failed to prewarm workspace search cache:`,e)})},e)}mo();async function ho(e,t){if(e.method===`GET`)return go(e,t);if(e.method===`POST`)return vo(e,t);G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`search`,extraHeaders:{Allow:`GET, POST`}})}let go=J(M,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`limit`),i=n.searchParams.get(`query`)??``,a=Xa(n.searchParams.get(`intent`)),o=ga(n.searchParams.get(`ranking`)),s=Za(n.searchParams.get(`scope`)??n.searchParams.get(`scopes`)),c=Qa(n.searchParams.get(`semantic`)),l=$a(n.searchParams.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}try{q(t,200,ti,await no({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-get`,cause:e})}},{handler:`search-get`,method:`GET`,skipBodyParse:!0}),vo=J(wte,async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Xa(n.intent),a=ga(n.ranking),o=Za(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Qa(n.semantic),l=$a(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}try{q(t,200,ti,await no({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to search workspace.`,{handler:`search-post`,cause:e})}},{handler:`search-post`,method:`POST`}),yo=J(M,async(e,t)=>{try{q(t,200,cee,{...await jJ($o())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill install state.`,{handler:`skill-install-state`,cause:e})}},{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>eZ(e,t,{handler:`skill-install-state`})});async function xo(e,t){if(eZ(e,t,{handler:`handoff`}))try{await che(e,t,{contentDir:r,platform:process.platform,isSchemeRegistered:ot.probeWithCache})}catch(e){t.headersSent||(vQ.error({err:e},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:e}))}}async function R(e,t){if(eZ(e,t,{handler:`spawn-cursor`}))try{await lW(e,t,{contentDir:r,platform:process.platform})}catch(e){t.headersSent||(vQ.error({err:e},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:e}))}}let To=J(Hr,async(e,t,n)=>{try{if(!F){gq(`no-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`no-remote`},{handler:fq});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!pq(e,n.kind)){gq(`invalid-path`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`invalid-path`},{handler:fq});return}let i=Sq(F);if(i===null){if(Oq(F).kind===`no-remote`){gq(`no-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`no-remote`},{handler:fq});return}gq(`detached-head`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`detached-head`},{handler:fq});return}let a=Oq(F);if(a.kind===`no-remote`){gq(`no-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`no-remote`},{handler:fq});return}if(a.kind===`non-github`||a.host!==`github.com`){gq(`non-github-remote`,{kind:n.kind}),q(t,200,ei,{ok:!1,error:`non-github-remote`},{handler:fq});return}if(!Mq(F,i)){gq(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,ei,{ok:!1,error:`branch-not-on-origin`,branch:i},{handler:fq});return}let o=WQ(F,r);if(o===null)throw Error(`content dir is not contained within the project dir`);let s=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;o!==``&&s&&U(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=mq(a.owner,a.repo,i,n.docPath);else{let e=n.folderPath===``?o:n.folderPath;c=hq(a.owner,a.repo,i,e)}let l=`https://openknowledge.ai/d/${dne(c)}`,u=await vq(F,i,o===``?e:e===``?o:`${o}/${e}`,n.kind);gq(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,ei,{ok:!0,shareUrl:l,sharedUrl:c,branch:i,freshness:u},{handler:fq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:fq,cause:e})}},{handler:fq,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:fq})}),Eo=J(M,async(e,t)=>{try{if(!F){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:EX});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(!ite(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:EX});return}if(!TX(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:EX});return}q(t,200,Xee,await lge(F,r,i,a),{handler:EX})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:EX,cause:e})}},{handler:EX,method:`GET`,skipBodyParse:!0}),Oo=J(Tte,async(e,t,n)=>{try{if(!F){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Jq});return}if(!TX(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:Jq});return}let e=WQ(F,r);if(e===null)throw Error(`content dir is not contained within the project dir`);let i=e===``?n.path:n.path===``?e:`${e}/${n.path}`;q(t,200,_ee,await Zq(F,n.branch,i,n.kind),{handler:Jq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Jq,cause:e})}},{handler:Jq,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Jq})}),ko=J(qee,async(e,t,n)=>{if(xX(n,xe).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:DX});return}if(!F){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:DX});return}try{q(t,200,Iee,await hi(()=>mge(F,n.branch,{fastForward:n.fastForward===!0})),{handler:DX})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:DX,cause:e})}},{handler:DX,method:`POST`});async function Ao(e){let[t,...n]=ye,r=[...n,...e];return await new Promise((e,n)=>{let i=_o(t,r,nV({...Qr,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},Iq),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 ${Iq}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=qq(Buffer.concat(c).toString(`utf-8`)).slice(0,500);console.warn(`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let jo=J(M,async(e,t)=>{if(!qe.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:Nq,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ao([`share`,`owners`,`--json`]),n=Bq(zq(e));Kq(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,kte,n,{handler:Nq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Nq,cause:e})}finally{qe.release(`/api/share/publish/owners`)}},{handler:Nq,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>eZ(e,t,{handler:Nq})}),Mo=J(M,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!Rq(r)||!Lq(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:Pq});return}if(!qe.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:Pq,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ao([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Hq(zq(e));Kq(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,Ree,n,{handler:Pq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Pq,cause:e})}finally{qe.release(`/api/share/publish/name-check`)}},{handler:Pq,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>eZ(e,t,{handler:Pq})}),No=J(fee,async(e,t,n)=>{if(!F){Kq(`publish-create`,`no-project`),q(t,200,te,{ok:!1,error:`no-project`},{handler:Fq});return}if(!Rq(n.owner)||!Lq(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:Fq});return}if(!qe.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:Fq,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,F,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Ao(e),i=Gq(zq(r));Kq(`publish-create`,i.ok?`ok`:i.error),i.ok&&ve?.()?.refreshRemote().catch(()=>{}),q(t,200,te,i,{handler:Fq})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Fq,cause:e})}finally{qe.release(`/api/share/publish`)}},{handler:Fq,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Fq})}),Fo=J(jte,async(e,t,n)=>{try{let e=U(`renderer`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,mee,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:`client-logs`})}),Io=F?gH(F):null;async function Lo(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=e.headers.host,r={collabUrl:n?`ws://${n}/collab`:null,previewUrl:null,port:Io?Oi(Io)?.port??0:0,singleFile:Ve};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,fte,r,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let zo=`local-op-embeddings-set-key`,Bo=`local-op-embeddings-clear-key`,Vo=`/api/local-op/embeddings`,Ho=J(uee,async(e,t,n)=>{if(!qe.tryAcquire(Vo)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:zo,extraHeaders:{"Retry-After":`5`}});return}try{await new GU(Ie).set(n.key),q(t,200,Gt,{keyPresent:!0},{handler:zo,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:zo,cause:e})}finally{qe.release(Vo)}},{handler:zo,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:zo})}),Wo=J(M,async(e,t)=>{if(!qe.tryAcquire(Vo)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Bo,extraHeaders:{"Retry-After":`5`}});return}try{await KU(Ie),q(t,200,Gt,{keyPresent:!1},{handler:Bo,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Bo,cause:e})}finally{qe.release(Vo)}},{handler:Bo,method:`POST`,preBodyGate:(e,t)=>eZ(e,t,{handler:Bo})}),Ko=J(M,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Ne){let t=Ne.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let o=await new GU(Ie).get(),s=process.env.OK_EMBEDDINGS_API_KEY??null,c=o?`file`:s?`env`:null,l=c!==null,u=o??s,d=u&&u.length>=8?u.slice(-4):null,f=0;for(let[e]of a())!ZI(e)&&!QI(e)&&!m(e)&&(f+=1);q(t,200,Vee,{enabled:e,keyPresent:l,keySource:c,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0});async function qo(e,t){let n=Le?.()??u;try{return(await Mt(e,WK(r,n,{docName:t,onProblem:e=>vQ.warn({problem:e,docName:t},`[lint] native config problem`)}),t)).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1}))}catch(e){return vQ.warn({err:e,docName:t},`[lint] advisory lint pass failed post-write; omitting advisories`),[]}}let Jo=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!QQ(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let i=Le?.()??u,a=[],o=HK(r,n??void 0,e=>a.push(e));q(t,200,vr,{effective:UK(i,o),configFile:o?.file??null,configProblems:a},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Xo=J(Pee,async(e,t,n)=>{let i;try{i=iq(B(r),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(i.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${i.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}try{let e=Le?.()??u,n=[],i=HK(r,void 0,e=>n.push(e));q(t,200,vr,{effective:UK(e,i),configFile:i?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),es=e=>{let n=e.replace(/\.(md|mdx)$/i,``),r=t.documents.get(n);return r===void 0?null:r.getText(`source`).toString()},ts=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!QQ(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let i=VQ(r,n);if(i===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let a=Le?.()??u;q(t,200,ze,await GK({projectDir:F??r,contentDir:r,baseConfig:a,docRelPath:i,liveSourceFor:es}),{handler:`lint`})}catch(e){if(e instanceof fG){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),ns=J(M,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),i=n===null||n===``?void 0:n;if(i!==void 0&&!kQ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let a=Le?.()??u;q(t,200,Ge,await qK({projectDir:F??r,contentDir:r,baseConfig:a,targetPath:i,liveSourceFor:es}),{handler:`lint-audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),rs=J(jee,async(t,i,a)=>{try{let t=MQ(a.docName,i,`lint-fix`);if(t===null)return;let o=gt(t),s=xX(a,xe);if(s.kind===`invalid-summary`){G(i,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=s.kind===`anonymous`?`principal-anonymous`:s.writerId,l=s.kind===`anonymous`?`Anonymous`:s.displayName,d=s.kind===`anonymous`?c:s.colorSeed,f=s.kind===`agent`?s.clientName:void 0;if(ZI(o)||QI(o)){G(i,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`lint-fix`});return}let p=VQ(r,o);if(p===null){G(i,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}NQ(B(r,p),r);let m=Le?.()??u,{stored:h}=Sn(s.summary),g=await n.getSession(o,c,{displayName:l,colorSeed:d,clientName:f}),_=g.dc.document.getText(`source`).toString(),{cfg:v,before:y,fixed:b}=await KK({projectDir:F??r,contentDir:r,baseConfig:m,docRelPath:p,source:_}),x=y,S;if(b!==_){try{let t=pn(f),n=cn[t]??Wn(d??c);he?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:o,mode:`writing`,ts:Date.now()}),g.dc.document.transact(()=>{jL(g.dc.document,b,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:o}:void 0)},g.origin),s.kind!==`anonymous`&&Oz(o,c,l,d,void 0,s.kind===`agent`?vn({clientName:s.clientName,clientVersion:s.clientVersion,label:s.label}):s.actor,h)}finally{he?.touchMode(c,`idle`)}let t=await xt(o);if(t?.kind===`failure`){wt(i,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Tt(i,`lint-fix`);return}bt(o,`lint-fix`);try{x=await Mt(g.dc.document.getText(`source`).toString(),v,p)}catch(e){S=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,vQ.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),x=y}}let C=x.filter(e=>e.severity===`error`).length,w=x.length-C;q(i,200,Dee,{file:p,fixedCount:Math.max(0,y.length-x.length),diagnostics:x,errorCount:C,warningCount:w,...S?{warning:S}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof fG){G(i,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof bL){xL(i,e,`lint-fix`);return}if(e instanceof TL){EL(i,e,`lint-fix`);return}if(e instanceof ML){G(i,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}vQ.error({err:e},`[lint-fix] handler failed`),G(i,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),is=`link-preview`,as=new t_e({cacheDir:Ve?null:B(F??r,`.ok`,`local`,`link-previews`)}),os=null,ss=()=>(os??=as.init(),os),cs=He??UX;async function ls(e){let t=await cs(e);return t.ok?{ok:!0,metadata:await $ge({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:cs})}:{ok:!1,reason:t.reason}}let us=()=>{try{return We?.()===!0}catch{return!1}},ds={"/api/config":Lo,"/api/asset":Sr,"/api/asset-text":Tr,"/api/document":Rn,"/api/documents":zn,"/api/backlinks":Vn,"/api/backlink-counts":Hn,"/api/link-preview":J(mte,async(e,t,n)=>{try{if(!us()){vQ.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Or,{ok:!1,reason:`disabled`},{handler:is});return}await ss();let e=!1,r=await as.load(n.url,()=>(e=!0,ls(n.url)));as.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};vQ.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,Or,i,{handler:is})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:is,cause:e})}},{handler:is,method:`POST`,preBodyGate:(e,t)=>{let n=i_e({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:is}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:is}),!1)}}),"/api/forward-links":Gn,"/api/link-graph":Kn,"/api/dead-links":Yn,"/api/orphans":qn,"/api/hubs":Jn,"/api/tags":Hi,"/api/pages":zr,"/api/folder-config":Yi,"/api/template":ta,"/api/templates":ea,"/api/skill":Sa,"/api/skill-file":Ba,"/api/skills":xa,"/api/skills/management":Da,"/api/skill/install":Va,"/api/skill/uninstall":Ha,"/api/skill/restore":Ka,"/api/skill/update":qa,"/api/skill-targets":Ua,"/api/search":ho,"/api/semantic-status":Ko,"/api/lint/config":Jo,"/api/lint/markdownlint-config":Xo,"/api/lint":ts,"/api/lint/audit":ns,"/api/lint/fix":rs,"/api/suggest-links":Br,"/api/page-headings":jr,"/api/create-page":Dr,"/api/create-folder":kr,"/api/duplicate-path":Ar,"/api/rename-path":Mr,"/api/delete-path":Pr,"/api/trash/cleanup":Fr,"/api/upload":qr,"/api/agent-write":Pn,"/api/agent-write-md":Fn,"/api/frontmatter-patch":In,"/api/agent-patch":Xn,"/api/agent-undo":Zn,"/api/agent-activity":Qn,"/api/agent-burst-diff":tr,"/api/save-version":sr,"/api/history":cr,"/api/rollback":ur,"/api/metrics/reconciliation":fr,"/api/metrics/parse-health":pr,"/api/metrics/agent-presence":gr,"/api/__embed-detect":yr,"/api/server-info":mr,"/api/share/construct-url":To,"/api/share/target-status":Oo,"/api/git/branch-info":Eo,"/api/git/checkout":ko,"/api/share/publish/owners":jo,"/api/share/publish/name-check":Mo,"/api/share/publish":No,"/api/principal":hr,"/api/rescue":Er,"/api/workspace":xr,"/api/sync/status":Mi,"/api/sync/trigger":Ni,"/api/sync/conflicts":Pi,"/api/sync/conflict-content":Ii,"/api/sync/resolve-conflict":Fi,"/api/local-op/clone":ri,"/api/local-op/ok-init":si,"/api/local-op/auth/login":yi,"/api/local-op/auth/status":Si,"/api/local-op/auth/repos":wi,"/api/local-op/auth/signout":Di,"/api/local-op/auth/set-identity":ji,"/api/local-op/embeddings/set-key":Ho,"/api/local-op/embeddings/clear-key":Wo,"/api/installed-agents":Vi,"/api/spawn-cursor":R,"/api/handoff":xo,"/api/install-skill":Bi,"/api/skill/install-state":yo,"/api/seed/plan":Li,"/api/seed/apply":Ri,"/api/seed/packs":zi,"/api/client-logs":Fo};C&&(ds[`/api/test-reset`]=rr,ds[`/api/test-flush-git`]=nr,ds[`/api/test-rescan-backlinks`]=ir,ds[`/api/test-rescan-files`]=or);let ps=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/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/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),ms=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;let r=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};if(gme({ts:Date.now(),url:n,method:e.method??``,ua:r(`user-agent`),origin:r(`origin`),referer:r(`referer`),host:r(`host`),remote:e.socket?.remoteAddress,secChUa:r(`sec-ch-ua`),secChUaMobile:r(`sec-ch-ua-mobile`),secChUaPlatform:r(`sec-ch-ua-platform`),secFetchSite:r(`sec-fetch-site`),secFetchDest:r(`sec-fetch-dest`),secFetchMode:r(`sec-fetch-mode`),secFetchUser:r(`sec-fetch-user`)}),n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!NR(n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${jt.protocol}, ${jt.runtime}, ${jt.kind}`)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(ps.has(n)||ms.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!lZ(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Ve&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!lZ(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!uZ(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!n.startsWith(`/api/`))return;let i=li.extract(fi.active(),e.headers),a=e.method??`GET`,o=n;n.startsWith(`/api/history/`)?o=`/api/history/:sha`:n.startsWith(`/api/tags/`)?o=`/api/tags/:name`:ds[n]||(o=`/api/*`);let s=UI(),c=Date.now();await fi.with(i,()=>s.startActiveSpan(`HTTP ${a} ${o}`,{kind:Lte.SERVER,attributes:{[kw]:a,[Hw]:o,[BE]:n,[HE]:`http`,[UE]:e.headers[`user-agent`]??``}},async r=>{try{let i=ds[n],o=!1;if(i)o=!0,await i(e,t);else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&(o=!0,await lr(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await Ui(e,t,r))}o||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${a} ${n}`});let s=t.statusCode;r.setAttribute(Vw,s),s>=500&&r.setStatus({code:ci.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:ci.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:o,cause:e}),e}finally{r.end();let e=(Date.now()-c)/1e3;kve().record(e,{[kw]:a,[Hw]:o,[Vw]:t.statusCode})}}))}}}function e$(e){let t=e?.code;return typeof t==`string`?t:void 0}function cye(e){let t;try{t=Uo(e.contentDir,{withFileTypes:!0})}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&aL(n.name,Wt)&&e.basenameIndex.add(n.name)}async function t$(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await ps(i,{withFileTypes:!0})}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=R(i,o.name),s=yB(z(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await us(a)}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await ms(a)}catch(t){let n=e$(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!bB(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await gs(i)}catch(t){let n=e$(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()&&aL(a,Nr)&&!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()&&aL(a,Nr)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}var n$=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const r$=U(`conflict-storage`);var i$=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=R(gH(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){r$.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){r$.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=So(this.storePath);V(e)||Ro(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};Qo(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){r$.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-Dw3ybSQC.mjs`),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=B(this.projectDir),r=B(t,e);if(!bB(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);Qo(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),r$.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await zz(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){r$.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}),r$.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}};function a$(e){let t=e.scheduler??Oe,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 o$(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function s$(e){if(!V(e))return{};let t;try{t=(0,YN.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(!o$(t))return{};let n=t.telemetry;if(!o$(n))return{};let r=n.localSink;return o$(r)?r:{}}function c$(e){return typeof e==`boolean`?e:void 0}function lye(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function l$(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function u$(e){if(o$(e))return lye(e.maxBytes)}function uye(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=s$(tP(`project`,e.projectDir)),n=s$(tP(`project-local`,e.projectDir));if((c$(n.enabled)??c$(t.enabled)??!0)===!1)return null;let r=u$(n.spans)??u$(t.spans)??52428800,i=u$(n.logs)??u$(t.logs)??26214400,a=l$(n.attributeDenylist)??l$(t.attributeDenylist)??hr;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var d$;(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})(d$||={});var dye;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(dye||={});const f$=d$.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),p$=e=>{switch(typeof e){case`undefined`:return f$.undefined;case`string`:return f$.string;case`number`:return Number.isNaN(e)?f$.nan:f$.number;case`boolean`:return f$.boolean;case`function`:return f$.function;case`bigint`:return f$.bigint;case`symbol`:return f$.symbol;case`object`:return Array.isArray(e)?f$.array:e===null?f$.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?f$.promise:typeof Map<`u`&&e instanceof Map?f$.map:typeof Set<`u`&&e instanceof Set?f$.set:typeof Date<`u`&&e instanceof Date?f$.date:f$.object;default:return f$.unknown}},Y=d$.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 m$=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,d$.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()}};m$.create=e=>new m$(e);const h$=(e,t)=>{let n;switch(e.code){case Y.invalid_type:n=e.received===f$.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,d$.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:n=`Unrecognized key(s) in object: ${d$.joinValues(e.keys,`, `)}`;break;case Y.invalid_union:n=`Invalid input`;break;case Y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${d$.joinValues(e.options)}`;break;case Y.invalid_enum_value:n=`Invalid enum value. Expected ${d$.joinValues(e.options)}, received '${e.received}'`;break;case Y.invalid_arguments:n=`Invalid function arguments`;break;case Y.invalid_return_type:n=`Invalid function return type`;break;case Y.invalid_date:n=`Invalid date`;break;case Y.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}"`:d$.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Y.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 Y.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 Y.custom:n=`Invalid input`;break;case Y.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Y.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Y.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,d$.assertNever(e)}return{message:n}};let fye=h$;function g$(){return fye}const _$=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 X(e,t){let n=g$(),r=_$({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===h$?void 0:h$].filter(e=>!!e)});e.common.issues.push(r)}var v$=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 y$;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 y$;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 y$=Object.freeze({status:`aborted`}),b$=e=>({status:`dirty`,value:e}),x$=e=>({status:`valid`,value:e}),S$=e=>e.status===`aborted`,C$=e=>e.status===`dirty`,w$=e=>e.status===`valid`,T$=e=>typeof Promise<`u`&&e instanceof Promise;var E$;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(E$||={});var D$=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 O$=(e,t)=>{if(w$(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 m$(e.common.issues);return this._error=t,this._error}}};function k$(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 A$=class{get description(){return this._def.description}_getType(e){return p$(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:p$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v$,ctx:{common:e.parent.common,data:e.data,parsedType:p$(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(T$(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:p$(e)};return O$(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:p$(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return w$(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=>w$(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:p$(e)},r=this._parse({data:e,path:n.path,parent:n});return O$(n,await(T$(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:Y.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 c1({schema:this,typeName:Z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return l1.create(this,this._def)}nullable(){return u1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K$.create(this)}promise(){return s1.create(this,this._def)}or(e){return Y$.create([this,e],this._def)}and(e){return Q$.create(this,e,this._def)}transform(e){return new c1({...k$(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new d1({...k$(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new m1({typeName:Z.ZodBranded,type:this,...k$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new f1({...k$(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return h1.create(this,e)}readonly(){return g1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const pye=/^c[^\s-]{8,}$/i,mye=/^[0-9a-z]+$/,hye=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gye=/^[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,_ye=/^[a-z0-9_-]{21}$/i,vye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yye=/^[-+]?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)?)??$/,bye=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let j$;const xye=/^(?:(?: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])$/,Sye=/^(?:(?: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])$/,Cye=/^(([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]))$/,wye=/^(([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])$/,Tye=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Eye=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,M$=`((\\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])))`,Dye=RegExp(`^${M$}$`);function N$(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 Oye(e){return RegExp(`^${N$(e)}$`)}function kye(e){let t=`${M$}T${N$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Aye(e,t){return!!((t===`v4`||!t)&&xye.test(e)||(t===`v6`||!t)&&Cye.test(e))}function jye(e,t){if(!vye.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 Mye(e,t){return!!((t===`v4`||!t)&&Sye.test(e)||(t===`v6`||!t)&&wye.test(e))}var P$=class e extends A${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f$.string){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.string,received:t.parsedType}),y$}let t=new v$,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:Y.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),X(n,{code:Y.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?X(n,{code:Y.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&X(n,{code:Y.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)bye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`email`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)j$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),j$.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`emoji`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)gye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`uuid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)_ye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`nanoid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)pye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`cuid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)mye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`cuid2`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)hye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`ulid`,code:Y.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),X(n,{validation:`url`,code:Y.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),X(n,{validation:`regex`,code:Y.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),X(n,{code:Y.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),X(n,{code:Y.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?kye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Dye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Oye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?yye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`duration`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Aye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`ip`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?jye(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`jwt`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Mye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`cidr`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Tye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Eye.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64url`,code:Y.invalid_string,message:r.message}),t.dirty()):d$.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Y.invalid_string,...E$.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...E$.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...E$.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...E$.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...E$.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...E$.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...E$.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...E$.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...E$.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...E$.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...E$.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...E$.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...E$.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...E$.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,...E$.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,...E$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...E$.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...E$.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...E$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...E$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...E$.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...E$.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...E$.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...E$.errToObj(t)})}nonempty(e){return this.min(1,E$.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}};P$.create=e=>new P$({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...k$(e)});function Nye(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 F$=class e extends A${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)!==f$.number){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.number,received:t.parsedType}),y$}let t,n=new v$;for(let r of this._def.checks)r.kind===`int`?d$.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),X(t,{code:Y.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),X(t,{code:Y.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),X(t,{code:Y.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Nye(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),X(t,{code:Y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),X(t,{code:Y.not_finite,message:r.message}),n.dirty()):d$.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,E$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E$.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:E$.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:E$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:E$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:E$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:E$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E$.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:E$.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:E$.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:E$.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`&&d$.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)}};F$.create=e=>new F$({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...k$(e)});var I$=class e extends A${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)!==f$.bigint)return this._getInvalidInput(e);let t,n=new v$;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),X(t,{code:Y.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),X(t,{code:Y.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),X(t,{code:Y.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):d$.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.bigint,received:t.parsedType}),y$}gte(e,t){return this.setLimit(`min`,e,!0,E$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E$.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:E$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:E$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:E$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:E$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E$.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}};I$.create=e=>new I$({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...k$(e)});var L$=class extends A${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f$.boolean){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.boolean,received:t.parsedType}),y$}return x$(e.data)}};L$.create=e=>new L$({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...k$(e)});var R$=class e extends A${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f$.date){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.date,received:t.parsedType}),y$}if(Number.isNaN(e.data.getTime()))return X(this._getOrReturnCtx(e),{code:Y.invalid_date}),y$;let t=new v$,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:Y.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),X(n,{code:Y.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):d$.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:E$.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:E$.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)}};R$.create=e=>new R$({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...k$(e)});var z$=class extends A${_parse(e){if(this._getType(e)!==f$.symbol){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.symbol,received:t.parsedType}),y$}return x$(e.data)}};z$.create=e=>new z$({typeName:Z.ZodSymbol,...k$(e)});var B$=class extends A${_parse(e){if(this._getType(e)!==f$.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.undefined,received:t.parsedType}),y$}return x$(e.data)}};B$.create=e=>new B$({typeName:Z.ZodUndefined,...k$(e)});var V$=class extends A${_parse(e){if(this._getType(e)!==f$.null){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.null,received:t.parsedType}),y$}return x$(e.data)}};V$.create=e=>new V$({typeName:Z.ZodNull,...k$(e)});var H$=class extends A${constructor(){super(...arguments),this._any=!0}_parse(e){return x$(e.data)}};H$.create=e=>new H$({typeName:Z.ZodAny,...k$(e)});var U$=class extends A${constructor(){super(...arguments),this._unknown=!0}_parse(e){return x$(e.data)}};U$.create=e=>new U$({typeName:Z.ZodUnknown,...k$(e)});var W$=class extends A${_parse(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.never,received:t.parsedType}),y$}};W$.create=e=>new W$({typeName:Z.ZodNever,...k$(e)});var G$=class extends A${_parse(e){if(this._getType(e)!==f$.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.void,received:t.parsedType}),y$}return x$(e.data)}};G$.create=e=>new G$({typeName:Z.ZodVoid,...k$(e)});var K$=class e extends A${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==f$.array)return X(t,{code:Y.invalid_type,expected:f$.array,received:t.parsedType}),y$;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(X(t,{code:e?Y.too_big:Y.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&&(X(t,{code:Y.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&&(X(t,{code:Y.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 D$(t,e,t.path,n)))).then(e=>v$.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new D$(t,e,t.path,n)));return v$.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:E$.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:E$.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:E$.toString(n)}})}nonempty(e){return this.min(1,e)}};K$.create=(e,t)=>new K$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...k$(t)});function q$(e){if(e instanceof J$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=l1.create(q$(r))}return new J$({...e._def,shape:()=>t})}else if(e instanceof K$)return new K$({...e._def,type:q$(e.element)});else if(e instanceof l1)return l1.create(q$(e.unwrap()));else if(e instanceof u1)return u1.create(q$(e.unwrap()));else if(e instanceof $$)return $$.create(e.items.map(e=>q$(e)));else return e}var J$=class e extends A${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=d$.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f$.object){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.object,received:t.parsedType}),y$}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof W$&&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 D$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof W$){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&&(X(n,{code:Y.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 D$(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=>v$.mergeObjectSync(t,e)):v$.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return E$.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:E$.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of d$.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 d$.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return q$(this)}partial(t){let n={};for(let e of d$.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 d$.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof l1;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return i1(d$.objectKeys(this.shape))}};J$.create=(e,t)=>new J$({shape:()=>e,unknownKeys:`strip`,catchall:W$.create(),typeName:Z.ZodObject,...k$(t)}),J$.strictCreate=(e,t)=>new J$({shape:()=>e,unknownKeys:`strict`,catchall:W$.create(),typeName:Z.ZodObject,...k$(t)}),J$.lazycreate=(e,t)=>new J$({shape:e,unknownKeys:`strip`,catchall:W$.create(),typeName:Z.ZodObject,...k$(t)});var Y$=class extends A${_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 m$(e.ctx.common.issues));return X(t,{code:Y.invalid_union,unionErrors:n}),y$}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 m$(e));return X(t,{code:Y.invalid_union,unionErrors:i}),y$}}get options(){return this._def.options}};Y$.create=(e,t)=>new Y$({options:e,typeName:Z.ZodUnion,...k$(t)});const X$=e=>e instanceof n1?X$(e.schema):e instanceof c1?X$(e.innerType()):e instanceof r1?[e.value]:e instanceof a1?e.options:e instanceof o1?d$.objectValues(e.enum):e instanceof d1?X$(e._def.innerType):e instanceof B$?[void 0]:e instanceof V$?[null]:e instanceof l1?[void 0,...X$(e.unwrap())]:e instanceof u1?[null,...X$(e.unwrap())]:e instanceof m1||e instanceof g1?X$(e.unwrap()):e instanceof f1?X$(e._def.innerType):[];var Pye=class e extends A${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$.object)return X(t,{code:Y.invalid_type,expected:f$.object,received:t.parsedType}),y$;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}):(X(t,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),y$)}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=X$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...k$(r)})}};function Z$(e,t){let n=p$(e),r=p$(t);if(e===t)return{valid:!0,data:e};if(n===f$.object&&r===f$.object){let n=d$.objectKeys(t),r=d$.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Z$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===f$.array&&r===f$.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=Z$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===f$.date&&r===f$.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Q$=class extends A${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(S$(e)||S$(r))return y$;let i=Z$(e.value,r.value);return i.valid?((C$(e)||C$(r))&&t.dirty(),{status:t.value,value:i.data}):(X(n,{code:Y.invalid_intersection_types}),y$)};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}))}};Q$.create=(e,t,n)=>new Q$({left:e,right:t,typeName:Z.ZodIntersection,...k$(n)});var $$=class e extends A${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f$.array)return X(n,{code:Y.invalid_type,expected:f$.array,received:n.parsedType}),y$;if(n.data.length<this._def.items.length)return X(n,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),y$;!this._def.rest&&n.data.length>this._def.items.length&&(X(n,{code:Y.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 D$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>v$.mergeArray(t,e)):v$.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};$$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new $$({items:e,typeName:Z.ZodTuple,rest:null,...k$(t)})};var Fye=class e extends A${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!==f$.object)return X(n,{code:Y.invalid_type,expected:f$.object,received:n.parsedType}),y$;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new D$(n,e,n.path,e)),value:a._parse(new D$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?v$.mergeObjectAsync(t,r):v$.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof A$?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...k$(r)}):new e({keyType:P$.create(),valueType:t,typeName:Z.ZodRecord,...k$(n)})}},e1=class extends A${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!==f$.map)return X(n,{code:Y.invalid_type,expected:f$.map,received:n.parsedType}),y$;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new D$(n,e,n.path,[a,`key`])),value:i._parse(new D$(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 y$;(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 y$;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};e1.create=(e,t,n)=>new e1({valueType:t,keyType:e,typeName:Z.ZodMap,...k$(n)});var t1=class e extends A${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f$.set)return X(n,{code:Y.invalid_type,expected:f$.set,received:n.parsedType}),y$;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(X(n,{code:Y.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&&(X(n,{code:Y.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 y$;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 D$(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:E$.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:E$.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};t1.create=(e,t)=>new t1({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...k$(t)});var Iye=class e extends A${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$.function)return X(t,{code:Y.invalid_type,expected:f$.function,received:t.parsedType}),y$;function n(e,n){return _$({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g$(),h$].filter(e=>!!e),issueData:{code:Y.invalid_arguments,argumentsError:n}})}function r(e,n){return _$({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,g$(),h$].filter(e=>!!e),issueData:{code:Y.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof s1){let e=this;return x$(async function(...t){let o=new m$([]),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 x$(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new m$([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new m$([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:$$.create(t).rest(U$.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||$$.create([]).rest(U$.create()),returns:n||U$.create(),typeName:Z.ZodFunction,...k$(r)})}},n1=class extends A${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})}};n1.create=(e,t)=>new n1({getter:e,typeName:Z.ZodLazy,...k$(t)});var r1=class extends A${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return X(t,{received:t.data,code:Y.invalid_literal,expected:this._def.value}),y$}return{status:`valid`,value:e.data}}get value(){return this._def.value}};r1.create=(e,t)=>new r1({value:e,typeName:Z.ZodLiteral,...k$(t)});function i1(e,t){return new a1({values:e,typeName:Z.ZodEnum,...k$(t)})}var a1=class e extends A${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return X(t,{expected:d$.joinValues(n),received:t.parsedType,code:Y.invalid_type}),y$}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return X(t,{received:t.data,code:Y.invalid_enum_value,options:n}),y$}return x$(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})}};a1.create=i1;var o1=class extends A${_parse(e){let t=d$.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f$.string&&n.parsedType!==f$.number){let e=d$.objectValues(t);return X(n,{expected:d$.joinValues(e),received:n.parsedType,code:Y.invalid_type}),y$}if(this._cache||=new Set(d$.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=d$.objectValues(t);return X(n,{received:n.data,code:Y.invalid_enum_value,options:e}),y$}return x$(e.data)}get enum(){return this._def.values}};o1.create=(e,t)=>new o1({values:e,typeName:Z.ZodNativeEnum,...k$(t)});var s1=class extends A${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==f$.promise&&t.common.async===!1?(X(t,{code:Y.invalid_type,expected:f$.promise,received:t.parsedType}),y$):x$((t.parsedType===f$.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};s1.create=(e,t)=>new s1({type:e,typeName:Z.ZodPromise,...k$(t)});var c1=class extends A${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{X(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 y$;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?y$:r.status===`dirty`||t.value===`dirty`?b$(r.value):r});{if(t.value===`aborted`)return y$;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?y$:r.status===`dirty`||t.value===`dirty`?b$(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`?y$:(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`?y$:(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(!w$(e))return y$;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=>w$(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):y$);d$.assertNever(r)}};c1.create=(e,t,n)=>new c1({schema:e,typeName:Z.ZodEffects,effect:t,...k$(n)}),c1.createWithPreprocess=(e,t,n)=>new c1({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...k$(n)});var l1=class extends A${_parse(e){return this._getType(e)===f$.undefined?x$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};l1.create=(e,t)=>new l1({innerType:e,typeName:Z.ZodOptional,...k$(t)});var u1=class extends A${_parse(e){return this._getType(e)===f$.null?x$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};u1.create=(e,t)=>new u1({innerType:e,typeName:Z.ZodNullable,...k$(t)});var d1=class extends A${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};d1.create=(e,t)=>new d1({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...k$(t)});var f1=class extends A${_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 T$(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new m$(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new m$(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};f1.create=(e,t)=>new f1({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...k$(t)});var p1=class extends A${_parse(e){if(this._getType(e)!==f$.nan){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:f$.nan,received:t.parsedType}),y$}return{status:`valid`,value:e.data}}};p1.create=e=>new p1({typeName:Z.ZodNaN,...k$(e)});var m1=class extends A${_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}},h1=class e extends A${_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`?y$:e.status===`dirty`?(t.dirty(),b$(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`?y$:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Z.ZodPipeline})}},g1=class extends A${_parse(e){let t=this._def.innerType._parse(e),n=e=>(w$(e)&&(e.value=Object.freeze(e.value)),e);return T$(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};g1.create=(e,t)=>new g1({innerType:e,typeName:Z.ZodReadonly,...k$(t)}),J$.lazycreate;var Z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Z||={}),P$.create,F$.create,p1.create,I$.create,L$.create,R$.create,z$.create,B$.create,V$.create,H$.create,U$.create,W$.create,G$.create,K$.create;const Lye=J$.create;J$.strictCreate,Y$.create,Pye.create,Q$.create,$$.create,Fye.create,e1.create,t1.create,Iye.create,n1.create,r1.create,a1.create,o1.create,s1.create,c1.create,l1.create,u1.create,c1.createWithPreprocess,h1.create;const Rye=C(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Vn.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>et(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ut(e,t,n),e.parseAsync=async(t,n)=>rt(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>he(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)=>Ze(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),zye=C(`ZodMiniObject`,(e,t)=>{g.init(e,t),Rye.init(e,t),bt(e,`shape`,()=>t.shape)});function _1(e,t){return new zye({type:`object`,shape:e??{},...ai(t)})}function v1(e){return!!e._zod}function y1(e){let t=Object.values(e);if(t.length===0)return _1({});let n=t.every(v1),r=t.every(e=>!v1(e));if(n)return _1(e);if(r)return Lye(e);throw Error(`Mixed Zod versions detected in object shape.`)}function b1(e,t){return v1(e)?ut(e,t):e.safeParse(t)}async function x1(e,t){return v1(e)?await he(e,t):await e.safeParseAsync(t)}function S1(e){if(!e)return;let t;if(t=v1(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function C1(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 y1(e)}}if(v1(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 w1(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 Bye(e){return e.description}function Vye(e){if(v1(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function T1(e){if(v1(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 E1=`2025-11-25`,D1=[E1,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],O1=`io.modelcontextprotocol/related-task`,k1=fr(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),A1=Jr([D(),Wr().int()]),j1=D();Jt({ttl:Wr().optional(),pollInterval:Wr().optional()});const Hye=I({ttl:Wr().optional()}),Uye=I({taskId:D()}),M1=Jt({progressToken:A1.optional(),[O1]:Uye.optional()}),N1=I({_meta:M1.optional()}),P1=N1.extend({task:Hye.optional()}),Wye=e=>P1.safeParse(e).success,F1=I({method:D(),params:N1.loose().optional()}),I1=I({_meta:M1.optional()}),L1=I({method:D(),params:I1.loose().optional()}),R1=Jt({_meta:M1.optional()}),z1=Jr([D(),Wr().int()]),B1=I({jsonrpc:jn(`2.0`),id:z1,...F1.shape}).strict(),V1=e=>B1.safeParse(e).success,H1=I({jsonrpc:jn(`2.0`),...L1.shape}).strict(),Gye=e=>H1.safeParse(e).success,U1=I({jsonrpc:jn(`2.0`),id:z1,result:R1}).strict(),W1=e=>U1.safeParse(e).success;var G1;(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`})(G1||={});const K1=I({jsonrpc:jn(`2.0`),id:z1.optional(),error:I({code:Wr().int(),message:D(),data:Et().optional()})}).strict(),q1=e=>K1.safeParse(e).success,J1=Jr([B1,H1,U1,K1]);Jr([U1,K1]);const Y1=R1.strict(),Kye=I1.extend({requestId:z1.optional(),reason:D().optional()}),X1=L1.extend({method:jn(`notifications/cancelled`),params:Kye}),Z1=I({icons:hn(I({src:D(),mimeType:D().optional(),sizes:hn(D()).optional(),theme:un([`light`,`dark`]).optional()})).optional()}),Q1=I({name:D(),title:D().optional()}),$1=Q1.extend({...Q1.shape,...Z1.shape,version:D(),websiteUrl:D().optional(),description:D().optional()}),qye=Zr(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Pn(I({form:Pn(I({applyDefaults:En().optional()}),wt(D(),Et())).optional(),url:k1.optional()}),wt(D(),Et()).optional())),Jye=Jt({list:k1.optional(),cancel:k1.optional(),requests:Jt({sampling:Jt({createMessage:k1.optional()}).optional(),elicitation:Jt({create:k1.optional()}).optional()}).optional()}),Yye=Jt({list:k1.optional(),cancel:k1.optional(),requests:Jt({tools:Jt({call:k1.optional()}).optional()}).optional()}),Xye=I({experimental:wt(D(),k1).optional(),sampling:I({context:k1.optional(),tools:k1.optional()}).optional(),elicitation:qye.optional(),roots:I({listChanged:En().optional()}).optional(),tasks:Jye.optional(),extensions:wt(D(),k1).optional()}),Zye=N1.extend({protocolVersion:D(),capabilities:Xye,clientInfo:$1}),e0=F1.extend({method:jn(`initialize`),params:Zye}),t0=e=>e0.safeParse(e).success,Qye=I({experimental:wt(D(),k1).optional(),logging:k1.optional(),completions:k1.optional(),prompts:I({listChanged:En().optional()}).optional(),resources:I({subscribe:En().optional(),listChanged:En().optional()}).optional(),tools:I({listChanged:En().optional()}).optional(),tasks:Yye.optional(),extensions:wt(D(),k1).optional()}),$ye=R1.extend({protocolVersion:D(),capabilities:Qye,serverInfo:$1,instructions:D().optional()}),n0=L1.extend({method:jn(`notifications/initialized`),params:I1.optional()}),ebe=e=>n0.safeParse(e).success,r0=F1.extend({method:jn(`ping`),params:N1.optional()}),tbe=I({progress:Wr(),total:sn(Wr()),message:sn(D())}),nbe=I({...I1.shape,...tbe.shape,progressToken:A1}),i0=L1.extend({method:jn(`notifications/progress`),params:nbe}),rbe=N1.extend({cursor:j1.optional()}),a0=F1.extend({params:rbe.optional()}),o0=R1.extend({nextCursor:j1.optional()}),ibe=un([`working`,`input_required`,`completed`,`failed`,`cancelled`]),s0=I({taskId:D(),status:ibe,ttl:Jr([Wr(),qn()]),createdAt:D(),lastUpdatedAt:D(),pollInterval:sn(Wr()),statusMessage:sn(D())}),c0=R1.extend({task:s0}),abe=I1.merge(s0),l0=L1.extend({method:jn(`notifications/tasks/status`),params:abe}),u0=F1.extend({method:jn(`tasks/get`),params:N1.extend({taskId:D()})}),d0=R1.merge(s0),f0=F1.extend({method:jn(`tasks/result`),params:N1.extend({taskId:D()})});R1.loose();const p0=a0.extend({method:jn(`tasks/list`)}),m0=o0.extend({tasks:hn(s0)}),h0=F1.extend({method:jn(`tasks/cancel`),params:N1.extend({taskId:D()})}),obe=R1.merge(s0),g0=I({uri:D(),mimeType:sn(D()),_meta:wt(D(),Et()).optional()}),_0=g0.extend({text:D()}),v0=D().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),y0=g0.extend({blob:v0}),b0=un([`user`,`assistant`]),x0=I({audience:hn(b0).optional(),priority:Wr().min(0).max(1).optional(),lastModified:ie({offset:!0}).optional()}),S0=I({...Q1.shape,...Z1.shape,uri:D(),description:sn(D()),mimeType:sn(D()),size:sn(Wr()),annotations:x0.optional(),_meta:sn(Jt({}))}),sbe=I({...Q1.shape,...Z1.shape,uriTemplate:D(),description:sn(D()),mimeType:sn(D()),annotations:x0.optional(),_meta:sn(Jt({}))}),C0=a0.extend({method:jn(`resources/list`)}),cbe=o0.extend({resources:hn(S0)}),w0=a0.extend({method:jn(`resources/templates/list`)}),lbe=o0.extend({resourceTemplates:hn(sbe)}),T0=N1.extend({uri:D()}),ube=T0,E0=F1.extend({method:jn(`resources/read`),params:ube}),dbe=R1.extend({contents:hn(Jr([_0,y0]))}),fbe=L1.extend({method:jn(`notifications/resources/list_changed`),params:I1.optional()}),pbe=T0,mbe=F1.extend({method:jn(`resources/subscribe`),params:pbe}),hbe=T0,gbe=F1.extend({method:jn(`resources/unsubscribe`),params:hbe}),_be=I1.extend({uri:D()}),vbe=L1.extend({method:jn(`notifications/resources/updated`),params:_be}),ybe=I({name:D(),description:sn(D()),required:sn(En())}),bbe=I({...Q1.shape,...Z1.shape,description:sn(D()),arguments:sn(hn(ybe)),_meta:sn(Jt({}))}),D0=a0.extend({method:jn(`prompts/list`)}),xbe=o0.extend({prompts:hn(bbe)}),Sbe=N1.extend({name:D(),arguments:wt(D(),D()).optional()}),O0=F1.extend({method:jn(`prompts/get`),params:Sbe}),k0=I({type:jn(`text`),text:D(),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),A0=I({type:jn(`image`),data:v0,mimeType:D(),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),j0=I({type:jn(`audio`),data:v0,mimeType:D(),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),Cbe=I({type:jn(`tool_use`),name:D(),id:D(),input:wt(D(),Et()),_meta:wt(D(),Et()).optional()}),wbe=I({type:jn(`resource`),resource:Jr([_0,y0]),annotations:x0.optional(),_meta:wt(D(),Et()).optional()}),M0=Jr([k0,A0,j0,S0.extend({type:jn(`resource_link`)}),wbe]),Tbe=I({role:b0,content:M0}),Ebe=R1.extend({description:D().optional(),messages:hn(Tbe)}),Dbe=L1.extend({method:jn(`notifications/prompts/list_changed`),params:I1.optional()}),Obe=I({title:D().optional(),readOnlyHint:En().optional(),destructiveHint:En().optional(),idempotentHint:En().optional(),openWorldHint:En().optional()}),kbe=I({taskSupport:un([`required`,`optional`,`forbidden`]).optional()}),N0=I({...Q1.shape,...Z1.shape,description:D().optional(),inputSchema:I({type:jn(`object`),properties:wt(D(),k1).optional(),required:hn(D()).optional()}).catchall(Et()),outputSchema:I({type:jn(`object`),properties:wt(D(),k1).optional(),required:hn(D()).optional()}).catchall(Et()).optional(),annotations:Obe.optional(),execution:kbe.optional(),_meta:wt(D(),Et()).optional()}),P0=a0.extend({method:jn(`tools/list`)}),Abe=o0.extend({tools:hn(N0)}),F0=R1.extend({content:hn(M0).default([]),structuredContent:wt(D(),Et()).optional(),isError:En().optional()});F0.or(R1.extend({toolResult:Et()}));const jbe=P1.extend({name:D(),arguments:wt(D(),Et()).optional()}),I0=F1.extend({method:jn(`tools/call`),params:jbe}),Mbe=L1.extend({method:jn(`notifications/tools/list_changed`),params:I1.optional()});I({autoRefresh:En().default(!0),debounceMs:Wr().int().nonnegative().default(300)});const L0=un([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Nbe=N1.extend({level:L0}),R0=F1.extend({method:jn(`logging/setLevel`),params:Nbe}),Pbe=I1.extend({level:L0,logger:D().optional(),data:Et()}),Fbe=L1.extend({method:jn(`notifications/message`),params:Pbe}),Ibe=I({hints:hn(I({name:D().optional()})).optional(),costPriority:Wr().min(0).max(1).optional(),speedPriority:Wr().min(0).max(1).optional(),intelligencePriority:Wr().min(0).max(1).optional()}),Lbe=I({mode:un([`auto`,`required`,`none`]).optional()}),Rbe=I({type:jn(`tool_result`),toolUseId:D().describe(`The unique identifier for the corresponding tool call.`),content:hn(M0).default([]),structuredContent:I({}).loose().optional(),isError:En().optional(),_meta:wt(D(),Et()).optional()}),zbe=Qn(`type`,[k0,A0,j0]),z0=Qn(`type`,[k0,A0,j0,Cbe,Rbe]),Bbe=I({role:b0,content:Jr([z0,hn(z0)]),_meta:wt(D(),Et()).optional()}),Vbe=P1.extend({messages:hn(Bbe),modelPreferences:Ibe.optional(),systemPrompt:D().optional(),includeContext:un([`none`,`thisServer`,`allServers`]).optional(),temperature:Wr().optional(),maxTokens:Wr().int(),stopSequences:hn(D()).optional(),metadata:k1.optional(),tools:hn(N0).optional(),toolChoice:Lbe.optional()}),Hbe=F1.extend({method:jn(`sampling/createMessage`),params:Vbe}),B0=R1.extend({model:D(),stopReason:sn(un([`endTurn`,`stopSequence`,`maxTokens`]).or(D())),role:b0,content:zbe}),V0=R1.extend({model:D(),stopReason:sn(un([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D())),role:b0,content:Jr([z0,hn(z0)])}),Ube=I({type:jn(`boolean`),title:D().optional(),description:D().optional(),default:En().optional()}),Wbe=I({type:jn(`string`),title:D().optional(),description:D().optional(),minLength:Wr().optional(),maxLength:Wr().optional(),format:un([`email`,`uri`,`date`,`date-time`]).optional(),default:D().optional()}),Gbe=I({type:un([`number`,`integer`]),title:D().optional(),description:D().optional(),minimum:Wr().optional(),maximum:Wr().optional(),default:Wr().optional()}),Kbe=I({type:jn(`string`),title:D().optional(),description:D().optional(),enum:hn(D()),default:D().optional()}),qbe=I({type:jn(`string`),title:D().optional(),description:D().optional(),oneOf:hn(I({const:D(),title:D()})),default:D().optional()}),Jbe=Jr([Jr([I({type:jn(`string`),title:D().optional(),description:D().optional(),enum:hn(D()),enumNames:hn(D()).optional(),default:D().optional()}),Jr([Kbe,qbe]),Jr([I({type:jn(`array`),title:D().optional(),description:D().optional(),minItems:Wr().optional(),maxItems:Wr().optional(),items:I({type:jn(`string`),enum:hn(D())}),default:hn(D()).optional()}),I({type:jn(`array`),title:D().optional(),description:D().optional(),minItems:Wr().optional(),maxItems:Wr().optional(),items:I({anyOf:hn(I({const:D(),title:D()}))}),default:hn(D()).optional()})])]),Ube,Wbe,Gbe]),Ybe=Jr([P1.extend({mode:jn(`form`).optional(),message:D(),requestedSchema:I({type:jn(`object`),properties:wt(D(),Jbe),required:hn(D()).optional()})}),P1.extend({mode:jn(`url`),message:D(),elicitationId:D(),url:D().url()})]),Xbe=F1.extend({method:jn(`elicitation/create`),params:Ybe}),Zbe=I1.extend({elicitationId:D()}),Qbe=L1.extend({method:jn(`notifications/elicitation/complete`),params:Zbe}),H0=R1.extend({action:un([`accept`,`decline`,`cancel`]),content:Zr(e=>e===null?void 0:e,wt(D(),Jr([D(),Wr(),En(),hn(D())])).optional())}),$be=I({type:jn(`ref/resource`),uri:D()}),exe=I({type:jn(`ref/prompt`),name:D()}),txe=N1.extend({ref:Jr([exe,$be]),argument:I({name:D(),value:D()}),context:I({arguments:wt(D(),D()).optional()}).optional()}),U0=F1.extend({method:jn(`completion/complete`),params:txe});function nxe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function rxe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const ixe=R1.extend({completion:Jt({values:hn(D()).max(100),total:sn(Wr().int()),hasMore:sn(En())})}),axe=I({uri:D().startsWith(`file://`),name:D().optional(),_meta:wt(D(),Et()).optional()}),oxe=F1.extend({method:jn(`roots/list`),params:N1.optional()}),W0=R1.extend({roots:hn(axe)}),sxe=L1.extend({method:jn(`notifications/roots/list_changed`),params:I1.optional()});Jr([r0,e0,U0,R0,O0,D0,C0,w0,E0,mbe,gbe,I0,P0,u0,f0,p0,h0]),Jr([X1,i0,n0,sxe,l0]),Jr([Y1,B0,V0,H0,W0,d0,m0,c0]),Jr([r0,Hbe,Xbe,oxe,u0,f0,p0,h0]),Jr([X1,i0,Fbe,vbe,fbe,Mbe,Dbe,l0,Qbe]),Jr([Y1,$ye,ixe,Ebe,xbe,cbe,lbe,dbe,F0,Abe,d0,m0,c0]);var G0=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===G1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new cxe(e.elicitations,n)}return new e(t,n,r)}},cxe=class extends G0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(G1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function K0(e){return e===`completed`||e===`failed`||e===`cancelled`}const lxe=Symbol(`Let zodToJsonSchema decide on which parser to use`),q0={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`},uxe=e=>typeof e==`string`?{...q0,name:e}:{...q0,...e},dxe=e=>{let t=uxe(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 J0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Y0(e,t,n,r,i){e[t]=n,J0(e,t,r,i)}const X0=(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 Z0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?X0(t,e.currentPath):t.join(`/`)}}function fxe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=u2(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&Y0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&Y0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Y0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),Y0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function pxe(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?Y0(n,`minimum`,r.value,r.message,t):Y0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Y0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Y0(n,`maximum`,r.value,r.message,t):Y0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Y0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Y0(n,`multipleOf`,r.value,r.message,t);break}return n}function mxe(){return{type:`boolean`}}function Q0(e,t){return u2(e.type._def,t)}const hxe=(e,t)=>u2(e.innerType._def,t);function $0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>$0(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 gxe(e,t)}}const gxe=(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`:Y0(n,`minimum`,r.value,r.message,t);break;case`max`:Y0(n,`maximum`,r.value,r.message,t);break}return n};function _xe(e,t){return{...u2(e.innerType._def,t),default:e.defaultValue()}}function vxe(e,t){return t.effectStrategy===`input`?u2(e.schema._def,t):Z0(t)}function yxe(e){return{type:`string`,enum:Array.from(e.values)}}const bxe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function xxe(e,t){let n=[u2(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),u2(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(bxe(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 Sxe(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 e2;const t2={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:()=>(e2===void 0&&(e2=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),e2),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 n2(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:Y0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:Y0(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`:i2(n,`email`,r.message,t);break;case`format:idn-email`:i2(n,`idn-email`,r.message,t);break;case`pattern:zod`:a2(n,t2.email,r.message,t);break}break;case`url`:i2(n,`uri`,r.message,t);break;case`uuid`:i2(n,`uuid`,r.message,t);break;case`regex`:a2(n,r.regex,r.message,t);break;case`cuid`:a2(n,t2.cuid,r.message,t);break;case`cuid2`:a2(n,t2.cuid2,r.message,t);break;case`startsWith`:a2(n,RegExp(`^${r2(r.value,t)}`),r.message,t);break;case`endsWith`:a2(n,RegExp(`${r2(r.value,t)}$`),r.message,t);break;case`datetime`:i2(n,`date-time`,r.message,t);break;case`date`:i2(n,`date`,r.message,t);break;case`time`:i2(n,`time`,r.message,t);break;case`duration`:i2(n,`duration`,r.message,t);break;case`length`:Y0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),Y0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:a2(n,RegExp(r2(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&i2(n,`ipv4`,r.message,t),r.version!==`v4`&&i2(n,`ipv6`,r.message,t);break;case`base64url`:a2(n,t2.base64url,r.message,t);break;case`jwt`:a2(n,t2.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&a2(n,t2.ipv4Cidr,r.message,t),r.version!==`v4`&&a2(n,t2.ipv6Cidr,r.message,t);break;case`emoji`:a2(n,t2.emoji(),r.message,t);break;case`ulid`:a2(n,t2.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:i2(n,`binary`,r.message,t);break;case`contentEncoding:base64`:Y0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:a2(n,t2.base64,r.message,t);break}break;case`nanoid`:a2(n,t2.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function r2(e,t){return t.patternStrategy===`escape`?wxe(e):e}const Cxe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function wxe(e){let t=``;for(let n=0;n<e.length;n++)Cxe.has(e[n])||(t+=`\\`),t+=e[n];return t}function i2(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}}})):Y0(e,`format`,t,n,r)}function a2(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:o2(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Y0(e,`pattern`,o2(t,r),n,r)}function o2(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
1267
1267
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1268
1268
  ]))`;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 s2(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===Z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:u2(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??Z0(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:u2(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=n2(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Z.ZodBranded&&e.keyType._def.type._def.typeName===Z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Q0(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Txe(e,t){return t.mapStrategy===`record`?s2(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[u2(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Z0(t),u2(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Z0(t)],minItems:2,maxItems:2}}}function Exe(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 Dxe(e){return e.target===`openAi`?void 0:{not:Z0({...e,currentPath:[...e.currentPath,`not`]})}}function Oxe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const c2={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function kxe(e,t){if(t.target===`openApi3`)return l2(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in c2&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=c2[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 l2(e,t)}const l2=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>u2(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 Axe(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:c2[e.innerType._def.typeName],nullable:!0}:{type:[c2[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=u2(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=u2(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function jxe(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`,J0(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?Y0(n,`minimum`,r.value,r.message,t):Y0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Y0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Y0(n,`maximum`,r.value,r.message,t):Y0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Y0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Y0(n,`multipleOf`,r.value,r.message,t);break}return n}function Mxe(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=Pxe(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=u2(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=Nxe(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Nxe(e,t){if(e.catchall._def.typeName!==`ZodNever`)return u2(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 Pxe(e){try{return e.isOptional()}catch{return!0}}const Fxe=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return u2(e.innerType._def,t);let n=u2(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Z0(t)},n]}:Z0(t)},Ixe=(e,t)=>{if(t.pipeStrategy===`input`)return u2(e.in._def,t);if(t.pipeStrategy===`output`)return u2(e.out._def,t);let n=u2(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,u2(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Lxe(e,t){return u2(e.type._def,t)}function Rxe(e,t){let n={type:`array`,uniqueItems:!0,items:u2(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&Y0(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&Y0(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function zxe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>u2(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:u2(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>u2(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Bxe(e){return{not:Z0(e)}}function Vxe(e){return Z0(e)}const Hxe=(e,t)=>u2(e.innerType._def,t),Uxe=(e,t,n)=>{switch(t){case Z.ZodString:return n2(e,n);case Z.ZodNumber:return jxe(e,n);case Z.ZodObject:return Mxe(e,n);case Z.ZodBigInt:return pxe(e,n);case Z.ZodBoolean:return mxe();case Z.ZodDate:return $0(e,n);case Z.ZodUndefined:return Bxe(n);case Z.ZodNull:return Oxe(n);case Z.ZodArray:return fxe(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return kxe(e,n);case Z.ZodIntersection:return xxe(e,n);case Z.ZodTuple:return zxe(e,n);case Z.ZodRecord:return s2(e,n);case Z.ZodLiteral:return Sxe(e,n);case Z.ZodEnum:return yxe(e);case Z.ZodNativeEnum:return Exe(e);case Z.ZodNullable:return Axe(e,n);case Z.ZodOptional:return Fxe(e,n);case Z.ZodMap:return Txe(e,n);case Z.ZodSet:return Rxe(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return Lxe(e,n);case Z.ZodNaN:case Z.ZodNever:return Dxe(n);case Z.ZodEffects:return vxe(e,n);case Z.ZodAny:return Z0(n);case Z.ZodUnknown:return Vxe(n);case Z.ZodDefault:return _xe(e,n);case Z.ZodBranded:return Q0(e,n);case Z.ZodReadonly:return Hxe(e,n);case Z.ZodCatch:return hxe(e,n);case Z.ZodPipeline:return Ixe(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>void 0)(t)}};function u2(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==lxe)return i}if(r&&!n){let e=Wxe(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=Uxe(e,e.typeName,t),o=typeof a==`function`?u2(a(),t):a;if(o&&Gxe(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Wxe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:X0(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`),Z0(t)):t.$refStrategy===`seen`?Z0(t):void 0}},Gxe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Kxe=(e,t)=>{let n=dxe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:u2(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Z0(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=u2(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Z0(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 qxe(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function d2(e,t){return v1(e)?ot(e,{target:qxe(t?.target),io:t?.pipeStrategy??`input`}):Kxe(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function f2(e){let t=S1(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=T1(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function p2(e,t){let n=b1(e,t);if(!n.success)throw n.error;return n.data}var Jxe=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(X1,e=>{this._oncancel(e)}),this.setNotificationHandler(i0,e=>{this._onprogress(e)}),this.setRequestHandler(r0,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(u0,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new G0(G1.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(f0,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 G0(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 G0(G1.InvalidParams,`Task not found: ${r}`);if(!K0(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(K0(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[O1]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(p0,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 G0(G1.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(h0,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new G0(G1.InvalidParams,`Task not found: ${e.params.taskId}`);if(K0(n.status))throw new G0(G1.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 G0(G1.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof G0?e:new G0(G1.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),G0.fromError(G1.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),W1(e)||q1(e)?this._onresponse(e):V1(e)?this._onrequest(e,t):Gye(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=G0.fromError(G1.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?.[O1]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:G1.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=Wye(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 G0(G1.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:G1.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),W1(e)?n(e):n(new G0(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(W1(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),W1(e)?r(e):r(G0.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 G0?e:new G0(G1.InternalError,String(e))}}return}let i;try{let r=await this.request(e,c0,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new G0(G1.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},K0(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new G0(G1.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new G0(G1.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 G0?e:new G0(G1.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||{},[O1]: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 G0?e:new G0(G1.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=b1(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(G0.fromError(G1.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},d0,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},m0,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},obe,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||{},[O1]: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||{},[O1]: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||{},[O1]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=f2(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=p2(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=f2(e);this._notificationHandlers.set(n,n=>{let r=p2(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`&&V1(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new G0(G1.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 G0(G1.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new G0(G1.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 G0(G1.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=l0.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),K0(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 G0(G1.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(K0(a.status))throw new G0(G1.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=l0.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),K0(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function m2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yxe(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];m2(a)&&m2(i)?n[r]={...a,...i}:n[r]=i}return n}var h2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),g2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=h2();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),_2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=h2(),n=g2();var r=h2();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=g2();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ne(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ne(this.rhs,e,n),this}get names(){return te(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ne(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(D(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(O(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ne(this.condition,e,t),this}get names(){let e=super.names;return te(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ne(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return te(te(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ne(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},ee=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ee.kind=`catch`;var T=class extends m{render(e){return`finally`+super.render(e)}};T.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
1269
1269
  `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ee(e),t(e)}return n&&(this._currNode=r.finally=new T,this.code(n)),this._endBlockNode(ee,T)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function te(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function ne(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function D(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function O(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ie(e)}`}e.not=O;let k=M(e.operators.AND);function re(...e){return e.reduce(k)}e.and=re;let A=M(e.operators.OR);function j(...e){return e.reduce(A)}e.or=j;function M(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ie(n)} ${e} ${ie(r)}`}function ie(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),v2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=_2(),n=h2();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),y2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=_2();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),b2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=_2(),n=v2(),r=y2();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Xxe=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=b2(),n=_2(),r=y2(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),x2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),S2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),C2=a((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=x2(),n=S2(),r=b2(),i=_2(),a=v2();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
@@ -3300,6 +3300,6 @@ Incremental by default — don't re-read the whole repo.
3300
3300
  `).split(`
3301
3301
  `),n=[],r=!1,i=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){r?RegExp(`^\\s{0,3}${i[0]==="`"?"`":`~`}{${i.length},}\\s*$`).test(e)&&(r=!1,i=``):(r=!0,i=t[1]);continue}if(r)continue;let a=yNe(e);for(D9.lastIndex=0;;){let e=D9.exec(a);if(e===null)break;let t=e[2];t&&n.push(t)}}return n}var k9=class{contentDir;contentFilter;state=O9();initChain=Promise.resolve();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!nL(e))try{let{frontmatter:n,body:r}=Ye(t),i=f(n?vt(n):``),a=bNe(r),o=new Set([...i,...a]),s=new Set;for(let e of o)for(let t of Ar(e))s.add(t);this.applyDocSnapshot(e,o,s)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(nL(e))return;let t=this.state.byDoc.get(e);if(t){for(let n of t){let t=this.state.byTag.get(n);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(n))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,n){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,n)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let n=[];for(let r of t){let t=this.state.byDocLiteral.get(r);if(!t)continue;let i=tr(t,e);n.push({docName:r,matchingTags:[...i].sort((e,t)=>e.localeCompare(t))})}return n.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),n=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&n.add(e.slice(0,t));let r=t;for(;r>0;)n.add(e.slice(0,r)),r=e.indexOf(`/`,r+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!n.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){let e=this.initChain.then(()=>this.initOnce());return this.initChain=e.catch(e=>{console.warn(`[tag-index] init failed (chain cleared for next init):`,e)}),e}async initOnce(){if(this.state=O9(),!V(this.contentDir))return;let e=await this.listDocsWithPaths();for(let t=0;t<e.length;t+=50){let n=e.slice(t,t+50),r=await Promise.all(n.map(async({docName:e,filePath:t})=>{try{return{docName:e,markdown:await fs(t,`utf-8`)}}catch(t){return console.warn(`[tag-index] Failed to read ${e} during init:`,t),null}}));for(let e of r)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown)}catch(t){console.warn(`[tag-index] Failed to index ${e.docName} during init:`,t)}}}applyDocSnapshot(e,t,n){let r=this.state.byDoc.get(e)??new Set;for(let t of r){if(n.has(t))continue;let r=this.state.byTag.get(t);r&&(r.delete(e),r.size===0&&this.state.byTag.delete(t))}for(let t of n){let n=this.state.byTag.get(t);n||(n=new Set,this.state.byTag.set(t,n)),n.add(e)}n.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,n),this.state.byDocLiteral.set(e,t))}async listDocsWithPaths(){let e=[];await this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}async walkContentDir(e,t){let n;try{n=await ps(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let r of n){let n=R(e,r.name);if(r.isDirectory()){let e=yB(z(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!iL(r.name))continue;let i=yB(z(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:oL(i),filePath:n})}}};const xNe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function SNe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(f5).join(` `)} auth git-credential`]}function CNe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=vo(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],nV({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return U(`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 U(`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(`
3302
3302
  `)){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=B(e,r);if(!YV(a,t))continue;let s=kB(a,t);i.has(s)||V(a)&&i.set(s,o)}return i}function A9(e){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:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=U(`server`);function b(){let e=aP({absPath:tP(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=fe(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 x(){let e=aP({absPath:tP(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||y.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let r=aP({absPath:tP(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),r.value.autoSync?.default===!0}function S(){let e=aP({absPath:tP(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?ht(e):u}function C(){return qU(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function w(){let e=aP({absPath:tP(`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 ee(e){return`${VU(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function T(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=x(),Ge?.setEnabled(t).catch(n=>{y.warn({err:n,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let n=C();ue.applyConfig({enabled:n.enabled,providerFingerprint:ee(n)}),y.info({docName:e,autoSyncEnabled:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}zI();let E=bs(),te=gH(n);if(ji(te,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{m9({lockDir:te,shadowRepoDir:ks(n)})}catch(e){throw xi(te),e}let ne=yr(),D=(e,t)=>ne.resolveEmbed(e,t),O=(e,n)=>{let r=ne.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=B(t,r);if(!bB(i,B(t)))return null;try{let e=Yo(i);return e.isFile()?e.size:null}catch{return null}},k,re,A,j,M,ie,N,ae,oe=null,se=null,P=null,ce=null,le=C(),ue=new Jme({loadEmbedder:e.embedderLoader??(()=>{let t=C();return zme({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:R(gH(n),`embeddings`),enabled:le.enabled,providerFingerprint:ee(le)}),de=null,pe=new Set,me=!1,he,ge,_e,ve=new Promise((e,t)=>{ge=e,_e=t});function ye(e){oe?.signal(e)}let be=null;function F(){be!==null&&clearTimeout(be),be=setTimeout(()=>{be=null,re.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let xe=null,Se=!1,Ce=()=>{try{o9(n,we.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},we=new PMe(void 0,{onEviction:()=>bae(),onSizeChange:e=>xae(e),onMutate:()=>{!Se||xe!==null||(xe=setTimeout(()=>{xe=null,Ce()},2e3))}});for(let[e,r]of LMe(n))tL(e)||QQ(e)&&([`.md`,`.mdx`].some(n=>{let r=B(t,`${e}${n}`);return bB(r,B(t))&&V(r)})||we.restore(e,r));Se=!0;let Te=(e,t)=>{tL(e)||we.setRenamed(e,t)},Ee=e=>{if(!tL(e)){if(we.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}we.setDeleted(e)}},De=e=>{tL(e)||we.delete(e)};try{k=KG({projectDir:n,contentDir:t,singleDocRelPath:_,onAfterRebuild:()=>{re.rebuildFromDisk($V()).catch(e=>{U(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),A.init().catch(e=>{U(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),pfe(Ue).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?U(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):U(`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=>{U(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),re=new gX({projectDir:n,contentDir:t,contentFilter:k}),A=new k9({contentDir:t,contentFilter:k}),A.init().catch(e=>{U(`server-factory`).warn({err:e},`[server-factory] tag-index init failed; continuing with empty index`)}),j={current:f},M=o?AMe({getShadow:()=>j.current??null,getCurrentBranch:()=>We?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Os(n)??void 0,isWriterLive:e=>{if(!P&&!ae)return U(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(P?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of ae?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ie=cH({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:j,ephemeral:v,contentRoot:p,backlinkIndex:re,configHomedirOverride:l,getCurrentBranch:()=>We?.getLastKnownBranch()??null,resolveEmbed:D,resolveSize:O,getPrincipal:()=>de,onAgentCommit:()=>oe?.signal(`session-activity`),onFlushCommit:()=>M?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{oe?.emitDiskAck(e,t),!tL(e)&&ape(r,n)&&(ce?.(),ye(`files`))},onConfigRejected:(e,t)=>oe?.emitConfigValidationRejected(e,t),onConfigPersisted:T,isRecentlyRemoved:e=>we.has(e),mdManager:e.mdManager}),N=new Qje({quiet:r,debounce:i,maxDebounce:a,extensions:[ie.extension]});let u=N.shouldUnloadDocument.bind(N);N.shouldUnloadDocument=e=>{if(pe.has(e)||me&&u(e))return!0;let t=e.name;return tL(t)||eH(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:u(e)},he=async e=>{pe.add(e);try{await N.unloadDocument(e)}finally{pe.delete(e)}},oe=new rL(N),se=new uk(N),P=new Ak(N),ae=new NL(N);let m=U7({backlinkIndex:re,tagIndex:A,signalChannel:ye});N.configuration.extensions.push(m),N.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=zR(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==E)throw new RR(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${E}`);let i=n?.expectedBranch,a=$V();if(typeof i==`string`&&i.length>0&&i!==a)throw new RR(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(de&&n.principalId===de.id?o.principalId=de.id:de?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:de.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),N.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!QI(e.documentName)&&!$I(e.documentName))return;let t=e.request,n=t.socket?.remoteAddress;if(n!==void 0&&!lZ(n))throw Error(`config-doc admission requires loopback peer (peer=${n}, doc=${e.documentName})`);let r=e.requestHeaders,i=(r&&typeof r.get==`function`?r.get(`host`):null)??t.headers?.host??void 0;if(!uZ(i))throw Error(`config-doc admission requires loopback Host header (host=${i??`<absent>`}, doc=${e.documentName})`)}});let g=B(t);function y(e){if(!QQ(e))return null;let t=B(g,fL(e));return bB(t,g)?t:null}N.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await FMe(e.documentName,{recentlyRemovedDocs:we,resolveFilePath:y,fileExists:V})}}),N.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=zR(e.token);cMe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>N.documents.get(e)})}}),N.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new _7(e.update);if(t.readVarString(),t.readVarUint()===O7.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Xr} rejected — server-only channel`)}});let x=$Q({hocuspocus:N,sessionManager:ae,contentDir:t,contentFilter:k,serverInstanceId:E,getFileIndex:()=>Ue?Ue.getFileIndex():new Map,getAttachmentFolderPath:b,getAllFilesIndex:()=>Ue?Ue.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Ue?.getFileIndexGeneration()??0,mutateFileIndex:e=>Ue?.mutateFileIndex(e),getFolderIndex:()=>Ue?Ue.getFolderIndex():new Map,getAliasMap:()=>Ue?Ue.getAliasMap():new Map,getFolderAliasIndex:()=>Ue?Ue.getFolderAliasIndex():new Map,rescanFiles:()=>Ue?.rescanFromDisk(),enableTestRoutes:d,shadowRef:j,flushGitCommit:()=>ie.flushPendingGitCommit(),flushContributors:()=>ie.flushContributors(),takeStoreFailure:e=>ie.takeStoreFailure(e),takeStoreDivergence:e=>ie.takeStoreDivergence(e),markAgentWriteStore:e=>ie.markAgentWriteStore(e),getCurrentBranch:()=>We?.getLastKnownBranch()??null,getDiskAckSVs:()=>oe?.getLatestDiskAckSVsAsBase64()??{},contentRoot:p,backlinkIndex:re,tagIndex:A,signalChannel:ye,agentFocusBroadcaster:se,agentPresenceBroadcaster:P,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Ge,localOpCliArgs:h,projectDir:n,resolveEmbed:D,getPrincipal:()=>de,homeDirOverride:l,forceUnloadDocument:he,ready:ve,recentlyRemovedDocs:we,serializeDoc:Me,evictManagedArtifactLkg:e=>{ie.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ue,getSemanticSimilarityFloor:()=>C().similarityFloor,getLinterBaseConfig:()=>S(),getLinkPreviewsEnabled:w,embeddingsSecretsFile:WU(l),ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{ce=e}});N.configuration.extensions.push(x),N.configuration.extensions.push(s9({mdManager:qN,schema:JN,shadowRef:j,contentRoot:p,getCurrentBranch:()=>We?.getLastKnownBranch()??null,resolveEmbed:D,resolveSize:O})),N.configuration.extensions.push(vNe()),N.configuration.extensions.push(sMe({getSyncEngine:()=>Ge,projectDir:n,contentDir:t}))}catch(e){throw xi(te),e}let Oe=null,ke=new Map,Ae=[];function je(e,t){let n=B(e,`rescue`),r=B(n,fL(t));return bB(r,n)?r:null}function Me(e){let t=N.documents.get(e);return t?uB(t):null}let Ne=(e,t)=>cB(N,e,t,D,O);function Pe(e){if(!yL(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Fe=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of N.documents){if(tL(n))continue;let r=N.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{sB(r,i,D,n)},oB)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},Ie=null,Le=e=>{e&&(Ie===null&&(Ie=new Set,setImmediate(()=>{let e=Ie;if(Ie=null,e)try{for(let t of e)Fe(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ie.add(e))};function Re(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 xB(e)}}async function ze(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),re.updateDocumentFromMarkdown(e.docName,e.content),F(),A.updateDocumentFromMarkdown(e.docName,e.content),ye(`files`),ye(`backlinks`),ye(`graph`),ye(`tags`),De(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=N.documents.get(t);if(!r){re.updateDocumentFromMarkdown(t,n),F(),A.updateDocumentFromMarkdown(t,n),ye(`backlinks`),ye(`graph`),ye(`tags`);return}let i=eH(t)??``,a=Me(t)??i,o=Iz({docName:t,base:i,ours:a,theirs:n}),s=DB(i).slice(0,6),c=DB(a).slice(0,6),l=DB(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`:Pe(r),re.updateDocumentFromMarkdown(t,n),F(),A.updateDocumentFromMarkdown(t,n),ye(`backlinks`),ye(`graph`),ye(`tags`);break;case`clean`:try{Ne(t,o.newContent),tH(t,o.newContent),dk(),Pe(r),re.updateDocumentFromMarkdown(t,n),F(),A.updateDocumentFromMarkdown(t,n),ye(`backlinks`),ye(`graph`),ye(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),tH(t,n),Pe(r)}break;case`merged`:try{Ne(t,o.newContent),tH(t,n),dk(),Pe(r),re.updateDocumentFromMarkdown(t,n),F(),A.updateDocumentFromMarkdown(t,n),ye(`backlinks`),ye(`graph`),ye(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),tH(t,n),Pe(r)}break;case`conflicts`:try{Ne(t,o.newContent),tH(t,o.newContent),dk(),fk(),re.updateDocumentFromMarkdown(t,n),F(),A.updateDocumentFromMarkdown(t,n),ye(`backlinks`),ye(`graph`),ye(`tags`)}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),tH(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{fk();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=N.documents.get(t);if(!n){re.deleteDocument(t),F(),A.deleteDocument(t),ye(`files`),ye(`backlinks`),ye(`graph`),ye(`tags`),Ee(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=eH(t)??``,i=Me(t)??``,a=i!==r;if(a&&j.current){let e=j.current,n=We?.getLastKnownBranch()??`main`;queueMicrotask(()=>{tB(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{mk(),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`),nH(t),re.deleteDocument(t),F(),A.deleteDocument(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),N.closeConnections(t),await he(n),ye(`files`),ye(`backlinks`),ye(`graph`),ye(`tags`),Ee(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=N.documents.get(t);if(nH(t),tH(n,r),re.renameDocument(t,n,r),F(),A.renameDocument(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),ye(`files`),ye(`backlinks`),ye(`graph`),ye(`tags`),Te(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=N.documents.get(t);if(!n)return;let r=Me(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`):tH(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`:ne.add(e.relativePath),ye(`files`),Le(bo(e.relativePath));break;case`asset-delete`:ne.remove(e.relativePath),ye(`files`),Le(bo(e.relativePath));break;case`folder-create`:case`folder-delete`:ye(`files`);break;case`file-create`:case`file-update`:case`file-delete`:ye(`files`);break;default:xB(e)}}catch(t){let n=Re(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Be=[];async function Ve(e){if(oH()){Be.push(e);return}await ze(e)}async function He(){let e=Be.splice(0,Be.length);for(let t of e)await ze(t)}let Ue=null,We=null,Ge=null,Ke=null;async function qe(e){if(N.documents.size===0)return;let t=!1,n=new Promise(e=>{N.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(N.documents.keys());N.closeConnections(),N.flushPendingStores();for(let e of N.documents.values())e.getConnectionsCount()===0&&N.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(N.documents.keys()),i=[],o=[];if(j.current){for(let e of n)if(!tL(e))try{let t=Me(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=je(j.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:j.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Ro(So(n),{recursive:!0}),Qo(n,t,`utf-8`),mk(),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 Je(){return Ke||(Ke=(async()=>{let e=Date.now(),t=[];me=!0;try{Mi(te)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(be!==null&&(clearTimeout(be),be=null),xe!==null&&(clearTimeout(xe),xe=null),Se)try{o9(n,we.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=N.documents.size;M?.destroy();try{try{try{We&&=(await We.unsubscribe(),null),Ue&&=(await Ue.unsubscribe(),null);for(let{docName:e,cleanup:t}of Ae)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Ae.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{oe?.destroy(),P?.destroy(),Oe&&=(await Oe.disconnect(),null);for(let[e,t]of ke)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}ke.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 ae.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 qe(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ie.flushPendingGitCommit(),await ie.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Ge&&=(await Ge.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(j.current){try{let e=(await mi({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Qo(B(j.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Kde(j.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{xi(te,{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 HI()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Ke)}let Ye=[];async function Xe(){try{de=await n9(n),y.info({principalId:de.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!j.current)try{j.current=await Wz(n),y.info({gitDir:j.current.gitDir},`[server] history repo initialized at ${j.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),Ye.push(`shadow-repo`)}if(j.current){let e=null;try{e=fV(j.current.gitDir),Nfe(j.current.gitDir,e),Ofe(j.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([DV(j.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 M?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(j.current)try{await Hz(j.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{j.current=await Wz(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),j.current=void 0,Ye.includes(`shadow-repo`)||Ye.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(j.current)try{let e=B(j.current.gitDir,`last-known-head`),t=null;try{t=H(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await mi({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await mi({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 Qz(j.current,p??``,t,r,e),pk()}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{Qo(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=A_e(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`),Ye.push(`managed-rename-recovery`)}try{let e=Zhe(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`),Ye.push(`upload-tempfile-sweep`)}try{Oe=await N.openDirectConnection(Xr),oe?.emitServerInfo(E,$V())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Ye.push(`cc1-push`)}let r=v?[]:wn;for(let e of r)try{let t=await N.openDirectConnection(e);ke.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Ye.push(`config-doc:${e}`)}let i=new Map([[Xn,tP(`project`,n)],[Nn,tP(`project-local`,n)],[kn,tP(`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 iMe(t,t=>{let n=N.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=Ez(n??null,e,t,ie.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),T(e)});Ae.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}`),Ye.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=gfe(e,ie.managedArtifactCtx);if(!n)return;let r=yfe(N.documents.get(n)??null,n,t,ie.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),qr(n)&&re.ingestGlobalSkillBundles(YB(ie.managedArtifactCtx),$V()).then(()=>{ye(`backlinks`),ye(`graph`)}).catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=YB(ie.managedArtifactCtx),n=await t9(t,e);Ae.push({docName:`__skill-files__`,cleanup:n}),y.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),Ye.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of XH(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?B(n,e,`.ok`,`templates`):B(n,`.ok`,`templates`)),i=await t9(r,e,MMe);Ae.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`),Ye.push(`managed-artifact-watcher:templates`)}}try{let e=B(t,`.okignore`),r=B(n,`.gitignore`),i=null;try{let e=vo(`git`,[`rev-parse`,`--git-common-dir`],nV({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=R(B(n,e.stdout.trim()),`info`,`exclude`);V(So(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 aMe(a,(t,r)=>{(async()=>{if(t===e)try{let e=Ez(N.documents.get(`__config__/okignore`)??null,dr,r,ie.configPersistenceCtx);o.info({docName:dr,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:z(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await k.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:z(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),oe?.signal(`files`);else{let e=z(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),oe?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:z(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Ae.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`),Ye.push(`ignore-files-watcher`)}let a=Os(n),o=a?H7(a)??`main`:`main`;QV(o),re.switchBranch(o);let s=performance.now();try{await GI(`ok.boot.indexes`,void 0,async()=>{let e=$V();try{if(await re.loadFromDisk(e)){let t=await re.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&y.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let n=0;for(let e of t.deletedDocNames)tL(e)||we.peek(e)?.kind!==`renamed`&&(we.setDeleted(e),n++);n>0&&y.info({count:n},`[removal-guard] tombstoned docs deleted while the server was down`)}else await re.rebuildFromDisk(e);try{await re.ingestGlobalSkillBundles(YB(ie.managedArtifactCtx),e)}catch(t){y.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}re.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){y.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let n=performance.now();Ue=await GI(`ok.boot.seed-walk`,void 0,async()=>WB(t,Ve,k)),bX(`seedWalkMs`,Math.round(performance.now()-n));{let e=B(t),n=0;for(let[t]of we.entries()){if(!QQ(t))continue;let r=B(e,`${t}${dL(t)}`);bB(r,e)&&V(r)&&(we.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{await A.init()}catch(e){y.error({err:e},`[tag-index] startup re-init failed; tag index updates incrementally via watcher events`),Ye.push(`tag-index`)}let r=0;try{_===void 0?await t$({contentDir:t,contentFilter:k,basenameIndex:ne,onSkip:(e,t,n)=>{r++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):cye({contentDir:t,basenameIndex:ne,onSkip:(e,t,n)=>{r++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),r>0&&(y.warn({count:r},`[basename-index] startup seed completed with ${r} skipped entries — embeds under inaccessible subtrees will not resolve`),Ye.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),Ye.push(`basename-index`)}})}catch(e){y.error({err:e},`[server] disk bridge watcher failed to start`),Ye.push(`file-watcher`)}finally{bX(`indexesMs`,Math.round(performance.now()-s)),Ue&&sge(`fileCount`,Ue.getFileIndex().size)}try{We=await pMe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),zie(),N.flushPendingStores(),await ie.flushPendingGitCommit(),aH(!0),j.current){let e=$V(),t=Os(n),r=t?H7(t)??e:e,i=[];for(let[e,t]of N.documents){if(tL(e))continue;let n=null;if(t.transact(()=>{n=Me(e)},xNe),n===null)continue;let r=eH(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await Qde(j.current,e,Xz.id,i,r);t&&(Hie(),y.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=Be.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(aH(!1),await He(),e.headMoved&&e.newHead){let r=CNe(n,B(t),e.oldHead,e.newHead);if(r.size>0){kde(r.keys());for(let[e,t]of r)Oz(e,Xte(t.email),t.name,t.email,Us(e));await ie.flushContributors()}}if(await ie.flushDeferredStores(`within-branch`),Ge!==null)try{await Ge.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Vie(),Be.splice(0,Be.length),QV(i),be!==null&&(clearTimeout(be),be=null),re.switchBranch(i),k.rebuildDirCount();try{let e=0;ne.clear(),await t$({contentDir:t,contentFilter:k,basenameIndex:ne,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`),Ye.includes(`basename-index-partial`)||Ye.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of N.documents)if(!tL(e))try{let r=JV(e,t);if(!V(r)){let t=eH(e)??``,r=Me(e)??``;if(r!==t&&j.current){let t=j.current;queueMicrotask(()=>{tB(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{mk(),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`);Ne(e,a),tH(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:N.documents.size},`[branch-switch] loaded branch ${i} (${N.documents.size} docs)`);try{if(await re.loadFromDisk(i)){let e=await re.reconcileWithDisk(i);(e.added>0||e.updated>0||e.deleted>0)&&y.info(e,`[backlinks] branch-switch reconcile for ${i}`)}else await re.rebuildFromDisk(i);try{await re.ingestGlobalSkillBundles(YB(ie.managedArtifactCtx),i)}catch(e){y.warn({err:e,branch:i},`[backlinks] branch-switch global skill bundle ingest failed`)}re.saveToDisk(i).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${i}:`,e)})}catch(e){y.error({err:e,branch:i},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(await A.init(),j.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of N.documents)if(!tL(t))try{let n=await efe(j.current,i,Xz.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=eH(t);if(!r)continue;let a=Iz({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:Ne(t,a.newContent),tH(t,a.newContent),e++;break;case`conflicts`:Ne(t,a.newContent),tH(t,a.newContent),fk(),e++;{let e=N.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-`)&&j.current)try{let t=Hz(j.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
3303
- `))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`)}aH(!1),await ie.flushDeferredStores(`discard-stale`),oe?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&j.current&&r>0){let t=p??`.`;try{let n=await Qz(j.current,t,e.oldHead,e.newHead,i);pk(),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`),Ye.push(`head-watcher`)}function c(e){for(let r of e)try{let e=yB(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=oL(e),a=N.documents.get(i);if(!a)continue;let o=Me(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):tH(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}let u=SNe(h);try{Ge=new gNe({projectDir:n,contentDir:t,contentFilter:k,contentRoot:p,syncEnabled:x(),credentialArgs:u,cc1Broadcaster:oe,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{aH(e),e||ie.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:c,onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await rP({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ct(t.error),configPath:tP(`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 Ge.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Ge=null}ye(`files`),ye(`backlinks`),ye(`graph`),ye(`tags`);let d=yX();d!==void 0&&bX(`readyMs`,d)}return Xe().then(ge,_e),{hocuspocus:N,sessionManager:ae,cc1Broadcaster:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:P,maintenanceCoordinator:M,contentFilter:k,basenameIndex:ne,serverInstanceId:E,destroy:Je,ready:ve,degraded:Ye,lockDir:te,get syncEngine(){return Ge}}}function j9(e){return e/1048576}function wNe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:j9(e.rss),heapTotalMb:j9(e.heapTotal),heapUsedMb:j9(e.heapUsed),externalMb:j9(e.external),arrayBuffersMb:j9(e.arrayBuffers)}}}let M9=null;yle(()=>{M9=null});function TNe(){if(M9)return;let e=WI().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=wNe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),M9=e}let N9=null,P9=!1;function F9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function I9(e){if(!F9())return;let t=gH(e);N9=new GO({currentPath:B(t,`tolerance-telemetry.jsonl`),previousPath:B(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),de(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};N9?.append(`${JSON.stringify(t)}\n`).catch(e=>{P9||(P9=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function L9(){de(null),await N9?.drain(),N9=null,P9=!1}L();const ENe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],DNe=[`cache`,`tmp`];function ONe(e){let t=B(e,He);if(!(()=>{if(!V(t))return!0;try{return Uo(t).length===0}catch{return!0}})())return[];let n=[];for(let t of ENe)V(B(e,t))&&n.push(t);for(let t of DNe){let r=B(e,t);try{V(r)&&Yo(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function kNe(e){let t=Ds(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 R9=5e3;async function ANe(e){oge();let t=e.projectDir??e.contentDir,n=uye({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}`)}lk.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}zI({localSink:n?.telemetry}),I9(t),TNe();let{kind:r,gitdir:i}=kNe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ez(i));let o=process.env.OK_STARTUP_TRACEPARENT,s=()=>GI(`ok.boot`,{attributes:a},async()=>jNe(e));if(o)try{let e=li.extract(fi.active(),{traceparent:o});return fi.with(e,s)}catch(e){U(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return s()}async function jNe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??U(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=e.lockKind??a??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-KfTPtASZ.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=B(p,`.ok`);if(!V(B(m,`config.yml`)))throw new B5(V(m)?`config`:`okdir`,p);V(B(m,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let h=e.gitPreflight??tY;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof QJ||e instanceof $J){let t=e instanceof $J?e.detected:``,n=e instanceof $J?`too_old`:`not_available`;oZ(e),i.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await HI(),await Promise.race([L9(),new Promise(e=>setTimeout(e,R9))]),e}let g=ONe(m);g.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${He}/.`);let _=A9({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:o,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:v,destroy:y,ready:b,degraded:x,lockDir:S,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:ee,maintenanceCoordinator:T}=_,E=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),te=e.port??0,ne=e.ephemeral?void 0:P5({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${E}:${te}`,log:i}),D=c();D.headersTimeout=3e4,D.requestTimeout=6e4;let O=e.serveContentAssets===!1?void 0:mH({contentFilter:_.contentFilter,contentSirv:Fi(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:bn,assetExtensions:Wt,blocklistExtensions:s}),k=!1;if(e.reactShellDistDir)try{zY(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),k=!0}catch(e){if(e instanceof RY)i.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:S},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await y().catch(()=>{}),u(S),e}let re=e.reactShellDistDir?Fi(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,A=I5({httpServer:D,hocuspocus:v,mcpHttpHandler:ne,log:i,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:ee,maintenanceCoordinator:T,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:O,reactShellMiddleware:re,ephemeral:e.ephemeral}),j=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},M=null;r!==null&&(M=a$({httpServer:D,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await j()})})),await z9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);D.once(`error`,r),D.listen(e.port,e.host,()=>{D.removeListener(`error`,r),t()})})}catch(e){if(k)try{HY(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),u(S),e}let ie=yX();ie!==void 0&&bX(`httpListenMs`,ie);let N=D.address(),ae=typeof N==`object`&&N?N.port:e.port??0;if(te=ae,d(S,ae),k&&BY(S,ae),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let oe=!1,se=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${R9}ms`))},R9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};j=async()=>{if(oe)return;oe=!0;let e=[],t=async(t,n)=>{try{await se(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(S),k&&qhe(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{M?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>A.shutdown()),ne!==void 0&&await t(`mcpHttpHandler.close`,()=>ne.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{A.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{D.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{D.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),k&&await t(`releaseUiLock`,async()=>HY(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>HI()),await t(`teardownToleranceTelemetry`,()=>L9()),await t(`flushLogFileSinks`,()=>lk.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await PY({projectDir:p,skillsRoot:B(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&i.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){i.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:D,destroy:j,lockDir:S,contentDir:e.contentDir,port:ae,ready:b,degraded:x,didAutoInit:f,serverInstance:_}}async function z9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new i$(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=null;try{let e=Os(n),t=e?R(e,`MERGE_HEAD`):null;if(!t||!V(t)){i.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:a.length}));return}let r=gi({baseDir:n,timeout:{block:5e3}});o=new Set(await zz(r,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(o!==null){let e=0;for(let t of a)o.has(t.file)||(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o?.has(e.file)),a.length===0)return}for(let e of a){let n=oL(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 MNe=Ce;function NNe(e={}){let t=e.home??$o(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(R(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(R(r.APPDATA??R(t,`AppData`,`Roaming`),`Claude`)):!1}const B9=R($o(),`.ok`,`logs`),PNe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function FNe(){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 INe(e){Ro(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function LNe(e){try{if(Yo(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{Ko(n,r)}catch{}}try{Zo(`${e}.3`)}catch{}}function RNe(e){try{let t=Date.now(),n=10080*60*1e3,r=Uo(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Yo(R(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{Zo(R(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{Zo(R(e,t.name)),a-=t.size}catch{}}}catch{}}function zNe(e){INe(B9);let t=V9(),n=e.filePath??R(B9,`${e.name}.${t}.log`);LNe(n),(e._setTimeout??setTimeout)(()=>RNe(B9),5e3).unref();let r=VO.default.destination({dest:n,append:!0,sync:!0});return(0,VO.default)({level:FNe(),name:e.name,redact:{paths:PNe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:VO.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function BNe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[VO.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 VNe(e){return R(B9,`${e}.${V9()}.log`)}function HNe(){return B9}function UNe(e){let t=B(e),n=0;for(;n<30;){let e=!1;try{e=V(B(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=So(t);if(r===t)return null;t=r,n+=1}return null}const H9=ws(go),U9=U(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function WNe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],nV({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function GNe(e){let t=B(e),n=B(t,`.git`),r=B(n,`HEAD`),i=!1;if(V(n)){if(!Yo(n).isDirectory()||V(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=tY()}catch(e){throw e instanceof QJ||e instanceof $J?(oZ(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof $J?`too_old`:`not_available`,detectedVersion:e instanceof $J?e.detected:``},e instanceof $J?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await WNe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],nV({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=U(`project-skill-git`),K9=/^[0-9a-f]{40}$/,KNe=cr.map(e=>e.replace(/\/$/,``));async function qNe(e){let t=Os(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(ZNe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=_i(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await hi(async()=>{let t=await JNe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await YNe(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=_i(e,{gitIndexFile:R(ns(),`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 XNe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await OX(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;yi(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 \`${Er}\` 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 KNe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function JNe(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 YNe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function XNe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function ZNe(e){return V(R(e,`MERGE_HEAD`))||V(R(e,`rebase-merge`))||V(R(e,`rebase-apply`))||V(R(e,`CHERRY_PICK_HEAD`))||V(R(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function QNe(e,t){let n;try{n=ho(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=So(n),r=0;r<32;r+=1){let n=R(t,`package.json`);if(V(n))try{let t=JSON.parse(await fs(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=So(t);if(r===t)return;t=r}}const $Ne=[{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 $Ne)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 ePe(e){if(!iL(e))throw new $9(e);let t;try{t=Go(B(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Yo(t).isFile())throw new Q9(e);let n=So(t),r=CX(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:oL(z(tPe(e),t).split(Do).join(`/`)),canonicalFilePath:t}}let i=bo(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:oL(i)}}function tPe(e){return B(e,aP({absPath:tP(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function nPe(e){let t=zo(B(ns(),`ok-ephemeral-`)),n=B(t,`.ok`);return Ro(n,{recursive:!0}),Qo(B(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Qo(B(n,`.gitignore`),`local/
3303
+ `))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`)}aH(!1),await ie.flushDeferredStores(`discard-stale`),oe?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&j.current&&r>0){let t=p??`.`;try{let n=await Qz(j.current,t,e.oldHead,e.newHead,i);pk(),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`),Ye.push(`head-watcher`)}function c(e){for(let r of e)try{let e=yB(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=oL(e),a=N.documents.get(i);if(!a)continue;let o=Me(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):tH(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}let u=SNe(h);try{Ge=new gNe({projectDir:n,contentDir:t,contentFilter:k,contentRoot:p,syncEnabled:x(),credentialArgs:u,cc1Broadcaster:oe,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{aH(e),e||ie.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:c,onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await rP({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ct(t.error),configPath:tP(`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 Ge.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Ge=null}ye(`files`),ye(`backlinks`),ye(`graph`),ye(`tags`);let d=yX();d!==void 0&&bX(`readyMs`,d)}return Xe().then(ge,_e),{hocuspocus:N,sessionManager:ae,cc1Broadcaster:oe,agentFocusBroadcaster:se,agentPresenceBroadcaster:P,maintenanceCoordinator:M,contentFilter:k,basenameIndex:ne,serverInstanceId:E,destroy:Je,ready:ve,degraded:Ye,lockDir:te,get syncEngine(){return Ge}}}function j9(e){return e/1048576}function wNe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:j9(e.rss),heapTotalMb:j9(e.heapTotal),heapUsedMb:j9(e.heapUsed),externalMb:j9(e.external),arrayBuffersMb:j9(e.arrayBuffers)}}}let M9=null;yle(()=>{M9=null});function TNe(){if(M9)return;let e=WI().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=wNe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),M9=e}let N9=null,P9=!1;function F9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function I9(e){if(!F9())return;let t=gH(e);N9=new GO({currentPath:B(t,`tolerance-telemetry.jsonl`),previousPath:B(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),de(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};N9?.append(`${JSON.stringify(t)}\n`).catch(e=>{P9||(P9=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function L9(){de(null),await N9?.drain(),N9=null,P9=!1}L();const ENe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],DNe=[`cache`,`tmp`];function ONe(e){let t=B(e,He);if(!(()=>{if(!V(t))return!0;try{return Uo(t).length===0}catch{return!0}})())return[];let n=[];for(let t of ENe)V(B(e,t))&&n.push(t);for(let t of DNe){let r=B(e,t);try{V(r)&&Yo(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function kNe(e){let t=Ds(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 R9=5e3;async function ANe(e){oge();let t=e.projectDir??e.contentDir,n=uye({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}`)}lk.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}zI({localSink:n?.telemetry}),I9(t),TNe();let{kind:r,gitdir:i}=kNe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ez(i));let o=process.env.OK_STARTUP_TRACEPARENT,s=()=>GI(`ok.boot`,{attributes:a},async()=>jNe(e));if(o)try{let e=li.extract(fi.active(),{traceparent:o});return fi.with(e,s)}catch(e){U(`boot`).warn({err:e instanceof Error?e.message:String(e)},`ok.boot trace-join failed — starting unparented boot`)}return s()}async function jNe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??U(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=e.lockKind??a??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-478F0EVr.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=B(p,`.ok`);if(!V(B(m,`config.yml`)))throw new B5(V(m)?`config`:`okdir`,p);V(B(m,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let h=e.gitPreflight??tY;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof QJ||e instanceof $J){let t=e instanceof $J?e.detected:``,n=e instanceof $J?`too_old`:`not_available`;oZ(e),i.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await HI(),await Promise.race([L9(),new Promise(e=>setTimeout(e,R9))]),e}let g=ONe(m);g.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${He}/.`);let _=A9({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:o,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:v,destroy:y,ready:b,degraded:x,lockDir:S,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:ee,maintenanceCoordinator:T}=_,E=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),te=e.port??0,ne=e.ephemeral?void 0:P5({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${E}:${te}`,log:i}),D=c();D.headersTimeout=3e4,D.requestTimeout=6e4;let O=e.serveContentAssets===!1?void 0:mH({contentFilter:_.contentFilter,contentSirv:Fi(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:bn,assetExtensions:Wt,blocklistExtensions:s}),k=!1;if(e.reactShellDistDir)try{zY(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),k=!0}catch(e){if(e instanceof RY)i.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:S},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await y().catch(()=>{}),u(S),e}let re=e.reactShellDistDir?Fi(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,A=I5({httpServer:D,hocuspocus:v,mcpHttpHandler:ne,log:i,sessionManager:C,agentFocusBroadcaster:w,agentPresenceBroadcaster:ee,maintenanceCoordinator:T,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:O,reactShellMiddleware:re,ephemeral:e.ephemeral}),j=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},M=null;r!==null&&(M=a$({httpServer:D,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await j()})})),await z9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);D.once(`error`,r),D.listen(e.port,e.host,()=>{D.removeListener(`error`,r),t()})})}catch(e){if(k)try{HY(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),u(S),e}let ie=yX();ie!==void 0&&bX(`httpListenMs`,ie);let N=D.address(),ae=typeof N==`object`&&N?N.port:e.port??0;if(te=ae,d(S,ae),k&&BY(S,ae),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let oe=!1,se=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${R9}ms`))},R9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};j=async()=>{if(oe)return;oe=!0;let e=[],t=async(t,n)=>{try{await se(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(S),k&&qhe(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{M?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>A.shutdown()),ne!==void 0&&await t(`mcpHttpHandler.close`,()=>ne.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{A.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{D.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{D.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),k&&await t(`releaseUiLock`,async()=>HY(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>HI()),await t(`teardownToleranceTelemetry`,()=>L9()),await t(`flushLogFileSinks`,()=>lk.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await PY({projectDir:p,skillsRoot:B(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&i.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){i.warn?.({event:`installed-skills-reconcile-failed`,error:String(e)},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:D,destroy:j,lockDir:S,contentDir:e.contentDir,port:ae,ready:b,degraded:x,didAutoInit:f,serverInstance:_}}async function z9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new i$(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=null;try{let e=Os(n),t=e?R(e,`MERGE_HEAD`):null;if(!t||!V(t)){i.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:a.length}));return}let r=gi({baseDir:n,timeout:{block:5e3}});o=new Set(await zz(r,[`diff`,`--name-only`,`--diff-filter=U`]))}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(o!==null){let e=0;for(let t of a)o.has(t.file)||(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o?.has(e.file)),a.length===0)return}for(let e of a){let n=oL(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 MNe=Ce;function NNe(e={}){let t=e.home??$o(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(R(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(R(r.APPDATA??R(t,`AppData`,`Roaming`),`Claude`)):!1}const B9=R($o(),`.ok`,`logs`),PNe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function FNe(){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 INe(e){Ro(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function LNe(e){try{if(Yo(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{Ko(n,r)}catch{}}try{Zo(`${e}.3`)}catch{}}function RNe(e){try{let t=Date.now(),n=10080*60*1e3,r=Uo(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Yo(R(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{Zo(R(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{Zo(R(e,t.name)),a-=t.size}catch{}}}catch{}}function zNe(e){INe(B9);let t=V9(),n=e.filePath??R(B9,`${e.name}.${t}.log`);LNe(n),(e._setTimeout??setTimeout)(()=>RNe(B9),5e3).unref();let r=VO.default.destination({dest:n,append:!0,sync:!0});return(0,VO.default)({level:FNe(),name:e.name,redact:{paths:PNe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:VO.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function BNe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[VO.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 VNe(e){return R(B9,`${e}.${V9()}.log`)}function HNe(){return B9}function UNe(e){let t=B(e),n=0;for(;n<30;){let e=!1;try{e=V(B(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=So(t);if(r===t)return null;t=r,n+=1}return null}const H9=ws(go),U9=U(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function WNe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],nV({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function GNe(e){let t=B(e),n=B(t,`.git`),r=B(n,`HEAD`),i=!1;if(V(n)){if(!Yo(n).isDirectory()||V(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=tY()}catch(e){throw e instanceof QJ||e instanceof $J?(oZ(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof $J?`too_old`:`not_available`,detectedVersion:e instanceof $J?e.detected:``},e instanceof $J?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,message:e instanceof Error?e.message:String(e)},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await WNe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],nV({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=U(`project-skill-git`),K9=/^[0-9a-f]{40}$/,KNe=cr.map(e=>e.replace(/\/$/,``));async function qNe(e){let t=Os(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(ZNe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=_i(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await hi(async()=>{let t=await JNe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await YNe(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=_i(e,{gitIndexFile:R(ns(),`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 XNe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await OX(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;yi(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 \`${Er}\` 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 KNe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function JNe(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 YNe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function XNe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function ZNe(e){return V(R(e,`MERGE_HEAD`))||V(R(e,`rebase-merge`))||V(R(e,`rebase-apply`))||V(R(e,`CHERRY_PICK_HEAD`))||V(R(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function QNe(e,t){let n;try{n=ho(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=So(n),r=0;r<32;r+=1){let n=R(t,`package.json`);if(V(n))try{let t=JSON.parse(await fs(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=So(t);if(r===t)return;t=r}}const $Ne=[{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 $Ne)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 ePe(e){if(!iL(e))throw new $9(e);let t;try{t=Go(B(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Yo(t).isFile())throw new Q9(e);let n=So(t),r=CX(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:oL(z(tPe(e),t).split(Do).join(`/`)),canonicalFilePath:t}}let i=bo(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:oL(i)}}function tPe(e){return B(e,aP({absPath:tP(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function nPe(e){let t=zo(B(ns(),`ok-ephemeral-`)),n=B(t,`.ok`);return Ro(n,{recursive:!0}),Qo(B(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Qo(B(n,`.gitignore`),`local/
3304
3304
  `,`utf-8`),t}export{j4 as $,tL as $i,DK as $n,Qz as $r,IX as $t,p9 as A,Xs as Aa,fz as Ai,TJ as An,IV as Ar,DZ as At,z5 as B,NR as Bi,Qq as Bn,TB as Br,lZ as Bt,A9 as C,Lie as Ca,pz as Ci,WJ as Cn,gH as Cr,LZ as Ct,m9 as D,qO as Da,uz as Di,AJ as Dn,cH as Dr,L_e as Dt,d9 as E,nk as Ea,az as Ei,OJ as En,mH as Er,z_e as Et,Z7 as F,Fs as Fa,PR as Fi,gJ as Fn,DB as Fr,jZ as Ft,j5 as G,jL as Gi,UK as Gn,oB as Gr,h_e as Gt,I5 as H,ML as Hi,iJ as Hn,WB as Hr,__e as Ht,X7 as I,Ds as Ia,LR as Ii,cJ as In,EB as Ir,OZ as It,R4 as J,_L as Ji,FK as Jn,rB as Jr,kX as Jt,y5 as K,vL as Ki,WK as Kn,cB as Kr,m_e as Kt,mMe as L,ks as La,IR as Li,hJ as Ln,RB as Lr,yZ as Lt,n9 as M,Zs as Ma,sz as Mi,DJ as Mn,nV as Mr,NZ as Mt,Y7 as N,Ms as Na,FR as Ni,_J as Nn,xB as Nr,AZ as Nt,l9 as O,JO as Oa,hz as Oi,jJ as On,JV as Or,MZ as Ot,EMe as P,js as Pa,RR as Pi,vJ as Pn,LB as Pr,kZ as Pt,M4 as Q,$I as Qi,MK as Qn,Kz as Qr,Tge as Qt,U7 as R,sde as Ri,tJ as Rn,PB as Rr,bZ as Rt,L9 as S,U as Sa,cz as Si,JJ as Sn,Mme as Sr,K_e as St,c9 as T,tk as Ta,lz as Ti,MJ as Tn,_H as Tr,SZ as Tt,L5 as U,NL as Ui,kq as Un,FB as Ur,aZ as Ut,B5 as V,Ele as Vi,rJ as Vn,IB as Vr,cZ as Vt,P5 as W,Mle as Wi,iq as Wn,CB as Wr,oZ as Wt,W4 as X,QI as Xi,LK as Xn,Yz as Xr,FX as Xt,z4 as Y,rL as Yi,PK as Yn,Jz as Yr,PX as Yt,HCe as Z,nL as Zi,IK as Zn,Xz as Zr,jX as Zt,MNe as _,vk as _a,Oz as _i,oY as _n,KU as _r,gQ as _t,ePe as a,HI as aa,eB as ai,fX as an,nG as ar,v4 as at,I9 as b,ck as ba,tz as bi,qJ as bn,Vme as br,$Q as bt,qNe as c,aP as ca,Hz as ci,VY as cn,lW as cr,J1 as ct,UNe as d,ace as da,Iz as di,QJ as dn,fW as dr,V1 as dt,ZI as ea,Gz as ei,bge as en,jK as er,E4 as et,zNe as f,nce as fa,Fz as fi,$J as fn,sW as fr,W1 as ft,NNe as g,Tk as ga,jz as gi,eY as gn,GU as gr,_Q as gt,HNe as h,Dk as ha,Ade as hi,lY as hn,qU as hr,t$ as ht,nPe as i,qI as ia,nB as ii,gX as in,QG as ir,b4 as it,s9 as j,Qs as ja,iz as ji,kJ as jn,GV as jr,R_e as jt,f9 as k,pne as ka,gz as ki,EJ as kn,FV as kr,EZ as kt,W9 as l,tP as la,Nz as li,HY as ln,pW as lr,E1 as lt,VNe as m,kk as ma,Mz as mi,tY as mn,tW as mr,n$ as mt,Z9 as n,UI as na,iB as ni,CX as nn,EK as nr,jCe as nt,X9 as o,GI as oa,tB as oi,RY as on,tG as or,y4 as ot,BNe as p,Ak as pa,Mde as pi,XJ as pn,QU as pr,a$ as pt,L4 as q,G as qi,HK as qn,rfe as qr,nZ as qt,$9 as r,zI as ra,Wz as ri,SX as rn,KG as rr,MCe as rt,QNe as s,KI as sa,aB as si,zY as sn,uW as sr,B2 as st,Q9 as t,WI as ta,qz as ti,Cge as tn,TK as tr,ACe as tt,GNe as u,rP as ua,Pz as ui,BY as un,dW as ur,ebe as ut,ANe as v,Oae as va,Az as vi,rY as vn,Bme as vr,Kve as vt,k9 as w,lk as wa,oz as wi,HJ as wn,hH as wr,FZ as wt,F9 as x,Iie as xa,ez as xi,KJ as xn,jme as xr,xQ as xt,z9 as y,uk as ya,kz as yi,YJ as yn,Hme as yr,qve as yt,H7 as z,zR as zi,nJ as zn,kB as zr,uZ as zt};
3305
- //# sourceMappingURL=src-BI8S8yWC.mjs.map
3305
+ //# sourceMappingURL=src-BaGHU9u4.mjs.map