@inkeep/open-knowledge 0.38.0 → 0.38.1

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 (106) hide show
  1. package/dist/{acp-harness-probe-DVr67aDl.mjs → acp-harness-probe-BiIP2ma7.mjs} +2 -2
  2. package/dist/assets/skills/discovery/SKILL.md +1 -1
  3. package/dist/assets/skills/project/SKILL.md +1 -1
  4. package/dist/assets/skills/write-skill/SKILL.md +1 -1
  5. package/dist/cli.mjs +7 -7
  6. package/dist/constants-C66Cr63I.mjs +2 -0
  7. package/dist/git-handle-DluCIpMR.mjs +1 -0
  8. package/dist/{git-handle-Kmafc544.mjs → git-handle-DnLoe9hy.mjs} +2 -2
  9. package/dist/index.d.mts +17 -17
  10. package/dist/index.mjs +1 -1
  11. package/dist/init-Bos4UGuO.mjs +1 -0
  12. package/dist/{init-CPMjxAVJ.mjs → init-CZem0BSM.mjs} +3 -3
  13. package/dist/{launch-json-removal--7ytoIfk.mjs → launch-json-removal-DhJlKIWu.mjs} +2 -2
  14. package/dist/loader-BZ4AallX.mjs +1 -0
  15. package/dist/{loader-CF5zifwE.mjs → loader-Bi9_RmKT.mjs} +2 -2
  16. package/dist/md-manager-DtA0LK6p.mjs +2 -0
  17. package/dist/{open-browser-DwZulh9C.mjs → open-browser-Bbzq7Z7d.mjs} +2 -2
  18. package/dist/parse-worker.mjs +1 -1
  19. package/dist/preview-DJVI5fyI.mjs +1 -0
  20. package/dist/{preview-CEz-vYuH.mjs → preview-ofV-XWka.mjs} +2 -2
  21. package/dist/public/assets/{ActivityModeContent-U6pBXIBQ.js → ActivityModeContent-CQTRie_S.js} +1 -1
  22. package/dist/public/assets/{AgentDiffPane-DNb7BQuZ.js → AgentDiffPane-ZsuLVO9W.js} +1 -1
  23. package/dist/public/assets/{AgentThreadClientBinder-BwmyMJCE.js → AgentThreadClientBinder-poPjsQXP.js} +1 -1
  24. package/dist/public/assets/{CodeMirrorPropInput-CIGTqTT1.js → CodeMirrorPropInput-DUwQlljh.js} +1 -1
  25. package/dist/public/assets/{DocumentContext-BjkX60te.js → DocumentContext-CPZffvoA.js} +1 -1
  26. package/dist/public/assets/{EnableSyncConfirmDialog-211MVqW1.js → EnableSyncConfirmDialog-BfZ_iVD2.js} +1 -1
  27. package/dist/public/assets/{FeedbackForm-CVHlnDrU.js → FeedbackForm-BUn96JmL.js} +1 -1
  28. package/dist/public/assets/{GraphPanel-Cdu7mW48.js → GraphPanel-BjCltqW1.js} +1 -1
  29. package/dist/public/assets/{ManagedArtifactProperties-DewIpjBm.js → ManagedArtifactProperties-CHmkRShb.js} +1 -1
  30. package/dist/public/assets/{McpConsentDialogBody-Ds1pkJ9h.js → McpConsentDialogBody-B0VkhB1e.js} +1 -1
  31. package/dist/public/assets/{MermaidDocEditor-RY-6y6bj.js → MermaidDocEditor-cedDjA-A.js} +1 -1
  32. package/dist/public/assets/{PropertyPanel-DQ9GHyDu.js → PropertyPanel-CpcpWkfS.js} +1 -1
  33. package/dist/public/assets/{ReportBugDialogBody-SgvzkcQL.js → ReportBugDialogBody-hPmCfQyc.js} +1 -1
  34. package/dist/public/assets/{SettingsDialogBody-CNW4J8BO.js → SettingsDialogBody-B6_psJil.js} +1 -1
  35. package/dist/public/assets/{ShareBranchSwitchDialog-CNMlHlvg.js → ShareBranchSwitchDialog-GXTPAgND.js} +1 -1
  36. package/dist/public/assets/{ShareReceiveDialog-m9Ncf1Rl.js → ShareReceiveDialog-IVAS4xf8.js} +1 -1
  37. package/dist/public/assets/{ShareReceiveMissDialog-Dt5rngAU.js → ShareReceiveMissDialog-ClkBICGx.js} +1 -1
  38. package/dist/public/assets/{SkillEditorActions-7t_8lXO9.js → SkillEditorActions-BEtnBlep.js} +1 -1
  39. package/dist/public/assets/{SourceEditor-CZsCwI8R.js → SourceEditor-Bp45kdTW.js} +1 -1
  40. package/dist/public/assets/{TerminalPanel-CMCcE_sg.js → TerminalPanel-CUoZt7C0.js} +1 -1
  41. package/dist/public/assets/{TerminalSessionsHost-D-He0AKd.js → TerminalSessionsHost-CNebjNFj.js} +2 -2
  42. package/dist/public/assets/{TerminalWindowApp--K-HXyFC.js → TerminalWindowApp-B6bT25Jw.js} +1 -1
  43. package/dist/public/assets/{ThreadView-DXQ4PyDl.js → ThreadView-CmIHLGuV.js} +1 -1
  44. package/dist/public/assets/{TimelineDiffPane-DnTda2pq.js → TimelineDiffPane-DffKOwf1.js} +1 -1
  45. package/dist/public/assets/{agent-diff-store-D_W1QQps.js → agent-diff-store-D6N0WX_4.js} +1 -1
  46. package/dist/public/assets/{agent-visibility-BwHf-SiF.js → agent-visibility-Z2AQQ5Ce.js} +1 -1
  47. package/dist/public/assets/{auth-state-cache-BXAoUmHN.js → auth-state-cache-CfU3gJ3i.js} +1 -1
  48. package/dist/public/assets/client-version-BBhtdyiC.js +1 -0
  49. package/dist/public/assets/{config-provider-YhhBOmCK.js → config-provider-DstRVgzH.js} +1 -1
  50. package/dist/public/assets/{dist-CWKw6fA9.js → dist-DKsN2Ojq.js} +1 -1
  51. package/dist/public/assets/{dist-C6nSogV9.js → dist-Vm1kQiqo.js} +1 -1
  52. package/dist/public/assets/{doc-hash-eIVtLs9w.js → doc-hash-B8kD24Kw.js} +1 -1
  53. package/dist/public/assets/{documents-events-DeUc9zJv.js → documents-events-DQ6Iario.js} +1 -1
  54. package/dist/public/assets/{file-tree-adapter-vjTAoe5H.js → file-tree-adapter-eftmn56d.js} +1 -1
  55. package/dist/public/assets/{index-B8c-hqIt.js → index-BgQgA_cx.js} +8 -8
  56. package/dist/public/assets/{keyboard-shortcuts-CUmPZNQy.js → keyboard-shortcuts-DZ9kTSZ4.js} +1 -1
  57. package/dist/public/assets/{lint-config-client-nikplC1R.js → lint-config-client-Bg-6mquJ.js} +1 -1
  58. package/dist/public/assets/{navigation-targets-DxoCd6kX.js → navigation-targets-4J3F85tT.js} +1 -1
  59. package/dist/public/assets/{open-managed-artifact-tab-ZPlXuFu4.js → open-managed-artifact-tab-ze9HkqWn.js} +1 -1
  60. package/dist/public/assets/{pending-receive-nav-store-CEPAOvDY.js → pending-receive-nav-store-CVDTioM4.js} +1 -1
  61. package/dist/public/assets/{prop-types-DUCnPFii.js → prop-types-B0l6ZN6O.js} +1 -1
  62. package/dist/public/assets/{receive-store-y2q0bQn6.js → receive-store-jfaprLyZ.js} +1 -1
  63. package/dist/public/assets/{selection-context-Db3fWWF7.js → selection-context-BpEA0WhV.js} +1 -1
  64. package/dist/public/assets/{skill-actions-BtUexWRp.js → skill-actions-s_ATobEI.js} +1 -1
  65. package/dist/public/assets/{skills-api-Bww6-eOu.js → skills-api-CYoD9FQt.js} +1 -1
  66. package/dist/public/assets/{src-CpymDWKp.js → src-B-pNk3y3.js} +1 -1
  67. package/dist/public/assets/{target-navigation-intent-C1iQZwv4.js → target-navigation-intent-95GTKrco.js} +1 -1
  68. package/dist/public/assets/{telemetry-impl-CcmuhtrG.js → telemetry-impl-BgQUPJ0t.js} +1 -1
  69. package/dist/public/assets/{telemetry-startup-CARo6YEP.js → telemetry-startup-DcvNN2rn.js} +1 -1
  70. package/dist/public/assets/{terminal-launch-events-CTfLdB6Z.js → terminal-launch-events-D0NkBM4g.js} +1 -1
  71. package/dist/public/assets/{terminal-telemetry-CbpvB1jF.js → terminal-telemetry-DxZXlrf4.js} +1 -1
  72. package/dist/public/assets/{typing-burst-detector-CwFvl_zZ.js → typing-burst-detector-CI_4wux0.js} +1 -1
  73. package/dist/public/assets/{use-activity-panel-C8eRf28P.js → use-activity-panel-DoU5dDI7.js} +1 -1
  74. package/dist/public/assets/{use-apply-config-color-theme-Cn_1YtLn.js → use-apply-config-color-theme-DBdIMwiU.js} +1 -1
  75. package/dist/public/assets/{use-collab-url-JouvqC5o.js → use-collab-url-CwAStsIj.js} +1 -1
  76. package/dist/public/assets/{use-live-xterm-theme-BnrEyx1M.js → use-live-xterm-theme-oqXGh0AM.js} +1 -1
  77. package/dist/public/assets/{use-terminal-enabled-BOL2sXHs.js → use-terminal-enabled-B1QnDzPO.js} +1 -1
  78. package/dist/public/assets/{use-timeline-entry-diff-CpGmM4IW.js → use-timeline-entry-diff-C_hkFzJg.js} +1 -1
  79. package/dist/public/assets/{use-workspace-BZeW5fgR.js → use-workspace-DyAcZSjY.js} +1 -1
  80. package/dist/public/assets/{workspace-paths-CS1BfvNO.js → workspace-paths-B_ozK4P-.js} +1 -1
  81. package/dist/public/assets/{zod-D4GZNMdC.js → zod-CCGVCn6n.js} +1 -1
  82. package/dist/public/index.html +35 -35
  83. package/dist/{repair-launch-json-BqMX91yY.mjs → repair-launch-json-BGucssnq.mjs} +2 -2
  84. package/dist/{repair-mcp-configs-Pzh4BjH1.mjs → repair-mcp-configs-DmRQJ8ZA.mjs} +2 -2
  85. package/dist/{repair-skills-Q9Gr8Nvl.mjs → repair-skills-DaVaOiQC.mjs} +2 -2
  86. package/dist/repair-skills-vw_jVt0o.mjs +1 -0
  87. package/dist/server-lock-DZZ64TDY.mjs +1 -0
  88. package/dist/{server-lock-C2OcZirx.mjs → server-lock-DzWMWbLN.mjs} +2 -2
  89. package/dist/{src-DTPLCYnP.mjs → src-Cwu3lS3D.mjs} +2 -2
  90. package/dist/{src-ncRTs63f.mjs → src-DJ0-ChPY.mjs} +2 -2
  91. package/dist/{src-BEaiZuXz.mjs → src-DxAg43k_.mjs} +6 -6
  92. package/dist/{src-C4MRpQ6i.mjs → src-eVRfK1KK.mjs} +1 -1
  93. package/dist/{start-DyvuJUR_.mjs → start-9DwCccQZ.mjs} +2 -2
  94. package/dist/start-CyWHw24I.mjs +1 -0
  95. package/dist/{write-project-skill-CMePkU0W.mjs → write-project-skill-DtERurRT.mjs} +2 -2
  96. package/package.json +4 -4
  97. package/dist/constants-DpFOPcaR.mjs +0 -2
  98. package/dist/git-handle-DY72DIzL.mjs +0 -1
  99. package/dist/init-C5AeIGix.mjs +0 -1
  100. package/dist/loader-B21K_fve.mjs +0 -1
  101. package/dist/md-manager-Burt5wQf.mjs +0 -2
  102. package/dist/preview-DkTBLSdT.mjs +0 -1
  103. package/dist/public/assets/client-version-BcS_alrQ.js +0 -1
  104. package/dist/repair-skills-pY9FxlXw.mjs +0 -1
  105. package/dist/server-lock-DTx_Ih9P.mjs +0 -1
  106. package/dist/start-DA5Owg6k.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$i as i,$n as a,$r as o,$t as s,A as c,Aa as l,Ai as u,An as d,Ar as f,At as p,B as m,Ba as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Cr as S,Ct as C,D as ee,Da as te,Di as ne,Dn as re,Dr as ie,Dt as ae,E as w,Ea as oe,Ei as se,En as ce,Er as le,Et as ue,F as de,Fa as fe,Fi as pe,Fn as me,Fr as he,Ft as ge,G as _e,Ga as T,Gn as ve,Gr as ye,Gt as be,H as xe,Ha as Se,Hi as Ce,Hn as we,Hr as Te,Ht as Ee,Ia as De,Ii as Oe,In as ke,Ir as Ae,It as je,J as Me,Ji as Ne,Jn as Pe,Jr as Fe,Jt as Ie,K as Le,Kn as Re,Kr as ze,Kt as Be,La as Ve,Li as He,Ln as Ue,Lr as We,Lt as Ge,M as Ke,Ma as qe,Mi as Je,Mn as Ye,Mr as Xe,Mt as Ze,N as Qe,Na as $e,Ni as et,Nn as tt,Nr as nt,Nt as rt,O as it,Oa as at,Oi as ot,On as st,Or as ct,Ot as lt,Pa as ut,Pi as dt,Pn as ft,Pr as pt,Pt as mt,Q as ht,Qi as gt,Qn as _t,Qr as vt,Qt as yt,R as bt,Ra as xt,Ri as St,Rn as Ct,Rr as wt,Rt as Tt,S as Et,Si as eee,Sn as Dt,Sr as tee,St as Ot,T as kt,Ta as At,Ti as nee,Tn as ree,Tr as jt,Tt as Mt,U as Nt,Ui as Pt,Un as Ft,Ur as It,Ut as Lt,V as Rt,Va as zt,Vi as Bt,Vn as Vt,Vr as Ht,Vt as Ut,W as Wt,Wn as Gt,Wr as Kt,Wt as qt,X as Jt,Xi as Yt,Xn as Xt,Xr as Zt,Xt as Qt,Y as $t,Yi as en,Yn as iee,Yr as tn,Yt as nn,Z as rn,Zn as aee,Zr as an,Zt as on,_ as sn,_a as cn,_i as ln,_n as un,_r as dn,_t as fn,a as pn,aa as mn,ai as hn,an as gn,ar as _n,at as vn,b as yn,ba as bn,bi as xn,bn as Sn,br as Cn,bt as wn,c as Tn,ca as En,ci as Dn,cn as On,cr as kn,ct as An,d as jn,di as Mn,dn as Nn,dr as Pn,dt as Fn,ei as In,en as oee,er as see,et as Ln,f as Rn,fi as zn,fn as cee,fr as Bn,ft as Vn,g as Hn,ga as Un,gi as Wn,gn as Gn,gr as Kn,gt as qn,h as Jn,hi as Yn,hn as lee,hr as Xn,ht as Zn,i as Qn,ia as $n,ii as er,in as tr,ir as nr,it as rr,j as ir,ja as ar,ji as or,jn as sr,jr as cr,jt as lr,k as ur,ka as dr,ki as fr,kn as pr,kr as mr,kt as hr,l as gr,li as _r,ln as vr,lr as yr,lt as br,m as xr,ma as Sr,mi as Cr,mn as wr,mr as Tr,mt as Er,n as Dr,na as Or,ni as kr,nn as Ar,nr as jr,nt as Mr,o as Nr,oa as Pr,oi as Fr,on as Ir,or as Lr,ot as Rr,pa as zr,pn as Br,pr as Vr,pt as Hr,q as Ur,qi as Wr,qn as Gr,qr as Kr,qt as qr,r as Jr,ra as Yr,ri as Xr,rn as Zr,rr as Qr,rt as $r,s as ei,si as ti,sn as ni,sr as ri,st as ii,t as ai,ta as oi,ti as si,tn as ci,tr as li,tt as uee,u as ui,ua as di,ui as fi,un as pi,ur as mi,ut as hi,v as gi,va as _i,vi as dee,vn as fee,vr as vi,vt as yi,w as pee,wa as bi,wi as xi,wn as Si,wr as mee,wt as Ci,x as wi,xa as Ti,xi as Ei,xn as Di,xr as Oi,xt as ki,y as Ai,ya as ji,yi as Mi,yn as Ni,yr as Pi,yt as Fi,z as Ii,za as Li,zi as Ri,zn as hee,zr as gee,zt as _ee}from"./src-DTPLCYnP.mjs";import{$ as zi,A as Bi,C as Vi,Ct as Hi,Dt as Ui,Et as Wi,G as Gi,H as Ki,I as qi,K as Ji,L as Yi,N as Xi,Ot as Zi,Q as Qi,R as $i,S as ea,St as ta,T as na,Tt as ra,U as ia,V as aa,X as E,Y as D,Z as oa,_ as sa,_t as ca,at as O,bt as la,ct as k,dt as A,et as ua,ft as da,g as fa,h as pa,i as ma,it as j,l as ha,lt as M,m as ga,mt as _a,n as va,nt as N,ot as ya,pt as ba,q as xa,r as Sa,rt as Ca,st as wa,t as Ta,u as Ea,ut as P,vt as Da,w as Oa,wt as ka,xt as Aa,yt as ja,z as Ma}from"./sleep-DcENuR74.mjs";import{c as Na,i as Pa,l as Fa,n as Ia,s as La}from"./esm-CItKw7Y6.mjs";import{n as Ra,t as za}from"./md-manager-Burt5wQf.mjs";import{A as Ba,C as Va,D as Ha,E as Ua,N as Wa,O as Ga,S as Ka,T as qa,_ as Ja,a as Ya,b as Xa,c as Za,d as Qa,f as $a,g as eo,h as to,i as no,j as ro,k as io,l as ao,m as oo,n as so,o as co,p as lo,r as uo,s as fo,t as po,u as mo,v as ho,w as go,x as _o,y as vo}from"./fs-traced-B-qtPUmb.mjs";import{D as yo,E as bo,S as xo,T as So,a as Co,b as wo,l as To,p as Eo,r as F,s as Do,x as Oo,y as ko}from"./logger-CuGHGn_E.mjs";import{a as Ao,i as jo,o as Mo,r as No,s as Po,t as Fo}from"./git-handle-Kmafc544.mjs";import{t as Io}from"./libesm-CG75CrN9.mjs";import{S as Lo,a as Ro,b as vee,c as zo,d as Bo,f as Vo,g as Ho,h as Uo,i as Wo,l as Go,m as Ko,n as qo,r as Jo,x as Yo,y as Xo}from"./server-lock-C2OcZirx.mjs";import{n as Zo,t as Qo}from"./build-DYQrG4v7.mjs";import{t as $o}from"./yazl-BafwB467.mjs";import{t as es}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as ts,c as ns,d as rs,f as is,h as as,i as os,l as ss,m as cs,n as ls,o as us,p as ds,r as fs,s as ps,t as ms,u as hs}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as gs,B as _s,C as vs,D as ys,E as bs,F as xs,H as Ss,I as Cs,L as ws,M as Ts,N as Es,O as Ds,P as Os,S as ks,T as As,V as js,_ as Ms,a as Ns,b as Ps,c as Fs,d as Is,f as Ls,g as Rs,h as zs,i as Bs,j as Vs,k as Hs,l as Us,m as Ws,n as Gs,o as Ks,p as qs,r as Js,s as Ys,t as Xs,u as Zs,v as Qs,w as $s,x as ec,y as tc,z as nc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as rc,c as ic,d as ac,i as oc,l as sc,n as cc,o as lc,r as uc,s as dc,t as fc,u as pc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as mc,r as hc,t as gc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as _c}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as vc}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as yc,t as bc}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as xc,t as Sc}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Cc,r as wc,t as Tc}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ec,t as Dc}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Oc}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as kc}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Ac}from"./wrapper-BcpqREsI.mjs";import{createRequire as jc}from"node:module";import{execFile as Mc,spawn as Nc,spawnSync as Pc}from"node:child_process";import*as Fc from"node:path";import{basename as Ic,delimiter as Lc,dirname as Rc,extname as zc,isAbsolute as Bc,join as I,normalize as Vc,posix as Hc,relative as L,resolve as R,sep as Uc,win32 as Wc}from"node:path";import*as Gc from"node:fs";import{appendFileSync as Kc,chmodSync as qc,closeSync as Jc,constants as Yc,createReadStream as Xc,createWriteStream as Zc,existsSync as z,lstatSync as Qc,mkdirSync as $c,mkdtempSync as el,openSync as tl,readFile as nl,readFileSync as B,readSync as rl,readdirSync as il,readlinkSync as al,realpathSync as ol,renameSync as sl,rmSync as cl,rmdirSync as ll,statSync as ul,unlinkSync as dl,writeFileSync as fl}from"node:fs";import{arch as pl,availableParallelism as ml,homedir as hl,hostname as gl,platform as _l,tmpdir as vl}from"node:os";import{access as yl,chmod as bl,constants as xl,lstat as Sl,readFile as Cl,readdir as wl,realpath as Tl,stat as El,writeFile as Dl}from"node:fs/promises";import{Readable as Ol,Transform as kl,Writable as Al}from"node:stream";import{URLSearchParams as jl,fileURLToPath as Ml,pathToFileURL as Nl}from"node:url";import Pl,{createHash as Fl,randomUUID as Il,webcrypto as Ll}from"node:crypto";import Rl from"crypto";import{Readable as zl}from"stream";import{Worker as Bl}from"node:worker_threads";import{monitorEventLoopDelay as Vl,performance as Hl}from"node:perf_hooks";import{createInterface as Ul}from"node:readline";import{pipeline as Wl}from"node:stream/promises";import{setTimeout as Gl}from"node:timers/promises";import{promisify as Kl}from"node:util";import{lookup as yee}from"node:dns/promises";import{request as bee}from"node:http";import{request as xee}from"node:https";import{createBrotliDecompress as See,createGunzip as Cee,createInflate as wee}from"node:zlib";import{Http2ServerRequest as ql,constants as Tee}from"http2";import{AsyncLocalStorage as Eee}from"node:async_hooks";import{lookup as Dee}from"node:dns";import Oee from"node:tls";var Jl=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=B(I(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Bc(t)?t:R(this.gitDir,t))}catch(e){if(!Ql(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=B(I(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return Ql(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}let t=/^ref:[ \t]*(refs\/heads\/(.+))$/.exec(e);return t?.[2]?{kind:`branch`,branch:t[2],ref:t[1]}:eu(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=B(I(t.path,`config`),`utf-8`)}catch(e){return Ql(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=kee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!$l(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=R(t.path,e),r=L(t.path,n);if(r.startsWith(`..`)||Bc(r))return{kind:`invalid`};try{let e=B(n,`utf-8`).trim(),t=Mee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Ql(e))return{kind:`unreadable`,cause:e}}let i;try{i=B(I(t.path,`packed-refs`),`utf-8`)}catch(e){return Ql(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}for(let t of i.split(/\r?\n/)){let n=t.trim();if(n.length===0||n.startsWith(`#`)||n.startsWith(`^`))continue;let r=n.split(/\s+/);if(r.length===2&&r[1]===e)return eu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Yl(e){return Zl(R(e),``)}function Xl(e){let t=R(e),n=R(hl());if(t===n)return{kind:`absent`};let r=Zl(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=Rc(i);if(e===i||e===n)return{kind:`absent`};let r=Zl(e,L(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Zl(e,t){let n=I(e,`.git`),r;try{r=ul(n)}catch(e){return Ql(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Jl(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=B(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Bc(o)?o:R(e,o);try{if(!ul(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Jl(`linked`,e,t,n,s)}}function kee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Aee(r);if(e.length===0)continue;if(e.startsWith(`[`)){n=/^\[\s*remote\s+["'](.+)["']\s*\]$/.exec(e)?.[1]===t;continue}if(!n)continue;let i=/^url\s*=\s*(.*)$/.exec(e);if(!i)continue;let a=jee(i[1]);if(a.length>0)return a}return null}function Aee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function jee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Ql(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function $l(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Mee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?$l(t[1])?{kind:`symbolic`,target:t[1]}:null:eu(e)?{kind:`oid`,oid:e}:null}function eu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Nee(e){return`git-author-${T(e.trim().toLowerCase())}`}const Pee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function tu(e){let t=Xl(e);if(t.kind!==`repository`)return t;let{repository:n}=t;return n.kind===`directory`?{kind:`directory`,path:n.gitDir,projectSubPath:n.projectSubPath}:{kind:`linked`,path:n.gitDir,gitPath:n.gitPath,projectSubPath:n.projectSubPath}}function nu(e){let t=tu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ru(e){let t=tu(e);switch(t.kind){case`directory`:return R(t.path,iu(t.projectSubPath));case`linked`:if(!z(t.path))throw new au(t.gitPath,t.path);return R(t.path,iu(t.projectSubPath));case`malformed-pointer`:throw new au(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new ou(t.gitPath,{cause:t.cause});case`absent`:return R(e,`.git/ok`)}}function iu(e){return e===``?`ok`:`ok-${Fee(e)}`}function Fee(e){let t=e.split(Uc).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Iee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Iee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var au=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}},ou=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 Lee(e){let t;try{t=ru(e)}catch(e){if(e instanceof au||e instanceof ou)return null;throw e}return z(R(t,`HEAD`))?t:null}function su(e){return`refs/wip/${e}/`}function Ree(e){if(!e)return[];let t=[];for(let n of e.split(`
1
+ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$i as i,$n as a,$r as o,$t as s,A as c,Aa as l,Ai as u,An as d,Ar as f,At as p,B as m,Ba as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Cr as S,Ct as C,D as ee,Da as te,Di as ne,Dn as re,Dr as ie,Dt as ae,E as w,Ea as oe,Ei as se,En as ce,Er as le,Et as ue,F as de,Fa as fe,Fi as pe,Fn as me,Fr as he,Ft as ge,G as _e,Ga as T,Gn as ve,Gr as ye,Gt as be,H as xe,Ha as Se,Hi as Ce,Hn as we,Hr as Te,Ht as Ee,Ia as De,Ii as Oe,In as ke,Ir as Ae,It as je,J as Me,Ji as Ne,Jn as Pe,Jr as Fe,Jt as Ie,K as Le,Kn as Re,Kr as ze,Kt as Be,La as Ve,Li as He,Ln as Ue,Lr as We,Lt as Ge,M as Ke,Ma as qe,Mi as Je,Mn as Ye,Mr as Xe,Mt as Ze,N as Qe,Na as $e,Ni as et,Nn as tt,Nr as nt,Nt as rt,O as it,Oa as at,Oi as ot,On as st,Or as ct,Ot as lt,Pa as ut,Pi as dt,Pn as ft,Pr as pt,Pt as mt,Q as ht,Qi as gt,Qn as _t,Qr as vt,Qt as yt,R as bt,Ra as xt,Ri as St,Rn as Ct,Rr as wt,Rt as Tt,S as Et,Si as eee,Sn as Dt,Sr as tee,St as Ot,T as kt,Ta as At,Ti as nee,Tn as ree,Tr as jt,Tt as Mt,U as Nt,Ui as Pt,Un as Ft,Ur as It,Ut as Lt,V as Rt,Va as zt,Vi as Bt,Vn as Vt,Vr as Ht,Vt as Ut,W as Wt,Wn as Gt,Wr as Kt,Wt as qt,X as Jt,Xi as Yt,Xn as Xt,Xr as Zt,Xt as Qt,Y as $t,Yi as en,Yn as iee,Yr as tn,Yt as nn,Z as rn,Zn as aee,Zr as an,Zt as on,_ as sn,_a as cn,_i as ln,_n as un,_r as dn,_t as fn,a as pn,aa as mn,ai as hn,an as gn,ar as _n,at as vn,b as yn,ba as bn,bi as xn,bn as Sn,br as Cn,bt as wn,c as Tn,ca as En,ci as Dn,cn as On,cr as kn,ct as An,d as jn,di as Mn,dn as Nn,dr as Pn,dt as Fn,ei as In,en as oee,er as see,et as Ln,f as Rn,fi as zn,fn as cee,fr as Bn,ft as Vn,g as Hn,ga as Un,gi as Wn,gn as Gn,gr as Kn,gt as qn,h as Jn,hi as Yn,hn as lee,hr as Xn,ht as Zn,i as Qn,ia as $n,ii as er,in as tr,ir as nr,it as rr,j as ir,ja as ar,ji as or,jn as sr,jr as cr,jt as lr,k as ur,ka as dr,ki as fr,kn as pr,kr as mr,kt as hr,l as gr,li as _r,ln as vr,lr as yr,lt as br,m as xr,ma as Sr,mi as Cr,mn as wr,mr as Tr,mt as Er,n as Dr,na as Or,ni as kr,nn as Ar,nr as jr,nt as Mr,o as Nr,oa as Pr,oi as Fr,on as Ir,or as Lr,ot as Rr,pa as zr,pn as Br,pr as Vr,pt as Hr,q as Ur,qi as Wr,qn as Gr,qr as Kr,qt as qr,r as Jr,ra as Yr,ri as Xr,rn as Zr,rr as Qr,rt as $r,s as ei,si as ti,sn as ni,sr as ri,st as ii,t as ai,ta as oi,ti as si,tn as ci,tr as li,tt as uee,u as ui,ua as di,ui as fi,un as pi,ur as mi,ut as hi,v as gi,va as _i,vi as dee,vn as fee,vr as vi,vt as yi,w as pee,wa as bi,wi as xi,wn as Si,wr as mee,wt as Ci,x as wi,xa as Ti,xi as Ei,xn as Di,xr as Oi,xt as ki,y as Ai,ya as ji,yi as Mi,yn as Ni,yr as Pi,yt as Fi,z as Ii,za as Li,zi as Ri,zn as hee,zr as gee,zt as _ee}from"./src-Cwu3lS3D.mjs";import{$ as zi,A as Bi,C as Vi,Ct as Hi,Dt as Ui,Et as Wi,G as Gi,H as Ki,I as qi,K as Ji,L as Yi,N as Xi,Ot as Zi,Q as Qi,R as $i,S as ea,St as ta,T as na,Tt as ra,U as ia,V as aa,X as E,Y as D,Z as oa,_ as sa,_t as ca,at as O,bt as la,ct as k,dt as A,et as ua,ft as da,g as fa,h as pa,i as ma,it as j,l as ha,lt as M,m as ga,mt as _a,n as va,nt as N,ot as ya,pt as ba,q as xa,r as Sa,rt as Ca,st as wa,t as Ta,u as Ea,ut as P,vt as Da,w as Oa,wt as ka,xt as Aa,yt as ja,z as Ma}from"./sleep-DcENuR74.mjs";import{c as Na,i as Pa,l as Fa,n as Ia,s as La}from"./esm-CItKw7Y6.mjs";import{n as Ra,t as za}from"./md-manager-DtA0LK6p.mjs";import{A as Ba,C as Va,D as Ha,E as Ua,N as Wa,O as Ga,S as Ka,T as qa,_ as Ja,a as Ya,b as Xa,c as Za,d as Qa,f as $a,g as eo,h as to,i as no,j as ro,k as io,l as ao,m as oo,n as so,o as co,p as lo,r as uo,s as fo,t as po,u as mo,v as ho,w as go,x as _o,y as vo}from"./fs-traced-B-qtPUmb.mjs";import{D as yo,E as bo,S as xo,T as So,a as Co,b as wo,l as To,p as Eo,r as F,s as Do,x as Oo,y as ko}from"./logger-CuGHGn_E.mjs";import{a as Ao,i as jo,o as Mo,r as No,s as Po,t as Fo}from"./git-handle-DnLoe9hy.mjs";import{t as Io}from"./libesm-CG75CrN9.mjs";import{S as Lo,a as Ro,b as vee,c as zo,d as Bo,f as Vo,g as Ho,h as Uo,i as Wo,l as Go,m as Ko,n as qo,r as Jo,x as Yo,y as Xo}from"./server-lock-DzWMWbLN.mjs";import{n as Zo,t as Qo}from"./build-DYQrG4v7.mjs";import{t as $o}from"./yazl-BafwB467.mjs";import{t as es}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as ts,c as ns,d as rs,f as is,h as as,i as os,l as ss,m as cs,n as ls,o as us,p as ds,r as fs,s as ps,t as ms,u as hs}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as gs,B as _s,C as vs,D as ys,E as bs,F as xs,H as Ss,I as Cs,L as ws,M as Ts,N as Es,O as Ds,P as Os,S as ks,T as As,V as js,_ as Ms,a as Ns,b as Ps,c as Fs,d as Is,f as Ls,g as Rs,h as zs,i as Bs,j as Vs,k as Hs,l as Us,m as Ws,n as Gs,o as Ks,p as qs,r as Js,s as Ys,t as Xs,u as Zs,v as Qs,w as $s,x as ec,y as tc,z as nc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as rc,c as ic,d as ac,i as oc,l as sc,n as cc,o as lc,r as uc,s as dc,t as fc,u as pc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as mc,r as hc,t as gc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as _c}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as vc}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as yc,t as bc}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as xc,t as Sc}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Cc,r as wc,t as Tc}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ec,t as Dc}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Oc}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as kc}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Ac}from"./wrapper-BcpqREsI.mjs";import{createRequire as jc}from"node:module";import{execFile as Mc,spawn as Nc,spawnSync as Pc}from"node:child_process";import*as Fc from"node:path";import{basename as Ic,delimiter as Lc,dirname as Rc,extname as zc,isAbsolute as Bc,join as I,normalize as Vc,posix as Hc,relative as L,resolve as R,sep as Uc,win32 as Wc}from"node:path";import*as Gc from"node:fs";import{appendFileSync as Kc,chmodSync as qc,closeSync as Jc,constants as Yc,createReadStream as Xc,createWriteStream as Zc,existsSync as z,lstatSync as Qc,mkdirSync as $c,mkdtempSync as el,openSync as tl,readFile as nl,readFileSync as B,readSync as rl,readdirSync as il,readlinkSync as al,realpathSync as ol,renameSync as sl,rmSync as cl,rmdirSync as ll,statSync as ul,unlinkSync as dl,writeFileSync as fl}from"node:fs";import{arch as pl,availableParallelism as ml,homedir as hl,hostname as gl,platform as _l,tmpdir as vl}from"node:os";import{access as yl,chmod as bl,constants as xl,lstat as Sl,readFile as Cl,readdir as wl,realpath as Tl,stat as El,writeFile as Dl}from"node:fs/promises";import{Readable as Ol,Transform as kl,Writable as Al}from"node:stream";import{URLSearchParams as jl,fileURLToPath as Ml,pathToFileURL as Nl}from"node:url";import Pl,{createHash as Fl,randomUUID as Il,webcrypto as Ll}from"node:crypto";import Rl from"crypto";import{Readable as zl}from"stream";import{Worker as Bl}from"node:worker_threads";import{monitorEventLoopDelay as Vl,performance as Hl}from"node:perf_hooks";import{createInterface as Ul}from"node:readline";import{pipeline as Wl}from"node:stream/promises";import{setTimeout as Gl}from"node:timers/promises";import{promisify as Kl}from"node:util";import{lookup as yee}from"node:dns/promises";import{request as bee}from"node:http";import{request as xee}from"node:https";import{createBrotliDecompress as See,createGunzip as Cee,createInflate as wee}from"node:zlib";import{Http2ServerRequest as ql,constants as Tee}from"http2";import{AsyncLocalStorage as Eee}from"node:async_hooks";import{lookup as Dee}from"node:dns";import Oee from"node:tls";var Jl=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=B(I(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Bc(t)?t:R(this.gitDir,t))}catch(e){if(!Ql(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=B(I(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return Ql(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}let t=/^ref:[ \t]*(refs\/heads\/(.+))$/.exec(e);return t?.[2]?{kind:`branch`,branch:t[2],ref:t[1]}:eu(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=B(I(t.path,`config`),`utf-8`)}catch(e){return Ql(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=kee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!$l(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=R(t.path,e),r=L(t.path,n);if(r.startsWith(`..`)||Bc(r))return{kind:`invalid`};try{let e=B(n,`utf-8`).trim(),t=Mee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Ql(e))return{kind:`unreadable`,cause:e}}let i;try{i=B(I(t.path,`packed-refs`),`utf-8`)}catch(e){return Ql(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}for(let t of i.split(/\r?\n/)){let n=t.trim();if(n.length===0||n.startsWith(`#`)||n.startsWith(`^`))continue;let r=n.split(/\s+/);if(r.length===2&&r[1]===e)return eu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Yl(e){return Zl(R(e),``)}function Xl(e){let t=R(e),n=R(hl());if(t===n)return{kind:`absent`};let r=Zl(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=Rc(i);if(e===i||e===n)return{kind:`absent`};let r=Zl(e,L(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Zl(e,t){let n=I(e,`.git`),r;try{r=ul(n)}catch(e){return Ql(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Jl(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=B(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Bc(o)?o:R(e,o);try{if(!ul(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Jl(`linked`,e,t,n,s)}}function kee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Aee(r);if(e.length===0)continue;if(e.startsWith(`[`)){n=/^\[\s*remote\s+["'](.+)["']\s*\]$/.exec(e)?.[1]===t;continue}if(!n)continue;let i=/^url\s*=\s*(.*)$/.exec(e);if(!i)continue;let a=jee(i[1]);if(a.length>0)return a}return null}function Aee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function jee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Ql(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function $l(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Mee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?$l(t[1])?{kind:`symbolic`,target:t[1]}:null:eu(e)?{kind:`oid`,oid:e}:null}function eu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Nee(e){return`git-author-${T(e.trim().toLowerCase())}`}const Pee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function tu(e){let t=Xl(e);if(t.kind!==`repository`)return t;let{repository:n}=t;return n.kind===`directory`?{kind:`directory`,path:n.gitDir,projectSubPath:n.projectSubPath}:{kind:`linked`,path:n.gitDir,gitPath:n.gitPath,projectSubPath:n.projectSubPath}}function nu(e){let t=tu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ru(e){let t=tu(e);switch(t.kind){case`directory`:return R(t.path,iu(t.projectSubPath));case`linked`:if(!z(t.path))throw new au(t.gitPath,t.path);return R(t.path,iu(t.projectSubPath));case`malformed-pointer`:throw new au(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new ou(t.gitPath,{cause:t.cause});case`absent`:return R(e,`.git/ok`)}}function iu(e){return e===``?`ok`:`ok-${Fee(e)}`}function Fee(e){let t=e.split(Uc).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Iee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Iee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var au=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}},ou=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 Lee(e){let t;try{t=ru(e)}catch(e){if(e instanceof au||e instanceof ou)return null;throw e}return z(R(t,`HEAD`))?t:null}function su(e){return`refs/wip/${e}/`}function Ree(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 cu=`ok-checkpoint-v1: `;function lu(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(cu))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 uu(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${cu}${JSON.stringify(t)}`}const du=`ok-actor: `;function fu(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),`${du}${JSON.stringify(i)}`}function pu(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=zee(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 zee(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 Bee(e){if(!e)return null;for(let t of e.split(`
4
4
  `)){let e=t.trim();if(!e.startsWith(du))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:pu(n)}return null}function mu(e){if(!e)return[];let t=[];for(let n of e.split(`
@@ -95,7 +95,7 @@ Karpathy's insight: "The tedious part of maintaining a knowledge base is not the
95
95
  `),r=e=>e.endsWith(`\r`)?e.slice(0,-1):e,i=0;for(;i<n.length;){let e=r(n[i]??``),a=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!a){i++;continue}let o=a[1]??``,s=o[0]??"`";if(s==="`"&&e.slice(e.indexOf(o)+o.length).includes("`")){i++;continue}let c=a[2]??``,l=RegExp(`^ {0,3}\\${s}{${o.length},}[ \t]*$`),u=[],d=i+1;for(;d<n.length&&!l.test(r(n[d]??``));)u.push(n[d]??``),d++;if(c===`mermaid`){let e=u.join(`
96
96
  `),n=(u.find(e=>e.trim().length>0)?.trim()??``).slice(0,200);t.push({firstLine:n,body:e})}i=d+1}return t}async function ZL(){let{Window:e}=await import(`./lib-CE7ieLC-.mjs`),t=new e({url:`http://localhost/`}),n={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},r=new Map;try{for(let[e,t]of Object.entries(n))r.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-BeGj3DLy.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
97
97
  A-->B`),e}finally{for(let[e,t]of r)t?Object.defineProperty(globalThis,e,t):delete globalThis[e]}}function QL(e){return YL??=ZL().catch(t=>(JL.warn({err:t,"doc.name":e},`mermaid validator unavailable — render validation disabled for this process`),null)),YL}function $L(e){let t=e.match(/Parse error on line (\d+)/);if(!t?.[1])return;let n=Number(t[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}async function eR(e,t){try{if(!e.includes(`mermaid`))return;let{body:n}=Ln(e),r=XL(n);if(r.length===0)return;let i=performance.now(),a=await QL(t);if(a===null)return;let o=performance.now(),s=[],c=0;for(let e=0;e<r.length&&s.length<10&&!(c>=20);e++){if(performance.now()-o>2e3){JL.debug({"doc.name":t,skippedFrom:e+1,fences:r.length},`mermaid validation budget exceeded — remaining fences skipped`);break}let n=r[e];if(n!==void 0){if(n.body.length>1e5||n.body.split(`
98
- `).length>2e3){JL.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{c++,await a.parse(n.body)}catch(r){if(r instanceof TypeError){JL.debug({err:r,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let i=r instanceof Error?r.message:String(r),a=i.slice(0,500),o=$L(i);s.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:n.firstLine,message:a,...o===void 0?{}:{line:o}})}}}let l=Math.round(performance.now()-i);if(s.length===0){l>250&&JL.debug({"doc.name":t,durationMs:l,fences:r.length},`mermaid validation slow (no warnings)`);return}return JL.debug({"doc.name":t,count:s.length,durationMs:l},`mermaid render warnings emitted`),s}catch(e){JL.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const tR=`share-construct-url`;function nR(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function rR(e,t,n,r,i){return`https://${e}/${t}/${n}/blob/${encodeURIComponent(r)}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function iR(e,t,n,r,i){let a=`https://${e}/${t}/${n}/tree/${encodeURIComponent(r)}`;return i===``?a:`${a}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function aR(e,t){let n=t?.branchExists,r=t?.kind,i=t?.freshness;F(`share`).info({action:`construct-url`,result:e,...n===void 0?{}:{branchExists:n},...r===void 0?{}:{kind:r},...i===void 0?{}:{freshness:i}},`share action`)}function oR(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}async function sR(e,t,n,r){try{let{git:r}=No(e,{timeoutMs:5e3}),i=`refs/remotes/origin/${t}`;await r.raw([`rev-parse`,`--verify`,i]);let a=n===``?`.`:n,[o,s,c]=await Promise.all([r.raw([`cat-file`,`-e`,`${i}:${n}`]).then(()=>!0).catch(()=>!1),r.raw([`diff`,`--name-only`,i,`--`,a]),r.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,a])]);return o?s.trim()!==``||c.trim()!==``?`stale`:`current`:`absent`}catch(e){let t=oR(e);F(`share`).warn({action:`freshness-probe-failed`,kind:r,error:t},`[share] freshness probe failed; omitting freshness`);return}}const cR=F(`git-context`);function lR(e){let t=Yl(e);return t.kind===`repository`?t.repository:null}function uR(e){let t=lR(e)?.readHead();return t?.kind===`branch`?t.branch:null}function dR(e){let t=e.toLowerCase().replace(/:\d+$/,``);return t===`www.github.com`?`github.com`:t}function fR(e){let t=e.trim();if(!t)return null;let n=(e,t,n)=>{let r=dR(e);return En.has(r)?null:{host:r,owner:t,repo:n}},r=/^https?:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return r||(r=/^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),r)||(r=/^[\w.-]+@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),r)||(r=/^git:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),r)?n(r[1],r[2],r[3]):null}function pR(e){let t=lR(e)?.readRemoteUrl(`origin`);if(t?.kind!==`configured`)return null;let n=t.url;return{originUrl:n,github:fR(n)}}function mR(e){let t=pR(e);if(!t)return{kind:`no-remote`};if(t.github){let{host:e,owner:n,repo:r}=t.github;return{kind:`ok`,host:e,owner:n,repo:r}}return{kind:`non-github`}}function hR(e){let t=mR(e);return t.kind===`ok`?t.host:(cR.debug({kind:t.kind},`[git-context] origin is not a GitHub host — falling back to github.com`),`github.com`)}function gR(e){let t=pR(e);if(!t)return null;if(t.github){let{host:e,owner:n,repo:r}=t.github;return{label:e===`github.com`?`${n}/${r}`:`${e}/${n}/${r}`,webUrl:`https://${e}/${n}/${r}`}}return{label:_R(t.originUrl),webUrl:null}}function _R(e){let t=e.trim().replace(/\.git$/,``),n=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(n)return`${n[1]}/${n[2]}`;let r=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return r?r[1]:t}function vR(e,t){return lR(e)?.readRef(`refs/remotes/origin/${t}`).kind===`present`}const yR=`share-publish-owners`,bR=`share-publish-name-check`,xR=`share-publish`,SR=3e4;function CR(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function wR(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function TR(e){let t=e.split(`
98
+ `).length>2e3){JL.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{c++,await a.parse(n.body)}catch(r){if(r instanceof TypeError){JL.debug({err:r,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let i=r instanceof Error?r.message:String(r),a=i.slice(0,500),o=$L(i);s.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:n.firstLine,message:a,...o===void 0?{}:{line:o}})}}}let l=Math.round(performance.now()-i);if(s.length===0){l>250&&JL.debug({"doc.name":t,durationMs:l,fences:r.length},`mermaid validation slow (no warnings)`);return}return JL.debug({"doc.name":t,count:s.length,durationMs:l},`mermaid render warnings emitted`),s}catch(e){JL.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const tR=`share-construct-url`;function nR(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function rR(e,t,n,r,i){return`https://${e}/${t}/${n}/blob/${encodeURIComponent(r)}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function iR(e,t,n,r,i){let a=`https://${e}/${t}/${n}/tree/${encodeURIComponent(r)}`;return i===``?a:`${a}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function aR(e,t){let n=t?.branchExists,r=t?.kind,i=t?.freshness;F(`share`).info({action:`construct-url`,result:e,...n===void 0?{}:{branchExists:n},...r===void 0?{}:{kind:r},...i===void 0?{}:{freshness:i}},`share action`)}function oR(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}async function sR(e,t,n,r){try{let{git:r}=No(e,{timeoutMs:5e3}),i=`refs/remotes/origin/${t}`;await r.raw([`rev-parse`,`--verify`,i]);let a=n===``?`.`:n,[o,s,c]=await Promise.all([r.raw([`cat-file`,`-e`,`${i}:${n}`]).then(()=>!0).catch(()=>!1),r.raw([`diff`,`--name-only`,i,`--`,a]),r.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,a])]);return o?s.trim()!==``||c.trim()!==``?`stale`:`current`:`absent`}catch(e){let t=oR(e);F(`share`).warn({action:`freshness-probe-failed`,kind:r,error:t},`[share] freshness probe failed; omitting freshness`);return}}const cR=F(`git-context`);function lR(e){let t=Yl(e);return t.kind===`repository`?t.repository:null}function uR(e){let t=lR(e)?.readHead();return t?.kind===`branch`?t.branch:null}function dR(e){let t=e.toLowerCase().replace(/:\d+$/,``);return t===`www.github.com`?`github.com`:t}function fR(e){let t=e.trim();if(!t)return null;let n=(e,t,n,r)=>{let i=dR(e);return En.has(i)?null:{host:i,owner:t,repo:n,transport:r}},r=/^https?:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return r?n(r[1],r[2],r[3],`https`):(r=/^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),r||(r=/^[\w.-]+@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),r)?n(r[1],r[2],r[3],`ssh`):(r=/^git:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),r?n(r[1],r[2],r[3],`git`):null))}function pR(e){let t=lR(e)?.readRemoteUrl(`origin`);if(t?.kind!==`configured`)return null;let n=t.url;return{originUrl:n,github:fR(n)}}function mR(e){let t=pR(e);if(!t)return{kind:`no-remote`};if(t.github){let{host:e,owner:n,repo:r,transport:i}=t.github;return{kind:`ok`,host:e,owner:n,repo:r,transport:i}}return{kind:`non-github`}}function hR(e){let t=mR(e);return t.kind===`ok`?t.host:(cR.debug({kind:t.kind},`[git-context] origin is not a GitHub host — falling back to github.com`),`github.com`)}function gR(e){let t=pR(e);if(!t)return null;if(t.github){let{host:e,owner:n,repo:r}=t.github;return{label:e===`github.com`?`${n}/${r}`:`${e}/${n}/${r}`,webUrl:`https://${e}/${n}/${r}`}}return{label:_R(t.originUrl),webUrl:null}}function _R(e){let t=e.trim().replace(/\.git$/,``),n=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(n)return`${n[1]}/${n[2]}`;let r=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return r?r[1]:t}function vR(e,t){return lR(e)?.readRef(`refs/remotes/origin/${t}`).kind===`present`}const yR=`share-publish-owners`,bR=`share-publish-name-check`,xR=`share-publish`,SR=3e4;function CR(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function wR(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function TR(e){let t=e.split(`
99
99
  `).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let n=JSON.parse(t[e]);if(n&&typeof n==`object`&&!Array.isArray(n))return n}catch{}return null}function ER(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let n of e.owners){if(!n||typeof n!=`object`)continue;let e=n,r=typeof e.login==`string`?e.login:null,i=e.kind===`user`||e.kind===`org`?e.kind:null;if(r===null||i===null)continue;let a=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:r,kind:i,...a?{avatarUrl:a}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:DR(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function DR(e){return e===`auth-required`||e===`network`}function OR(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:DR(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const kR=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function AR(e){return typeof e==`string`&&kR.has(e)}function jR(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,n=typeof e.repoName==`string`?e.repoName:null,r=typeof e.cloneUrl==`string`?e.cloneUrl:null,i=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&n!==null&&r!==null&&i!==null?{ok:!0,ownerLogin:t,repoName:n,cloneUrl:r,defaultBranch:i}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:AR(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function MR(e,t,n){F(`share`).info({action:e,result:t,...n?.count===void 0?{}:{count:n.count},...n?.available===void 0?{}:{available:n.available}},`share action`)}function NR(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const PR=`share-target-status`;function FR(e,t){for(let n of e)if(n.from===t){if(n.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:n.to};if(n.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function IR(e,t){let n=t.endsWith(`/`)?t:`${t}/`,r=new Set;for(let t of e){if(!t.from.startsWith(n)||!t.status.startsWith(`R`))continue;let e=t.from.slice(n.length);t.to.endsWith(`/${e}`)?r.add(t.to.slice(0,t.to.length-e.length-1)):r.add(`\0ambiguous`)}let i=r.size===1?[...r][0]:void 0;return i!==void 0&&i!==`\0ambiguous`?{verdict:`renamed`,renamedTo:i}:{verdict:`deleted`}}async function LR(e,t,n,r,i={}){let a=F(`share`),o=e=>(a.info({action:`target-status`,verdict:e.verdict,kind:r},`target-status verdict`),e),{git:s}=No(e,i.skipFetch?{}:{timeoutMs:i.fetchTimeoutMs??15e3});if(!i.skipFetch)try{await s.raw([`fetch`,`origin`,t])}catch(e){return a.warn({action:`target-status`,kind:r,error:oR(e)},`target-status fetch failed`),o({verdict:`unknown`})}let c=`origin/${t}`;try{if(await s.raw([`cat-file`,`-e`,`${c}:${n}`]).then(()=>!0).catch(()=>!1)){let t=await s.raw([`cat-file`,`-e`,`HEAD:${n}`]).then(()=>!0).catch(()=>!1),r=z(I(e,n));return o(t&&!r?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await s.raw([`log`,`-1`,`--format=%H`,c,`--`,n])).trim();if(t===``)return o({verdict:`never-on-branch`});let i=await uO(s,[`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t]),a=r===`folder`?IR(i,n):FR(i,n);return a.verdict===`renamed`&&!await s.raw([`cat-file`,`-e`,`${c}:${a.renamedTo}`]).then(()=>!0).catch(()=>!1)?o({verdict:`deleted`}):o(a)}catch(e){return a.warn({action:`target-status`,kind:r,error:oR(e)},`target-status detection failed`),o({verdict:`unknown`})}}const RR={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},zR=new Set(Object.values(RR));function BR(e){return zR.has(e)}const VR=Object.keys(RR),HR={discovery:`user`,project:`project`,"write-skill":`user`},UR=VR.filter(e=>HR[e]===`user`);function WR(e){return`packages/server/assets/skills/${e}/SKILL.md`}var GR=t($o(),1);const KR=102400,qR=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function JR(e,t={}){let n=t.platform??process.platform,r=t.checkDesktop??!1,i=t.home??hl(),a=[];r&&n===`darwin`&&(a.push(I(`/Applications`,qR,e)),a.push(I(i,`Applications`,qR,e))),a.push(Ml(new URL(`../dist/assets/skills/${e}`,import.meta.url))),a.push(Ml(new URL(`../assets/skills/${e}`,import.meta.url))),a.push(Ml(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of a)if(z(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${a.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*YR(e,t=e){let n=await wl(e,{withFileTypes:!0});for(let r of n){let n=I(e,r.name);r.isDirectory()?yield*YR(n,t):r.isFile()&&(yield L(t,n))}}function XR(e,t=Ic){return t(e)||`open-knowledge`}function ZR(e,t=Uc){return t===`/`?e:e.split(t).join(`/`)}async function QR(e,t,n=XR(e)){let r=new GR.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of YR(e))i.push(t);i.sort();for(let t of i){let i=I(e,t),a=`${n}/${ZR(t)}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=Zc(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function $R(e){return new Promise((t,n)=>{let r=Fl(`sha256`),i=Xc(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}function ez(e){let{frontmatter:t}=en(e);if(t===``)return;let n=Yt(t),r=n.search(/^metadata:/m);if(r<0)return;let i=n.slice(r).split(`
100
100
  `).slice(1);for(let e of i){if(/^[^\s]/.test(e))break;let t=e.match(/^\s+version:\s*["']?([^"'\s]+)["']?$/);if(t)return t[1]}}async function tz(e,t,n={}){let r=n.bundle??`project`,i=ul(e).size;if(i>KR)throw Error(`Built ${e} is ${i} bytes, exceeds ${KR}-byte ceiling`);let a=await $R(e),o=await Cl(I(n.sourceDir??JR(r,{checkDesktop:!1}),`SKILL.md`),`utf-8`),s=RR[r];if(!RegExp(`^name:\\s+${s}$`,`m`).test(o.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${s}'. Check packages/server/assets/skills/${r}/SKILL.md frontmatter.`);let c=ez(o);if(t!==void 0){if(!c)throw Error(`SKILL.md metadata.version missing. Add it to packages/server/assets/skills/${r}/SKILL.md.`);if(c!==t)throw Error(`SKILL.md metadata.version (${c}) does not match expected version (${t}).`)}return{size:i,sha256:a,skillVersion:c}}async function nz(e={}){let t=e.bundle??`project`,n=e.sourceDir??JR(t,{checkDesktop:e.checkDesktop??!1}),r=e.outputPath??I(process.cwd(),`openknowledge.skill`);await QR(n,r,RR[t]);let{size:i,sha256:a,skillVersion:o}=await tz(r,e.expectedSkillVersion,{bundle:t,sourceDir:n});return{outputPath:r,size:i,sha256:a,skillVersion:o}}const rz=[`.ok`,`skill-install-events.jsonl`];async function iz(e,t){let n=t?.homedir??(()=>process.env.HOME??``),r=t?.warn??((e,t)=>{F(`skills`).warn(e,t)}),i=n();if(!i){r({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let a=I(i,...rz),o=`${JSON.stringify(e)}\n`;try{await Za(Rc(a),{recursive:!0})}catch(e){r({event:`skill-install-events.mkdir-failed`,err:e},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await Ja(a,o,{flag:`a`,encoding:`utf-8`})}catch(e){r({event:`skill-install-events.append-failed`,err:e},`[skill-install-events] append failed; telemetry skipped`)}}const az=Kl(nl);function oz(e){return I(e,...gi)}async function sz(e,t){let n=oz(e);await Za(Rc(n),{recursive:!0});try{return await ro(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const cz={warn:(e,t)=>F(`skills`).warn(e,t)};async function lz(e,t=cz){let n=oz(e),r;try{r=await az(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,HE.parseDocument)(r);if(i.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:n,errors:i.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let a=wi.safeParse(i.toJSON());if(!a.success){let e=a.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:n,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:n,issues:a.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return a.data}async function uz(e,t){let n=wi.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid skill-state: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=oz(e);await Za(Rc(r),{recursive:!0});let i=(0,HE.parseDocument)(``);i.contents=i.createNode(n.data),await Wa(r,i.toString(),{fs:Ya})}async function dz(e,t,n){let r=await lz(e,n);return r===null?null:r.targets[t]?.version??null}async function fz(e,t,n){let r=await lz(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function pz(e,t,n,r,i){if(!yn.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await sz(e,async()=>{let a=await lz(e,i)??Et(),o=new Date().toISOString(),s=a.targets[t],c=r===void 0?s?.surface??void 0:r,l=c===void 0?{version:n,recordedAt:o}:{version:n,recordedAt:o,surface:c};await uz(e,{...a,targets:{...a.targets,[t]:l}})})}async function mz(e,t,n){let r=(await lz(e,n).catch(()=>null))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function hz(e,t,n,r){await sz(e,async()=>{let i=await lz(e,r)??Et();await uz(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function gz(){let e=await az(Ml(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function _z(e,t){let[n,r]=await Promise.all([gz(),vz(e,t)]);return{currentVersion:n,targets:r}}async function vz(e,t=cz){let n=null;try{n=await lz(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:oz(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=Ai.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const yz=`open-knowledge`,bz=[`.claude`,`.cursor`,`.agents`],xz=`skills@~1.5.0`;function Sz(e,t){return I(e,`.agents`,`skills`,t)}async function Cz(e,t){try{return(await El(Sz(e,t))).isDirectory()}catch{return!1}}function wz(e){return/\s/.test(e)?`"${e.replaceAll(`"`,`\\"`)}"`:e}function Tz(e,t,n,r,i,a){return new Promise(o=>{let s,c=a===`win32`,l=c?n.map(wz):n;try{s=e(t,l,NA({env:r,stdio:[`ignore`,`pipe`,`pipe`],...c?{shell:!0}:{}}))}catch(e){o({kind:`spawn-error`,stderr:``,error:e});return}let u=``,d=!1,f=e=>{d||(d=!0,clearTimeout(p),o(e))};s.stderr?.on(`data`,e=>{u+=typeof e==`string`?e:e.toString(`utf-8`)}),s.on(`error`,e=>{f({kind:`spawn-error`,stderr:u,error:e})}),s.on(`exit`,e=>{f(e===0?{kind:`ok`,exitCode:e,stderr:u}:{kind:`nonzero`,exitCode:e,stderr:u})});let p=setTimeout(()=>{try{s.kill(`SIGTERM`)}catch{}f({kind:`timeout`,stderr:u})},i)})}async function Ez(e){for(let t of bz)try{if((await El(I(e,t,`skills`,yz))).isDirectory())return!0}catch{}return!1}async function Dz(e,t,n,r,i,a){if(!await Ez(e))return;let o=await Tz(t,`npx`,[`-y`,xz,`remove`,`--agent`,`*`,`-g`,yz],n,r,a);o.kind!==`ok`&&i.warn({event:`skill-install.legacy-remove-failed`,reason:o.kind,exitCode:o.exitCode,stderr:o.stderr},"Legacy `open-knowledge` skill removal did not exit cleanly; continuing with install.")}async function Oz(e={}){let t=e.home??hl(),n=e.logger??{warn:(e,t)=>F(`skills`).warn(e,t),info:(e,t)=>F(`skills`).info(e,t)},r=e.spawn??Nc,i=e.timeoutMs??6e4,a=e.surface??`cli-npx-skills-add`,o=e.platform??process.platform,s=e.bundleId??`discovery`,c=RR[s],l=async(e,r,i)=>{await iz({ts:new Date().toISOString(),surface:a,target:`cli-hosts`,bundle:s,outcome:e,...r===void 0?{}:{version:r},...i===void 0?{}:{reason:i}},{homedir:()=>t,warn:n.warn})},u;try{u=await gz()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,err:e},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await l(`failed`,void 0,`version-read-failed`),`failed`}let d=await dz(t,`cli-hosts`,n).catch(e=>(n.warn({event:`skill-install.gate.read-failed`,err:e},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&d!==null&&d===u){if(await Cz(t,c))return n.info?.({event:`skill-install.skip-current`,version:u},`OpenKnowledge skill already installed at current version; skipping.`),await l(`skip-current`,u),`skip-current`;n.info?.({event:`skill-install.reinstall-missing`,version:u,path:Sz(t,c)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let f;try{f=JR(s,{checkDesktop:!1})}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,err:e},`Skill install aborted — bundled SKILL.md asset not found.`),await l(`failed`,u,`bundled-asset-missing`),`failed`}let p={...process.env,HOME:t};await Dz(t,r,p,i,n,o);let m=await Tz(r,`npx`,[`-y`,xz,`add`,f,`--agent`,`*`,`-g`,`-y`,`--copy`],p,i,o);if(m.kind===`ok`){try{await pz(t,`cli-hosts`,u,a,n)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,err:e},`Skill install succeeded but sidecar write failed.`),await l(`failed`,u,`sidecar-write-failed`),`failed`}return n.info?.({event:`skill-install.installed`,version:u},`OpenKnowledge skill installed to detected agent hosts.`),await l(`installed`,u),`installed`}return m.kind===`timeout`?(n.warn({event:`skill-install.failed`,reason:`timeout`,timeoutMs:i,stderr:m.stderr},`Skill install subprocess timed out. Run manually: npx ${xz} add ${f} --agent '*' -g -y --copy`),await l(`failed`,u,`timeout`),`failed`):m.kind===`spawn-error`?(n.warn({event:`skill-install.failed`,reason:`spawn-error`,err:m.error,stderr:m.stderr},`Skill install failed — \`npx\` unavailable or spawn errored. Run manually: npx ${xz} add ${f} --agent '*' -g -y --copy`),await l(`failed`,u,`spawn-error`),`failed`):(n.warn({event:`skill-install.failed`,reason:`nonzero-exit`,exitCode:m.exitCode,stderr:m.stderr},`Skill install subprocess exited non-zero. Run manually: npx ${xz} add ${f} --agent '*' -g -y --copy`),await l(`failed`,u,`nonzero-exit:${m.exitCode??`unknown`}`),`failed`)}function kz(e){return I(e,`Downloads`,`openknowledge.skill`)}function Az(e,t,n){let r=NA({detached:!0,stdio:`ignore`});try{return t===`darwin`?(n(`open`,[e],r).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],r).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],r).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function jz(e={}){let t=e.home??hl(),n=R(e.out??kz(t)),r=e.platformName??_l(),i=e.spawnFn??Nc,a=e.logger,o=async(e,n,r)=>{await iz({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...n===void 0?{}:{version:n},...r===void 0?{}:{reason:r}},{homedir:()=>t,warn:a?.warn})};if(!e.force){let e=null;try{e=await gz()}catch(e){a?.warn?.({event:`skill-install.gate.version-read-failed`,err:e},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let n=null,r=null;try{[n,r]=await Promise.all([dz(t,`claude-cowork`,a),fz(t,`claude-cowork`,a)])}catch(e){a?.warn?.({event:`skill-install.gate.read-failed`,err:e},`Could not read claude-cowork install-state; rebuilding.`)}if(n!==null&&n===e)return a?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await o(`skip-current`,e),{status:`skip-current`,skillVersion:e,...r===null?{}:{recordedAt:r}}}}try{await Za(Rc(n),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let s;try{s=await nz({outputPath:n,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let c={status:`built`,outputPath:s.outputPath,size:s.size,sha256:s.sha256,skillVersion:s.skillVersion};if(s.skillVersion)try{await pz(t,`claude-cowork`,s.skillVersion,`server-build-and-open`,a)}catch(e){a?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:s.skillVersion,err:e},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await o(`built`,s.skillVersion),c;let l=Az(s.outputPath,r,i);return l.ok?(await o(`installed`,s.skillVersion),{...c,status:`installed`}):(await o(`built`,s.skillVersion,`handoff-${l.reason}`),{...c,handoffError:{reason:l.reason,message:l.message}})}const Mz=F(`skill-management`),Nz=[`.ok`,`local`,`skill-management.json`];function Pz(e){return I(e,...Nz)}function Fz(e){let t=Pz(e);if(!z(t))return null;try{let e=JSON.parse(B(t,`utf-8`));if(e&&typeof e==`object`&&typeof e.manageEditorSkills==`boolean`){let t=e;return{version:typeof t.version==`number`?t.version:1,manageEditorSkills:t.manageEditorSkills,decidedAt:typeof t.decidedAt==`string`?t.decidedAt:void 0,surface:typeof t.surface==`string`?t.surface:void 0}}return Mz.warn({path:t},`skill-management marker malformed — treating as unset`),null}catch(e){return Mz.warn({err:e,path:t},`skill-management marker unreadable — treating as unset`),null}}async function Iz(e,t){let n={version:1,manageEditorSkills:t.manageEditorSkills,decidedAt:t.now??new Date().toISOString(),...t.surface?{surface:t.surface}:{}},r=Pz(e);await Za(Rc(r),{recursive:!0}),await Wa(r,`${JSON.stringify(n,null,2)}\n`,{fs:Ya})}function Lz(e,t=process.env){if(t.OK_RECLAIM_DISABLE===`1`)return!1;let n=t.OK_SKILL_MANAGE;return n===`1`||n===`true`?!0:n===`0`||n===`false`?!1:Fz(e)?.manageEditorSkills??!1}const Rz=`2.31.0`,zz=5e3;var Bz=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,n){super(iB(t),n),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},Vz=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,n,r,i,a){super(aB(t,n,r,i),a),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=n,this.resolvedPath=r,this.guidance=i}};function Hz(){let e=Wz(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of Yz(process.platform)){if(!z(e))continue;let t=Wz(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new Bz(process.platform,Xz(process.platform))}function Uz(){let e=Hz();if(oB(e.version,`2.31.0`)<0)throw new Vz(process.platform,e.version,Rz,e.resolvedPath,Xz(process.platform));return e}function Wz(e){let t=Pc(e,[`--version`],NA({encoding:`utf-8`,timeout:zz,env:{...process.env,LANG:`C`,LC_ALL:`C`}}));if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let n=Gz(typeof t.stdout==`string`?t.stdout:``);return n===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:n,resolvedPath:e===`git`?Jz(`git`)??e:e}}function Gz(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const Kz=/^[a-zA-Z0-9_.-]+$/,qz=new Map;function Jz(e){if(!Kz.test(e))return null;let t=qz.get(e);if(t!==void 0)return t;let n;if(process.platform===`win32`){let t=Pc(`where`,[e],NA({encoding:`utf-8`,timeout:zz}));n=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=Pc(`/bin/sh`,[`-c`,`command -v ${e}`],NA({encoding:`utf-8`,timeout:zz}));n=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return n!==null&&qz.set(e,n),n}function Yz(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,I(hl(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,I(hl(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function Xz(e){switch(e){case`darwin`:{let e=[];return eB()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return tB()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),nB()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),rB()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:Zz()}}}function Zz(){switch(Qz()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function Qz(e){let t=e;if(t===void 0)try{t=B(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let n=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return n.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:n.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:n.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:n.some(e=>/^opensuse/i.test(e))||n.includes(`suse`)?`opensuse`:n.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function $z(e){return Jz(e)!==null}function eB(){return $z(`brew`)}function tB(){return $z(`winget`)}function nB(){return $z(`scoop`)}function rB(){return $z(`choco`)}function iB(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let n of e.options){let e=n.requiresAdmin?` (admin required)`:``;t.push(` • ${n.label}${e}`),t.push(` ${n.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
101
101
  `)}function aB(e,t,n,r){let i=[];if(i.push(`OpenKnowledge requires ${r.product} ${t} or newer (detected ${e} at ${n}).`),i.push(``),r.options.length>0){i.push(`Update ${r.product}:`);for(let e of r.options){let t=e.requiresAdmin?` (admin required)`:``;i.push(` • ${e.label}${t}`),i.push(` ${e.command}`)}i.push(``)}return i.push(`Or download from: ${r.url}`),i.push(``),i.push(`After updating, re-run OpenKnowledge.`),i.push("Run `ok diagnose health --check git` to verify your installation."),i.join(`
@@ -1223,7 +1223,7 @@ tags: [lore, history]
1223
1223
  `),i=n.nextFenced+(r?`
1224
1224
  `:``)+t;Px(b.dc.document,i,`agent`,void 0,S),RS(`mcp-write`),ne=!0}te=!0},b.origin)})}finally{gt?.touchMode(l,`idle`)}if(ee){let e;switch(ee.kind){case`invalid_value`:e={[ee.key]:ee.reason};break;case`reserved_key`:e={[ee.key]:`'${ee.key}' is reserved`};break;case`unknown_key`:e={[ee.key]:`'${ee.key}' is not a recognized key`};break;case`duplicate_target`:e={[ee.key]:`'${ee.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${ee.expected.join(`, `)}; got: ${ee.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${ee.bytes} > ${ee.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${ee.reason}`};break;case`invalid_path`:e={[ee.path.map(String).join(`.`)||`__path__`]:ee.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(ee)})`}}W(o,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(te&&re.length>0){if(GD(c,l,u,d,void 0,_i({clientName:f,clientVersion:p,label:m}),y),Gx(),Ai(_),ne){let e=await vr(c);if(e?.kind===`failure`){br(o,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){xr(o,`frontmatter-patch`);return}}ur(c,`frontmatter-patch`)}ht?.setFocus(l,{agentName:u,currentDoc:c,writeKind:`write`,ts:Date.now()}),vt?.();let ie=rr(c),ae=ir();ae===0&&DK().add(1,{"shadow.writer":`agent`,"agent.type":lh(f)});let w=Cr(x);kr(c,b.dc.document.getText(`source`).toString());let oe=Dr();oe.add(c);let se=GV(b.dc.document.getText(`source`).toString(),c,oe,Or);K(o,200,ze,{timestamp:C,subscriberCount:ie,systemSubscriberCount:ae,appliedKeys:re,...v?{summary:v}:{},...w?{warning:w,warnings:[w]}:{},brokenLinks:se},{handler:`frontmatter-patch`})}catch(e){if(e instanceof mC){W(o,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}J.error({err:e,requestId:xS(a)},`[frontmatter-patch] handler failed`),W(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Wi(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 Gi=q(tt,async(e,n)=>{try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!Zq(r)){W(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let a=$n(r);if(tS(a)||nS(a)){W(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){K(n,200,ct,{docName:a,content:o.getText(`source`).toString(),lifecycle:Wi(o)},{handler:`document-read`});return}if(!z(wq(i,`file`,a))){W(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){W(n,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}K(n,200,ct,{docName:a,content:e.getText(`source`).toString(),lifecycle:Wi(e)},{handler:`document-read`})}finally{await s.disconnect()}}catch(e){W(n,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Ki=q(tt,async(e,t)=>{try{Xt&&await Xt.catch(e=>{J.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=n.searchParams.get(`dir`),a=n.searchParams.get(`showAll`)===`true`,o=n.searchParams.get(`showOk`)===`true`,s=n.searchParams.get(`depth`)===`1`?1:1/0;if(r)try{iq(i,r)}catch{W(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&Gt&&mq(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=ES(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=sq(),n=hq({contentDir:i,contentFilter:Gt,dirFilter:r,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await a(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&J.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):J.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&Gt){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${r??``}`,n=vn.get(e);if(!n){let t=new AbortController,a=(async()=>{let e=[],n=sq(),{truncated:a}=await gq({contentDir:i,contentFilter:Gt,dirFilter:r,documents:e,maxEntries:n,maxDepth:s,showOk:o,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&&J.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 c=n;vn.set(e,c),a.finally(()=>{vn.get(e)===c&&vn.delete(e)})}let a=n;a.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),vn.get(e)===a&&vn.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await a.promise;if(c)return;K(t,200,ie,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;W(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}let l=c(),u=m(),d=te?.()??new Map,f=[];for(let[e,t]of d)r&&!e.startsWith(`${r}/`)&&e!==r||f.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let p=[];try{let e=In(l);bn?.signature!==e&&(bn={signature:e,assets:tN({contentDir:i,fileIndex:l,readMarkdown:e=>{try{return B(e,`utf-8`)}catch{return null}},isExcluded:Gt?e=>Gt.isPathIgnored(e):void 0})}),p=bn?.assets??[]}catch(e){bn=null,J.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let h=new Set;for(let e of p)r&&!e.path.startsWith(`${r}/`)&&e.path!==r||(h.add(e.path),f.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of u){if(t.kind===`markdown`){if(r&&!e.startsWith(`${r}/`)&&e!==r)continue;let n=gS(e);f.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(r&&!a.startsWith(`${r}/`)&&a!==r)continue;let o=Sk(L(i,t.canonicalPath));f.push({kind:`document`,docName:a,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o})}continue}if((!r||e===r||e.startsWith(`${r}/`))&&!h.has(e)){let n=aq(e);f.push({kind:`file`,docName:e,path:e,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let n of t.aliases){if(!(!r||n===r||n.startsWith(`${r}/`))||h.has(n))continue;let a=Sk(L(i,t.canonicalPath)),o=aq(n);f.push({kind:`file`,docName:n,path:n,docExt:`.${o}`,assetExt:o,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}let g=de?.()??new Map;if(g.size>0){let e=e=>!r||e===r||e.startsWith(`${r}/`),t=new Map;for(let[e,n]of g){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,r]of t){let t=d.get(n),a=t?Sk(L(i,t.canonicalPath)):n;for(let i of r)e(i)&&f.push({kind:`folder`,path:i,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 d)n(e,n=>{f.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:Sk(L(i,t.canonicalPath))})});for(let[e,t]of u)n(e,n=>{let r=Sk(L(i,t.canonicalPath));if(t.kind===`markdown`)f.push({kind:`document`,docName:n,docExt:gS(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=aq(n);f.push({kind:`file`,docName:n,path:n,docExt:`.${i}`,assetExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r})}})}f.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),K(t,200,ie,{documents:f},{handler:`document-list`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Xi=q(tt,async(e,t)=>{if(!nt){W(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){W(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!Zq(n)){W(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}K(t,200,le,{docName:n,backlinks:nt.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:qn(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Zi=q(tt,async(e,t)=>{if(!nt){W(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){W(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||!Zq(t)||(r[t]=nt.getBacklinkCount(t))}K(t,200,jt,{counts:r},{handler:`backlink-counts`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Qi=q(tt,async(e,t)=>{if(!nt){W(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){W(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!Zq(n)){W(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=Dr();K(t,200,mr,{docName:n,forwardLinks:nt.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Jn(e.target,r),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){W(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}),ea=q(tt,async(e,t)=>{if(!nt){W(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&&!Zq(r)){W(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){W(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){W(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:a,links:o}=nt.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=nt.getLinkGraph());let s=Dr();K(t,200,f,{nodes:a.map(e=>{if(e.kind===`doc`){let t=Zn(e.docName,s);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Jn(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){W(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}),ta=q(tt,async(e,t)=>{if(!nt){W(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(!Pr(n)){W(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}K(t,200,Vr,{orphans:nt.getOrphans([...c().keys()],n).map(e=>({docName:e,title:qn(e)}))},{handler:`orphans`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),ra=q(tt,async(e,t)=>{if(!nt){W(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=Dr();K(t,200,Bn,{hubs:nt.getHubs(i).map(e=>({docName:e.docName,title:Jn(e.docName,a),count:e.count}))},{handler:`hubs`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ia=q(tt,async(e,t)=>{if(!nt){W(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||!Zq(e))){W(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>$n(e)))]:void 0;K(t,200,Pn,{deadLinks:nt.getDeadLinks(Dr(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:qn(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){W(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}),aa=q(pt,async(r,a,o)=>{try{let{find:r,replace:s,offset:c}=o,l=Sq(o.docName,a,`agent-patch`);if(l===null)return;let u=$n(l),{agentId:d,agentName:f,colorSeed:p,clientName:m,clientVersion:h,label:g}=gi(o);if(AK(r)){kK().add(1,{result:`rejected`}),W(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(tS(u)||nS(u)){W(a,400,`urn:ok:error:reserved-doc-name`,`'${u}' is a reserved document name.`,{handler:`agent-patch`});return}let _=tD(o.summary),v=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),y=uk(t,u,i,e.resolveEmbed),b=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:u}:void 0,x;{let{frontmatter:e,body:t}=en(v.dc.document.getText(`source`).toString()),n=Ne(e,t),i=c==null?n.indexOf(r):n.slice(c,c+r.length)===r?c:-1;if(i!==-1&&i>=e.length){let e=n.slice(0,i)+s+n.slice(i+r.length);x=await lC(v.dc.document,en(e).body,`patch`,b)}}let S=new Date().toISOString(),C=!1,ee=!1,te=!1,ne;try{let e=jn(m),t=Tn[e]??gr(p??d);if(gt?.setPresence(d,{displayName:f,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),YE(v.dc.document.getText(`source`),d,p,m),v.dc.document.transact(()=>{let{frontmatter:e,body:t}=en(v.dc.document.getText(`source`).toString()),n=Ne(e,t),i=c==null?n.indexOf(r):n.slice(c,c+r.length)===r?c:-1;if(i===-1){c==null?C=!0:ee=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":u,findLength:r.length,replaceLength:s.length,hadOffset:c!=null})),Vne();return}if(i<e.length){te=!0;return}let{body:a}=en(n.slice(0,i)+s+n.slice(i+r.length)),o=dC(v.dc.document);ne=uC(v.dc.document,a,`patch`,b,x);let l=zt(o,dC(v.dc.document))??void 0;v.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Patched (${f}): ${r.slice(0,50)}`,...l===void 0?{}:{changedBlocks:l}})},v.origin),ne!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":u,position:`patch`,intendedBytes:ne.intendedBytes,actualBytes:ne.actualBytes,byteDelta:ne.byteDelta,"agent.id":d,"agent.client_name":m})),!C&&!ee&&!te){let{stored:e}=wi(_);GD(u,d,f,p,void 0,_i({clientName:m,clientVersion:h,label:g}),e),Gx(),Ai(_),VK(`agent-patch`,ne)}}finally{gt?.touchMode(d,`idle`)}if(ee){W(a,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(C){W(a,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(te){kK().add(1,{result:`rejected`}),W(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 re=await vr(u);if(re?.kind===`failure`){br(a,re.failure,`agent-patch`);return}if(re?.kind===`divergence`){xr(a,`agent-patch`);return}ur(u,`agent-patch`),ht?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`edit`,ts:Date.now()}),vt?.();let ie=rr(u),ae=ir();ae===0&&DK().add(1,{"shadow.writer":`agent`,"agent.type":lh(m)});let{response:w}=wi(_),oe=v.dc.document.getText(`source`).toString();kr(u,oe);let se=await eR(oe,u),ce=Dr();ce.add(u);let le=GV(oe,u,ce,Or),ue=Cr(y),de=ne===void 0?void 0:NS(ne),fe=[...de?[de]:[],...ue?[ue]:[],...se??[],...await qc(v.dc.document.getText(`source`).toString(),u)];K(a,200,he,{timestamp:S,subscriberCount:ie,systemSubscriberCount:ae,...w?{summary:w}:{},...de?{warning:de}:ue?{warning:ue}:{},...fe.length>0?{warnings:fe}:{},brokenLinks:le},{handler:`agent-patch`})}catch(e){if(e instanceof kS){AS(a,e,`agent-patch`);return}if(e instanceof PS){IS(a,e,`agent-patch`);return}if(e instanceof mC){W(a,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}J.error({err:e,requestId:xS(r)},`[agent-patch] handler failed`),W(a,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),oa=q(Ae,async(t,r,i)=>{try{let t=Sq(i.docName,r,`agent-undo`);if(t===null)return;let a=$n(t),{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=gi(i);if(tS(a)||nS(a)){W(r,400,`urn:ok:error:reserved-doc-name`,`'${a}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=i,p,m;if(i.scope===`count`?(p=`count`,m=i.count):p=i.scope===`session`||i.scope===`file`?`session`:`last`,!n.hasSession(a,f)){W(r,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let h=await n.getSession(a,f),g=!1;try{let t=jn(l),n=Tn[t]??gr(c??o);gt?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:a,mode:`writing`,ts:Date.now()}),g=kre(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:a}:void 0,m),g&&GD(a,f,s,c,void 0,_i({clientName:l,clientVersion:u,label:d}))}finally{gt?.touchMode(o,`idle`)}if(g){let e=await vr(a);if(e?.kind===`failure`){br(r,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){xr(r,`agent-undo`);return}ar(a,`agent-undo`)}ht?.setFocus(f,{agentName:f,currentDoc:a,writeKind:`undo`,ts:Date.now()}),K(r,200,We,{docName:a,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof kS){AS(r,e,`agent-undo`);return}J.error({err:e,requestId:xS(t)},`[agent-undo] handler failed`),W(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),sa=q(tt,async(e,t)=>{try{let r=oh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(r===null){W(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}K(t,200,we,lie(n,r),{handler:`agent-activity`})}catch(n){J.error({err:n,requestId:xS(e)},`[agent-activity] handler failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),ca=q(tt,async(e,t)=>{try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=oh(r.searchParams.get(`agentId`)),a=r.searchParams.get(`docName`),o=r.searchParams.get(`keptCount`);if(i===null){W(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!a||a.trim()===``){W(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!Zq(a)){W(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=$n(a);if(tS(s)||nS(s)){W(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))){W(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(o);if(!Number.isInteger(c)||c<0){W(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=n.getLiveSession(s,i);if(!l){W(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){W(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let d=l.dc.document.getText(`source`),{diff:f,before:p,after:m}=$E(u.undoStack,c,d,s);K(t,200,Ft,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){J.error({err:n,requestId:xS(e)},`[agent-burst-diff] handler failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:n})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),la=q(tt,async(e,t)=>{try{await xe?.(),K(t,200,aee,{},{handler:`test-flush-git`})}catch(n){J.error({err:n,requestId:xS(e)},`[test-flush-git] flush failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:n})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),k=q(tt,async(e,r)=>{try{let a=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),o=$n(a.searchParams.get(`docName`)??`test-doc`),s;try{s=wM(o,i)}catch(e){J.error({err:e,docName:o},`[test-reset] safeContentPath rejected docName`),W(r,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(Jt??t.unloadDocument.bind(t))(l),fl(s,``,`utf-8`),nt&&(nt.deleteDocument(o),nt.saveToDisk().catch(e=>{J.warn({docName:o,err:e},`[backlinks] Failed to persist cache after test-reset for ${o}`)}),ut?.(`backlinks`),ut?.(`graph`)),a.searchParams.get(`reset-okignore`)!==`false`)try{let e=R(i,`.okignore`),n=t.documents.get(bi);if(n){let e=n.getText(`source`);e.length>0&&n.transact(()=>{e.delete(0,e.length)},MD)}z(e)&&fl(e,``,`utf-8`),Gt&&await Gt.rebuildIgnorePatterns()}catch(e){J.warn({err:e},`[test-reset] okignore reset partial failure`)}ut?.(`files`),K(r,200,see,{},{handler:`test-reset`})}catch(e){W(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),A=q(tt,async(e,t)=>{try{if(!nt){W(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await nt.rebuildFromDisk(),await nt.ingestGlobalSkillBundles([R(ws,`.ok`,`skills`)]),nt.saveToDisk().catch(e=>{J.warn({err:e},`[backlinks] Failed to persist cache after test-rescan-backlinks`)}),ut?.(`backlinks`),ut?.(`graph`),K(t,200,_t,{},{handler:`test-rescan-backlinks`})}catch(e){W(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}),ua=q(tt,async(e,t)=>{try{if(!fe){W(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await fe(),ut?.(`files`),K(t,200,a,{},{handler:`test-rescan-files`})}catch(e){W(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}),da=q(Oi,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=gi(n),o=T?.current;if(!o){W(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){W(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=Ve?.()??`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 TO(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[BO],l=!0}let d=qe??`.`,f=tD(typeof n.summary==`string`?n.summary:void 0),p=await tk(o,d,c,u,f.kind===`value`?f.value:void 0,l?{includeUpstream:!1}:void 0);F(`history`).info({checkpointRef:p.checkpointRef},`checkpoint`);try{await _j(o,$A(o.gitDir))}catch(e){J.warn({err:e},`[rename-log] post-saveVersion GC failed`)}K(t,200,tee,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(n){J.error({err:n,requestId:xS(e)},`[save-version] handler failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),fa=q(tt,async(e,t)=>{let n=T?.current;if(!n){W(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}try{let e=performance.now();await xe?.();let t=performance.now()-e;t>1e3&&J.warn({durationMs:Math.round(t)},`[history] pre-read commit flush slow`)}catch(e){J.warn({err:e},`[history] pre-read commit flush failed`)}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`folder`),o=r.searchParams.get(`branch`)??Ve?.()??`main`;if(!i&&a===null){W(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)){W(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=ss(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}=yn.run(u,()=>CK(n,e.folderRel,qe??`.`,{branch:o,limit:s,offset:l}));f&&iK(`folder`),K(t,200,vi,{...await d},{handler:`history`});return}let s=qe??`.`,c=qK(i,s);if(`error`in c){W(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}=yn.run(_,()=>SK(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&iK(`doc`);let a=await e,c=Date.now()-v;F(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),K(t,200,vi,{...a},{handler:`history`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function pa(e,t,n){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=T?.current;if(!r){W(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=qe??`.`,o=qK(i,a);if(`error`in o){W(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=CO(r),c=Ve?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){W(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await Sj(r,i,n,c,$A(r.gitDir),e=>{let t=qK(e,a);return`error`in t?`${e}.md`:t.path},rj());if(e===null){W(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`);K(t,200,Pi,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let ma=q(Ct,async(n,r,i)=>{let a=rH(i,At);if(a.kind===`invalid-summary`){W(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=t.documents.get(i.docName);if(o&&DS(o)){AS(r,new kS({file:_S(i.docName)}),`rollback`);return}let s=T?.current;if(!s){W(r,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=i,u=qe??`.`,d=qK(c,u);if(`error`in d){W(r,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=CO(s),p=Date.now();try{let n=$A(s.gitDir),i=rj(),o=await Sj(s,c,l,Ve?.()??`main`,n,e=>{let t=qK(e,u);return`error`in t?`${e}.md`:t.path},i);if(o===null){W(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 GO(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=t.documents.get(c);if(!h){W(r,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let g=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:c}:void 0,_=await oC(d,g),v;h.transact(()=>{Fx(h,d,g,_),v=MS(h.getText(`source`).toString(),d,`rollback`)},WK),v!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:v.intendedBytes,actualBytes:v.actualBytes,byteDelta:v.byteDelta,"actor.kind":a.kind,...a.kind===`agent`||a.kind===`principal`?{"actor.writer_id":a.writerId}:{}})),VK(`rollback`,v);let y;switch(a.kind){case`agent`:{let e=l.slice(0,8),t=a.summary.kind===`value`,n=t?a.summary:tD(`Restored to ${e}`),r=wi(n);y=t||!r.response?r.response:Ei(r.response),GD(c,a.writerId,a.displayName,a.colorSeed,vu(c,l),a.actor,r.stored),Gx(),Ai(n,!t);break}case`principal`:{let e=wi(a.summary);y=e.response,GD(c,a.writerId,a.displayName,a.colorSeed,vu(c,l),a.actor,e.stored),Ai(a.summary,!1);break}case`anonymous`:J.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)}`)}MK().add(1,{kind:`rollback`,attribution_kind:a.kind});let b=await vr(c);if(b?.kind===`failure`){br(r,b.failure,`rollback`);return}if(b?.kind===`divergence`){xr(r,`rollback`);return}ar(c,`rollback`);let x=Date.now()-p;F(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),a.kind===`agent`&&ht?.setFocus(a.writerId,{agentName:a.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:NS(v);K(r,200,hee,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){W(r,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),ha=q(tt,async(e,t)=>{try{K(t,200,Pe,eS(),{handler:`metrics-reconciliation`})}catch(n){J.error({err:n,requestId:xS(e)},`[metrics-reconciliation] handler failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:n})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),ga=q(tt,async(e,t)=>{try{K(t,200,Gr,Wn(),{handler:`metrics-parse-health`})}catch(n){J.error({err:n,requestId:xS(e)},`[metrics-parse-health] handler failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:n})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),_a=q(tt,async(e,t)=>{try{Xt&&await Xt.catch(e=>{J.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=kM(),n=Ke?.(),r=nH();K(t,200,eee,{serverInstanceId:o,currentBranch:e,...n===void 0?{}:{currentDiskAckSVs:n},...r===void 0?{}:{boot:r}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),va=O({agents:D(O({id:M(),name:M(),version:M(),description:M().optional(),license:M().optional(),iconUrl:M().optional(),website:M().optional(),source:Ji([`registry`,`custom`]),supported:E(),featured:E(),harness:O({cli:Ji([`claude`,`codex`,`cursor`,`opencode`,`pi`]),availability:Ji([`present`,`not-found`,`unknown`])}).optional()})),stale:E(),maxThreads:j()}),N=q(tt,async(e,t)=>{if(Pt===void 0){W(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=Ou(),{agents:n,stale:r}=await Pt.getCatalog(),i=await Rt?.()??[],a=await Wt();K(t,200,va,{agents:[...n.map(t=>{let n=UE[t.id];return{id:t.id,name:t.name,version:t.version,...t.description===void 0?{}:{description:t.description},...t.license===void 0?{}:{license:t.license},...t.icon===void 0?{}:{iconUrl:t.icon},...t.website===void 0?{}:{website:t.website},source:`registry`,supported:t.distribution.npx!==void 0||t.distribution.uvx!==void 0||e!==null&&t.distribution.binary?.[e]!==void 0,featured:Tu.includes(t.id),...n===void 0?{}:{harness:{cli:n,availability:a[n]??`unknown`}}}}),...i.map(e=>({id:e.id,name:e.name,version:`custom`,source:`custom`,supported:!0,featured:!1}))],stale:r,maxThreads:8},{handler:`acp-catalog`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function ya(e,t){if(!yW(e.socket.remoteAddress)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=At?.()??null;if(!n){W(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}K(t,200,xn,n,{handler:`principal`})}async function ba(e,t){if(!yW(e.socket.remoteAddress)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=gt?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);K(t,200,Re,{presence:r},{handler:`metrics-agent-presence`})}catch(n){J.error({err:n,requestId:xS(e)},`[metrics-agent-presence] handler failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:n})}}async function xa(e,n){if(!yW(e.socket.remoteAddress)){W(n,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!bW(e.headers.host)){W(n,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-effects`});return}if(e.method!==`GET`){W(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-effects`,extraHeaders:{Allow:`GET`}});return}let r;try{let e=[];for(let[n,i]of t.documents){if(tS(n)||nS(n)||!i.share.has(`agent-effects`))continue;r=n;let t=i.getMap(`agent-effects`);if(t.size===0)continue;let a=[...t.values()].map(e=>{let t=0,n=0;for(let r of e.delta)typeof r.insert==`string`?t+=r.insert.length:r.insert!==void 0&&(t+=1),typeof r.delete==`number`&&(n+=r.delete);return{sessionId:e.sessionId,agentType:e.agent_type,ts:e.timestamp,insertedChars:t,deletedChars:n}}).sort((e,t)=>e.ts-t.ts);e.push({"doc.name":n,entries:a})}e.sort((e,t)=>e[`doc.name`].localeCompare(t[`doc.name`])),K(n,200,ve,{effects:e},{handler:`metrics-agent-effects`})}catch(e){J.error({err:e,"doc.name":r},`[metrics-agent-effects] handler failed`),W(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-effects`,cause:e})}}async function Sa(e,t){if(!yW(e.socket.remoteAddress)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-watcher-recent`});return}if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-watcher-recent`,extraHeaders:{Allow:`GET`}});return}try{K(t,200,iee,{decisions:zk().map(e=>({ts:e.ts,decision:e.decision,kind:e.kind,"doc.name":e.path,pathRole:e.pathRole}))},{handler:`metrics-watcher-recent`})}catch(n){J.error({err:n,requestId:xS(e)},`[metrics-watcher-recent] handler failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-watcher-recent`,cause:n})}}async function Ca(e,t){if(!yW(e.socket.remoteAddress)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=aF.read();K(t,200,mee,{entries:n,count:n.length,detection:pae(n[0])},{handler:`embed-detect`})}async function wa(e,t){if(!yW(e.socket.remoteAddress)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=R(i),r=n,a=!0;try{r=ol(n)}catch(e){let r=Xo(e);if(r===`ENOENT`)J.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),a=!1;else{J.warn({path:n,err:e},`[workspace] realpath failed for contentDir`),W(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}K(t,200,S,{contentDir:r,pathSeparator:Uc,symlinkResolved:a},{handler:`workspace`})}let Ta=q(tt,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){W(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let r=nN(n),a=zc(n).slice(1).toLowerCase();if(!r||!Bi.has(a)){W(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let o=ol(i),s=R(o,n),c;try{c=ol(s)}catch{W(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!TM(c,o)){W(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let l;try{l=ul(c)}catch{W(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!l.isFile()){W(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let u=eN(o,c);if(u!==n.split(`\\`).join(`/`)){W(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(Gt?.isPathIgnored(u)){W(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let d=Ma.has(a),f={"Content-Type":r,"Content-Length":String(l.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":qi.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`]=$i),t.writeHead(200,f);try{await Wl(Xc(c),t)}catch(e){J.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){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Ea=1048576,P=q(tt,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){W(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let r=ol(i),a=R(r,n),o;try{o=ol(a)}catch(e){W(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!TM(o,r)){W(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let s;try{s=ul(o)}catch(e){W(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!s.isFile()){W(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(eN(r,o)!==n.split(`\\`).join(`/`)){W(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(s.size>Ea){W(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ea}-byte text-viewer cap.`,{handler:`asset-text`});return}let c=(await Cl(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){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Da=q(tt,async(e,t)=>{try{if(!T?.current){K(t,200,Cn,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=R(T.current.gitDir,`rescue`);if(z(r))try{let t=il(r).filter(e=>lS(e));for(let i of t){let t=R(r,i),a=ul(t);if(e-a.mtimeMs>864e5){try{dl(t)}catch(e){J.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:dS(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){J.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=Ve?.()??`main`,t=await JO(T.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){J.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}K(t,200,Cn,n,{handler:`rescue-list`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),ka=q(re,async(e,t,n)=>{try{let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let r=n.path;if(!lS(r)){W(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(r.includes(`..`)||r.startsWith(`/`)||r.includes(`\0`)||r.includes(`\\`)){W(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let a=R(i),o=R(a,r);if(!Ck(o,a)){W(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let s=dS(r);if(tS(s)||nS(s)){W(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`create-page`});return}if(vq(r)||$e(s)){W(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let c=typeof n.template==`string`?n.template.trim():``,l=``,u;if(c.length>0){if(!/^[A-Za-z0-9_-]+$/.test(c)){W(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let n=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)):``,i=sP(a,n),o=i.find(e=>e.name===c);if(!o){let e=i.length===0?`(none)`:i.map(e=>`"${e.name}" (${e.scope})`).join(`, `);W(t,400,`urn:ok:error:invalid-request`,`Template "${c}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let s=R(a,o.path),d;try{d=B(s,`utf-8`)}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=Hn(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;l=YP(f,{date:ZP(),user:p}),u=o.scope}$c(Rc(o),{recursive:!0});try{fl(o,l,{encoding:`utf-8`,flag:`wx`})}catch(e){if(kq(e)){W(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let d=dS(r);switch(Zt?.delete(d),Gt&&Gt.incrementMdDir(Rc(d)),Ak(o,Mk(l)),e.kind){case`agent`:case`principal`:GD(d,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}y?.({kind:`create`,path:o,docName:d,content:l}),nt&&(nt.updateDocumentFromMarkdown(d,l),nt.saveToDisk().catch(e=>{J.warn({docName:d,err:e},`[backlinks] Failed to persist create-page cache for ${d}`)}),ut?.(`backlinks`),ut?.(`graph`)),ut?.(`files`),u!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:c,templateScope:u,docName:d})),K(t,200,st,{docName:d},{handler:`create-page`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),Aa=q(ree,async(e,t,n)=>{try{if(rH(n,At).kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!_q(e)){W(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(vq(e)){W(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(Gt?.isDirExcluded(e)){W(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let r=wq(i,`folder`,e);if(z(r)){W(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}ao(r,{recursive:!0}),An(e),ut?.(`files`),K(t,200,ce,{path:e},{handler:`create-folder`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),ja=q(sr,async(e,n,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:a}=r,o=r.path,s=a===`file`?dS(o):o;if(!_q(o)){W(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(vq(o)||a===`file`&&(tS(s)||nS(s))||a===`folder`&&yq(o)){W(n,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}a===`file`&&Bq(i,o);let c=wq(i,a,o);if(!z(c)){if(a===`file`){let e=wq(i,`folder`,o);if(z(e)&&ul(e).isDirectory()){W(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return}}W(n,404,`urn:ok:error:doc-not-found`,`${a} does not exist.`,{handler:`duplicate-path`});return}let l=ul(c);if(a===`file`&&!l.isFile()||a===`folder`&&!l.isDirectory()){W(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${a}.`,{handler:`duplicate-path`});return}let u=a===`file`?[Pq(i,o)]:ui(wq(i,`folder`,o)),d=bt?.(),f=new Set(d?d.getConflicts().map(e=>e.file):[]);for(let e of u){let r=e,i=t.documents.get(r),a=_S(r),o=i!==void 0&&DS(i),s=f.has(a);if(o||s){AS(n,new kS({file:a}),`duplicate-path`);return}}let p,m=[];if(a===`file`){let e=zc(c);if(p=Iq(i,s).docName,tS(p)||nS(p)||Gt?.isExcluded(`${p}${e}`)){W(n,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let t=Fq(i,p,e),r=B(c,`utf-8`),a=Rc(t),o=z(a);try{ao(a,{recursive:!0}),ho(t,r,{encoding:`utf-8`,flag:`wx`})}catch(e){if(kq(e)){W(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{oo(a)}catch(e){let t=Xo(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&J.warn({destinationDir:a,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let l=!1;try{hS(p,e),Zt?.delete(p),Gt&&(Gt.incrementMdDir(Rc(p)),l=!0),Ak(t,Mk(r)),y?.({kind:`create`,path:t,docName:p,content:r}),nt?.updateDocumentFromMarkdown(p,r),m=[p]}catch(e){try{lo(t,{force:!0})}catch(e){J.warn({destinationPath:t,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw vS(p),Gt&&l&&Gt.decrementMdDir(Rc(p)),y?.({kind:`delete`,path:t,docName:p}),e}}else{if(p=Lq(i,o).folderPath,Gt?.isDirExcluded(p)){W(n,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=wq(i,`folder`,p);try{co(c,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(kq(e)){W(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 zq(i,p))An(e);let e=Rq(i,p);m=e.map(e=>e.docName);for(let t of e){let e=zc(t.fullPath);hS(dS(t.docName),e),Zt?.delete(t.docName),Gt&&Gt.incrementMdDir(Rc(t.docName)),Ak(t.fullPath,Mk(t.content)),y?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),nt?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{lo(e,{recursive:!0,force:!0})}catch(t){J.warn({destinationPath:e,err:t},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of m)GD(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)}`)}nt&&m.length>0&&(nt.saveToDisk().catch(e=>{J.warn({err:e},`[backlinks] Failed to persist duplicate-path cache`)}),ut?.(`backlinks`),ut?.(`graph`)),ut?.(`files`),K(n,200,Ye,{kind:a,path:p,duplicatedDocNames:m},{handler:`duplicate-path`})}catch(e){if(e instanceof Oq){W(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=Aq(e);if(t){W(n,t.status,t.type,t.title,{handler:`duplicate-path`,cause:e});return}W(n,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Ia=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){W(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!Zq(n)){W(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=Vn(n);if(!r){W(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!z(r)){W(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}K(t,200,ft,{docName:n,headings:Xq(B(r,`utf-8`))},{handler:`page-headings`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Ra=q(ke,async(e,n,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:a,fromPath:o,toPath:s}=r;if(!_q(o)||!_q(s)){W(n,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(a===`file`&&(tS(o)||tS(s)||nS(o)||nS(s))){W(n,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(vq(o)||vq(s)){W(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(o===s){K(n,200,Ue,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let c=a===`asset`&&lS(o)&&lS(s)?`file`:a;if(c===`asset`){let t;try{t=lS(o)&&!lS(s)?await pi(o,s):await fi(o,s)}catch(e){if(e instanceof kS){AS(n,e,`rename-path`);return}let{status:t,type:r,error:i}=zr(e);W(n,t,r,i,{handler:`rename-path`,cause:e});return}t.renamedAssets.length>0&&Rn();let r;if(t.renamedAssets.length>0&&t.rewrittenDocs.length>0){let n=`Renamed asset ${o} → ${s}`;r=ji(e,n,t.rewrittenDocs.map(({docName:e})=>({docName:e,subject:n})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{J.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(MK().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),De)try{await De()}catch(e){J.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}K(n,200,Ue,{renamed:[],renamedAssets:t.renamedAssets,rewrittenDocs:t.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}c===`file`&&Bq(i,o);let l=c===`file`?[Pq(i,o)]:ui(wq(i,`folder`,o)),u=bt?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of l){let r=e,i=t.documents.get(r),a=_S(r),o=i!==void 0&&DS(i),s=d.has(a);if(o||s){AS(n,new kS({file:a}),`rename-path`);return}}if(Gt){let e=lS(o)?zc(o):gS(o);if(c===`file`?Gt.isExcluded(lS(s)?s:`${s}${e}`):Gt.isDirExcluded(s)){W(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 hi(o,s,c,f?{actor:f}:{})}catch(e){if(e instanceof _I){W(n,409,`urn:ok:error:doc-already-exists`,Rr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(p.renamed.length===0&&p.renamedAssets.length===0){K(n,200,Ue,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&Rn();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=ji(e,`Renamed ${o} → ${s}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:yu(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{J.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)`)}})),MK().add(1,{kind:`rename-${c}`,attribution_kind:e.kind}),De)try{await De()}catch(e){J.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}K(n,200,Ue,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:t,type:r,error:i}=zr(e);W(n,t,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),za=q(pr,async(e,n,r)=>{try{gi(r);let{kind:e,path:a}=r;if(!_q(a)){W(n,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let o=e===`asset`?oi(a):{path:a,ambiguous:!1};if(o.ambiguous){W(n,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let s=o.path,c=e===`asset`&&lS(s)?`file`:e;if(c===`file`&&Bq(i,s),vq(s)){W(n,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let l=c===`asset`?wq(i,`folder`,s):wq(i,c,s);if(!z(l)){W(n,404,`urn:ok:error:doc-not-found`,`${c} does not exist.`,{handler:`delete-path`});return}let u=ul(l);if(c===`file`&&!u.isFile()||c===`asset`&&!u.isFile()||c===`folder`&&!u.isDirectory()){W(n,400,`urn:ok:error:invalid-request`,`Target path is not a ${c}.`,{handler:`delete-path`});return}let f=c===`asset`?[]:c===`file`?[Pq(i,s)]:ui(wq(i,`folder`,s)),p=bt?.(),m=new Set(p?p.getConflicts().map(e=>e.file):[]);for(let e of f){let r=e,i=t.documents.get(r),a=_S(r),o=i!==void 0&&DS(i),s=m.has(a);if(o||s){AS(n,new kS({file:a}),`delete-path`);return}}if(await Hr(f,`deleted-upstream`),Zt)for(let e of f)tS(e)||nS(e)||(Zt.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));c===`file`||c===`asset`?eo(l):(lo(l,{recursive:!0,force:!1}),Nn(s)),Rn();for(let e of f)y?.({kind:`delete`,path:R(i,_S(e)),docName:e});ut?.(`files`),K(n,200,d,{deletedDocNames:f},{handler:`delete-path`})}catch(e){W(n,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ba=q(g,async(e,t,n)=>qa(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":so(n.path),"ok.cleanup.path.role":po(n.path)}},async()=>{try{if(rH(n,At).kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:r}=n;if(!_q(r)){W(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let a=e===`asset`&&lS(r)?`file`:e,o=dS(r);a===`file`&&Bq(i,r);let s=a===`folder`&&yq(r);if(a===`file`&&(tS(o)||nS(o))||s||vq(r)){W(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(a===`asset`){Rn(),ut?.(`files`),K(t,200,Vt,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let l=c(),u=a===`file`?l.has(o)?[o]:[]:bq(l,a,r);if(Rn(),u.length===0){K(t,200,Vt,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Hr(u,`deleted-upstream`),Zt)for(let e of u)tS(e)||nS(e)||(Zt.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of u)y?.({kind:`delete`,path:R(i,_S(e)),docName:e});a===`folder`&&Nn(r),ut?.(`files`),K(t,200,Vt,{deletedDocNames:u},{handler:`trash-cleanup`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Va=q(tt,async(e,t)=>{try{let e=c(),n=[];for(let[t,r]of e){let e=gS(t),a,o;if(r.title!==void 0)a=r.title,o=r.icon;else{a=t;try{let n=B(R(i,`${t}${e}`),`utf-8`);a=_k(n,t),o=vk(n)}catch(e){J.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:a,docExt:e,size:r.size,modified:r.modified,icon:o})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),K(t,200,me,{pages:n},{handler:`pages`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),Ha=q(tt,async(e,n)=>{try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){W(n,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!Zq(r)){W(n,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(tS(r)||nS(r)){W(n,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`suggest-links`});return}K(n,200,Tr,await XG({hocuspocus:t,fileIndex:c(),docName:r}),{handler:`suggest-links`})}catch(e){if(e instanceof kG){W(n,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}W(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 Wa(e,t){if(e.method!==`POST`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let n;try{n=await rq(e,Et??i)}catch(e){if(e instanceof sV){W(t,cV(e.reason),e.reason,uV(e.reason),{handler:`upload-asset`,cause:e});return}W(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:r,tempPath:a,sha:o,byteLength:s,parentDocName:c,placement:u}=n,d=()=>{if(z(a))try{dl(a)}catch{}},f=NF(nee,{parentDocName:c,placement:u||void 0},t,{handler:`upload-asset`});if(!f.ok){d();return}let{parentDocName:p,placement:m}=f.value,{agentId:h,agentName:g}=gi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(s===0){d(),W(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(p.includes(`\0`)||p.includes(`..`)||p.startsWith(`/`)){d(),W(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let _=R(i),v;try{v=m===`parent-dir`?`./`:l?.()??`./`}catch(e){d(),J.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),W(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!Oa(v)){d(),W(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let y=QK(p,na(v),_);if(!TM(y,_)){d(),W(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{Cq(y,_)}catch(e){if(d(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){W(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}J.error({err:e,destDir:y},`[upload] failed to validate destination directory`),W(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{$c(y,{recursive:!0})}catch(e){if(!kq(e)){d();let n=lV(e);W(t,cV(n),n,uV(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=ol(y),n;try{n=ol(_)}catch{n=_}if(!TM(e,n)){d(),W(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(Xo(e)!==`ENOENT`){d(),W(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let b=$K(a,4100),x=await BE(b),S=x?.mime,C=x?.ext;if(!S){let e=b.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(S=`image/svg+xml`,C=`svg`)}{let n=await nq(y,o,s);if(n){d();let r=Sk(L(i,R(y,n)));J.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!0,mime:S??null,size:s,destPath:r,httpStatus:200},`[upload] dedup hit`),K(t,200,xi,{src:n,path:r,deduped:!0},{handler:`upload-asset`});return}}let ee;if(!r||r===`upload`||JK.test(r)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=r?zc(r).slice(1):``,n=C??t??``;ee=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else ee=ZK(r);try{let n=hV(a,y,ee),r=Sk(L(i,R(y,n)));J.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:h,agentName:g,dedup:!1,mime:S??null,size:s,destPath:r,httpStatus:200},`[upload] write ok`),K(t,200,xi,{src:n,path:r,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof sV?n.reason:`urn:ok:error:storage-error`;J.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:xS(e),agentId:h,agentName:g,filename:ee,size:s,reason:r,httpStatus:cV(r),err:n},`[upload] write failed`),W(t,cV(r),r,uV(r),{handler:`upload-asset`,cause:n})}}let Ga=`/api/local-op/clone`,Ka=`/api/local-op/ok-init`,Ja=600*1e3,Ya={stdio:[`ignore`,`ignore`,`pipe`]},Za={stdio:[`ignore`,`pipe`,`pipe`]},Qa={stdio:`ignore`},$a=`local-op-clone`,to=q(Mi,no,{handler:$a,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:$a})});async function no(e,t,n){let{url:r,dir:i,branch:a}=n;if(!RU(r)){W(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:$a,cause:Error(`url=${r}`)});return}if(!HU(i)){W(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:$a,cause:Error(`dir=${i}`)});return}if(!mn.tryAcquire(Ga)){W(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:$a,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let o=ES(t,$a),s=null,c=sW({cliArgs:St,url:r,dir:i,branch:a,timeoutMs:Ja,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&J.warn({stderr:NR(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=tW(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(NR(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await c.done,s&&!t.writableEnded&&!t.destroyed){let e=await ro(s);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:s})}\n`):o(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?o(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):J.error({err:e,handler:$a},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),mn.release(Ga)}})(),t.on(`close`,()=>{c.cancel()})}async function ro(e,t){let n=R(zU(e)),r=aN(n),i=iV(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=St,s=e=>{let n=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...o,e,...n]},c=async e=>{let t=Nc(a,s(e),NA({...Ya,cwd:n,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),i=[];t.stderr?.on(`data`,t=>{i.push(t),J.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,J.error({cwd:n,cliCmd:e,err:t},`[local-op/clone] failed to spawn child`)}),t.unref();let u=Date.now()+45e3;for(;Date.now()<u;){await Gl(500);let t=iV(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=Wo(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=Wo(r);if(e&&e.port>0){let e=await c(`ui`);return`port`in e?e:{error:`${d.error}; connect fallback failed: ${e.error}`}}}return`port`in d?d:{error:d.error}}let io=`local-op-ok-init`,uo=q(yr,async(e,t,n)=>{let{projectPath:r}=n;if(!Bc(r)){W(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:io,cause:Error(`projectPath=${r}`)});return}let i;try{i=ol(r)}catch(e){K(t,200,mi,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:io});return}if(!HU(i)){W(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:io,cause:Error(`projectPath=${r}`)});return}let a=tu(i).kind;if(a!==`directory`&&a!==`linked`){J.warn({project:Ic(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${Ic(i)} result=not-a-git-worktree kind=${a}`),K(t,200,mi,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:io});return}if(iH(i)){J.warn({project:Ic(i),result:`already-initialized`},`[ok-init] action=init project=${Ic(i)} result=already-initialized`),K(t,200,mi,{ok:!0,projectPath:i},{handler:io});return}if(!mn.tryAcquire(Ka)){W(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:io,extraHeaders:{"Retry-After":`2`}});return}try{await jo(async()=>{FH(i)}),J.warn({project:Ic(i),result:`success`},`[ok-init] action=init project=${Ic(i)} result=success`),K(t,200,mi,{ok:!0,projectPath:i},{handler:io})}catch(e){let n=e instanceof Error?e.message:String(e);J.warn({project:Ic(i),result:`failed`,reason:n},`[ok-init] action=init project=${Ic(i)} result=failed reason=${n}`),K(t,200,mi,{ok:!1,reason:`init-failed`,message:n},{handler:io})}finally{mn.release(Ka)}},{handler:io,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:io})}),fo=`/api/local-op/auth/status`,mo=`/api/local-op/auth/repos`,go=`/api/local-op/auth/signout`,_o=`/api/local-op/auth/pat`,vo=()=>hR(Et??i),Co={current:null},To={current:null};function Eo(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!mn.tryAcquire(r)){let e=i.current;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-flow-slot-no-controller`,channel:`auth`,transport:`http`,handler:n})),W(t,429,`urn:ok:error:concurrent-operation`,a,{handler:n,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),i.current=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`,handler:n}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let c=ES(t,n),l=s(e=>{if(e.type===`error`){c(500,`urn:ok:error:auth-failed`,o,{cause:e.message?Error(e.message):void 0});return}if(UK(e,bt),!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}});i.current=l;let u=()=>{l.cancel(),i.current===l&&(i.current=null,mn.release(r))};t.on(`close`,u),l.done.finally(()=>{if(t.off(`close`,u),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===l&&(i.current=null,mn.release(r))})}let Do=`local-op-auth-login`,ko=q(jr,Mo,{handler:Do,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Do})});async function Mo(e,t,n){let r=n.host??vo();Eo({res:t,handler:Do,guardKey:`/api/local-op/auth/login`,inFlight:Co,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>YU({cliArgs:St,host:r,timeoutMs:Ja,onEvent:e})})}let No=`local-op-auth-gh-login`,Po=q(jr,async(e,t,n)=>{let r=n.host??vo(),i=await hW();if(i===null){W(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:No});return}Eo({res:t,handler:No,guardKey:`/api/local-op/auth/gh-login`,inFlight:To,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>vW({host:r,ghPath:i,timeoutMs:Ja,onEvent:e})})},{handler:No,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:No})}),Fo=`local-op-auth-status`,Io=q(jr,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(fo)){W(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Fo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=St,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=Nc(e,i,NA({...Za,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(`
1225
1225
  `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}let s=await hW()!==null;o===null?K(t,200,Lr,{authenticated:!1,ghAvailable:s},{handler:Fo}):K(t,200,Lr,{...o,ghAvailable:s},{handler:Fo})}catch(e){W(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Fo,cause:e})}finally{mn.release(fo)}},{handler:Fo,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Fo})}),Lo=`local-op-auth-pat`,Ro=q(Qr,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(_o)){W(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:Lo,extraHeaders:{"Retry-After":`5`}});return}try{let e=await XU({cliArgs:St,host:r,token:n.token});e.ok?(HK(bt),K(t,200,nr,{host:e.host,login:e.login},{handler:Lo})):W(t,400,`urn:ok:error:auth-failed`,e.error,{handler:Lo})}catch(e){W(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:Lo,cause:e})}finally{mn.release(_o)}},{handler:Lo,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Lo})}),zo=`local-op-auth-repos`,Bo=q(jr,Vo,{handler:zo,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:zo})});async function Vo(e,t,n){let r=n.host??vo();if(!mn.tryAcquire(mo)){W(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:zo,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=ES(t,zo),[a,...o]=St,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=Nc(a,s,NA({...Za,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},Ja);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
1226
- `);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=>{J.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),mn.release(mo))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),mn.release(mo))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),mn.release(mo))})}let Ho=`local-op-auth-signout`,Uo=q(jr,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(go)){W(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Ho,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=St,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=Nc(e,i,NA({...Qa,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),K(t,200,li,{},{handler:Ho})}catch(e){W(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Ho,cause:e})}finally{mn.release(go)}},{handler:Ho,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Ho})}),Go=`/api/local-op/auth/set-identity`,Ko=`local-op-auth-set-identity`,qo=q(_n,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!Et){W(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ko});return}if(!mn.tryAcquire(Go)){W(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ko,extraHeaders:{"Retry-After":`5`}});return}try{SH(Et,r,i),bt?.()?.refreshIdentity().catch(()=>{}),K(t,200,li,{},{handler:Ko})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ko,cause:e})}finally{mn.release(Go)}},{handler:Ko,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Ko})});async function Jo(e,t){if(GU(e,t,{handler:`sync-status`})){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=bt?.();if(!e){K(t,200,Dt,{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(),K(t,200,Dt,e.getStatus(),{handler:`sync-status`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Yo=q(x,async(e,t,n)=>{let r=bt?.();if(!r){W(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;K(t,202,Si,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:`sync-trigger`})?bt?.()?!0:(W(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Zo(e,t){if(GU(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=bt?.();K(t,200,Ni,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Qo=q(Sn,async(e,t,n)=>{let r=bt?.();if(!r){W(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),K(t,200,Di,{},{handler:`sync-resolve-conflict`})}catch(e){W(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)=>GU(e,t,{handler:`sync-resolve-conflict`})?bt?.()?!0:(W(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function $o(e,n){if(!GU(e,n,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){W(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Et){W(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){W(n,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){W(n,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=dS(i),o=t.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=bt?.(),c=s?s.getConflicts().some(e=>e.file===i):!1;if(!o&&!c){W(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=Ao({baseDir:Et,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=dS(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=$t?$t(e):null;t!==null&&!KK(t)?u=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else J.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}K(n,200,fee,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:f},{handler:`sync-conflict-content`})}catch(e){W(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function es(e,t){if(!GU(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),r=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=rG(a);if(a!==null&&a!==``&&o===void 0){W(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{K(t,200,un,{plan:await yG({projectDir:i,rootDir:r,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof GW){W(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof KW){W(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}W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let ts=q(wr,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){W(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let a=r,o=n.packId,s=rG(o);if(typeof o==`string`&&o.length>0&&s===void 0){W(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${o}" is not registered.`});return}try{K(t,200,lee,{result:await mG(a,{projectDir:i,packId:s})},{handler:`seed-apply`})}catch(e){W(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)=>GU(e,t,{handler:`seed-apply`})});async function ns(e,t){if(GU(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}K(t,200,Gn,{packs:aG()},{handler:`seed-packs`})}}let rs=q(cee,async(e,t,n)=>{if(n.out!==void 0&&!HU(n.out)){W(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{K(t,200,Br,await jz({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){W(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)=>GU(e,t,{handler:`install-skill`})});async function is(e,t){if(GU(e,t,{handler:`installed-agents`}))try{await Wae(e,t,zn.probeAll)}catch(n){t.headersSent||(J.error({err:n,requestId:xS(e)},`[installed-agents] route wrapper failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let as=q(tt,async(e,t)=>{if(!it){W(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{K(t,200,on,{tags:it.getAllTags()},{handler:`tags-list`})}catch(e){W(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 os(e,t,n){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!it){W(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{W(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){W(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=it.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:qn(e),matchingTags:t,snippet:null}));K(t,200,Qt,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function ss(e,t,n=`path`,r=`folder-config`){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return W(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let o=R(i),s=a===``?o:R(o,a);return s!==o&&!s.startsWith(`${o}${Uc}`)?(W(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:a,resolvedContentDir:o}}let cs=/^[A-Za-z0-9_-]+$/;function ls(e,t,n=`template`){return!e||!cs.test(e)?(W(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function us(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:R(e,i);if(a!==e&&!a.startsWith(`${e}${Uc}`))continue;let o=R(a,`.ok`,`templates`,`${n}.md`);if(z(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function ds(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}let fs=wH({GET:q(tt,async(e,t)=>{try{let n=ss(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await OP(n.folderRel,{projectDir:n.resolvedContentDir}),i=R(R(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(z(i))try{let e=(0,HE.parse)(await Cl(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);J.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}K(t,200,yi,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Fi,async(e,t,n)=>{try{if(ln){W(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=ss(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=NP({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;W(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`&&(Li(e,Ii(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Ri(`folder-config-put`))}K(t,200,wn,{applied:i},{handler:`folder-config-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function ps(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&&DS(o)?(AS(i,new kS({file:`${a}.md`}),r),!0):!1}function ms(e,n,r){let i=t.documents.get(e);return i&&DS(i)?(AS(r,new kS({file:`${e}.md`}),n),!0):!1}let hs=q(tt,CH(async(e,t)=>{let n=cP(R(i));K(t,200,Ir,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),gs=e=>{let{body:t}=en(e);return{frontmatter:Qe(e)??{},body:t}},_s=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ls(r,t,`template-get`))return;let i=ss(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,c=us(o,a,r);if(!c){W(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:l,folder:u,scope:d}=c,f=sn(await Cl(l,`utf-8`)),p=f.identity,m=f.starterContent;K(t,200,s,{template:{name:r,folder:u,scope:d,path:L(o,l).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:p,body:m}},{handler:`template-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),vs=q(tr,async(e,t,r)=>{try{if(ln){W(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let i=r.name;if(!ls(i,t,`template-put`))return;let a=ss(r.folder,t,`folder`,`template-put`);if(!a||ps(a.folderRel,i,`template-put`,t))return;let o=$P({name:i,body:typeof r.body==`string`?r.body:``,frontmatter:ds(r.frontmatter)});if(!o.ok){W(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=R(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`),c=!z(s),l=L(a.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=As(a.folderRel,i),{agentId:d,agentName:f,colorSeed:p,clientName:m}=gi(r),h=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Px(h.dc.document,o.content,`agent`)},h.origin);let g=await vr(u);if(g?.kind===`failure`){br(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){xr(t,`template-put`);return}Li(e,Ii(`template`,a.folderRel,i),`${c?`template-create`:`template-edit`}: ${l}`),await Ri(`template-put`),K(t,200,gn,{path:l,created:c,warnings:o.warnings},{handler:`template-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),ys=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ls(r,t,`template-delete`))return;let i=ss(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=rH({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},At);if(o.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(ps(i.folderRel,r,`template-delete`,t))return;await Hr([As(i.folderRel,r)],`deleted-upstream`);let s=iae({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;W(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&&(Li(o,Ii(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Ri(`template-delete`)),K(t,200,yt,{existed:s.existed,path:s.path},{handler:`template-delete`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),bs=wH({GET:_s,PUT:vs,POST:q(Ar,async(e,t,n)=>{try{let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!ls(n.fromName,t,`template-move`)||!ls(n.toName,t,`template-move`))return;let r=ss(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=ss(n.toFolder,t,`folder`,`template-move`);if(!i||ps(r.folderRel,n.fromName,`template-move`,t))return;await Hr([As(r.folderRel,n.fromName)],`renamed`);let a=await aae({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await Jq(Et,e,t);return n||qq(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=us(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){W(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}W(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`){W(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;W(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=Hn(B(R(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=rae({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ds(n.frontmatter)});t.ok||(o=t.error)}}if(Li(e,Ii(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Ri(`template-move`),ut?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;W(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}K(t,200,Zr,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:ys},{handler:`template`}),xs=q(oee,async(e,r,a)=>{try{if(ln){W(r,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=rH(a,At);if(e.kind===`invalid-summary`){W(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let o=a.sourcePath;if(!Zq(o)){W(r,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let s=$n(o);if(tS(s)||nS(s)){W(r,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`template-import`});return}let c=wq(i,`file`,s);if(!z(c)){W(r,404,`urn:ok:error:doc-not-found`,`Source document not found: ${s}.`,{handler:`template-import`});return}let l=t.documents.get(s);if(a.deleteSource){let e=bt?.(),t=new Set(e?e.getConflicts().map(e=>e.file):[]),n=l!==void 0&&DS(l),i=t.has(o);if(n||i){AS(r,new kS({file:o}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await t.openDirectConnection(s);try{let t=e.document;if(!t){W(r,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=t.getText(`source`).toString()}finally{await e.disconnect()}}let d=a.name;if(!d){let{basename:e}=Tq(o);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!ls(d,r,`template-import`))return;let f=ss(a.targetFolder,r,`folder`,`template-import`);if(!f||ps(f.folderRel,d,`template-import`,r))return;let{frontmatter:p,body:m}=en(u),h=Yt(p),g={};try{h.trim()&&(g=(0,HE.parse)(h))}catch{}let _=a.title||g?.title||_k(u,d),v=g?.description||``,b=Array.isArray(g?.tags)?g.tags:[],x={...g};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,HE.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=$P({name:d,body:S,frontmatter:{title:_,description:v,tags:b}});if(!C.ok){W(r,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let ee=R(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),te=!z(ee),ne=L(f.resolvedContentDir,ee).split(/[\\/]/).filter(Boolean).join(`/`),re=As(f.folderRel,d),{agentId:ie,agentName:ae,colorSeed:w,clientName:oe}=gi(a),se=await n.getSession(re,ie,{displayName:ae,colorSeed:w,clientName:oe});se.dc.document.transact(()=>{Px(se.dc.document,C.content,`agent`)},se.origin);let ce=await vr(re);if(ce?.kind===`failure`){br(r,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){xr(r,`template-import`);return}Li(e,Ii(`template`,f.folderRel,d),`template-import: ${ne}`),a.deleteSource&&(await Hr([s],`deleted-upstream`),Zt&&Zt.setDeleted(s),eo(c),y?.({kind:`delete`,path:c,docName:s})),await Ri(`template-import`),ut?.(`files`),K(r,200,ci,{path:ne,created:te,warnings:C.warnings},{handler:`template-import`})}catch(e){W(r,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Ss(e,t,n){return!e||e.length>64||!ki.test(e)?(W(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 Cs(e,t,n){let r=v.safeParse(e??`project`);return r.success?r.data:(W(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let ws=Nt??hl();function Ts(e){return R(e===`global`?ws:i,`.ok`,`skills`)}let Es=RR.project;function Ds(){if(!Et)return null;let e=[],t=null;for(let n of Un){let r=Sr[n];if(!r)continue;let i=R(Et,...r.split(`/`),Es);z(R(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=R(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:L(Et,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Os(){let e=Ds();if(!e)return null;let t;try{let{frontmatter:n}=gs(B(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Es,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function ks(e,t,n){return BR(e)?(W(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 As(e,t){return`${dr}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function js(e){return e===`navigation`||e===`relevance`?e:void 0}function Ms(e,t){return L(t===`global`?ws:i,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Ns(e){return e===`global`?ws:Et}async function Ps(e,t){let n=await rI(e,t);return bB(t,e,Un),n!==null}function Fs(e,t){let n=[];if(!z(e))return{skills:n,truncated:!1};let r;try{r=il(e,{withFileTypes:!0})}catch(r){return F(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!ki.test(a.name))continue;if(n.length>=500){i=!0;break}let r=R(e,a.name,`SKILL.md`);if(!z(r))continue;let o,s;try{let{frontmatter:e}=gs(B(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:Ms(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Is=q(tt,CH(async(e,t)=>{let n=Fs(Ts(`project`),`project`),r=Fs(Ts(`global`),`global`),i=Et?eI(Et).skills:{},a=eI(ws).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=MB(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Es)?null:Os();K(t,200,Ie,{skills:[...o(n,i),...o(r,a),...s?[s]:[]],truncated:n.truncated||r.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Ls=O({managed:E().nullable(),importable:j().int().nonnegative()}),Rs=()=>({managed:Et?Fz(Et)?.manageEditorSkills??null:null,importable:Et?KB({projectDir:Et,skillsRoot:Ts(`project`)}):0}),zs=wH({GET:q(tt,async(e,t)=>{if(!Et){W(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}K(t,200,Ls,Rs(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:q(O({manageEditorSkills:E()}),async(e,t,n)=>{if(!Et){W(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await Iz(Et,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await qB({projectDir:Et,skillsRoot:Ts(`project`)});e.adopted.length+e.collided.length>0&&ut?.(`files`)}K(t,200,Ls,Rs(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),Bs=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`skill-get`))return;let i=Cs(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Es&&i===`project`){let e=Ds();if(e){let{frontmatter:n,body:a}=gs(await Cl(e.skillMd,`utf-8`));K(t,200,p,{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:wB(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Ts(i),o=R(a,r,`SKILL.md`);if(!z(o)){W(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}=gs(await Cl(o,`utf-8`));K(t,200,p,{skill:{name:r,scope:i,path:Ms(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:wB(R(a,r))}},{handler:`skill-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),Vs=q(je,async(e,t,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Ss(r.name,t,`skill-put`)||ks(r.name,t,`skill-put`))return;let i=BP({name:r.name,body:typeof r.body==`string`?r.body:``,frontmatter:{name:r.frontmatter.name,description:r.frontmatter.description}});if(!i.ok){W(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=Ts(r.scope),o=R(a,r.name,`SKILL.md`),s=!z(o),c=L(a,o).split(/[\\/]/).filter(Boolean).join(`/`),l=h(r.scope,r.name);if(ms(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Px(m.dc.document,i.content,`agent`)},m.origin);let g=await vr(l);if(g?.kind===`failure`){br(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){xr(t,`skill-put`);return}r.scope===`project`&&(Li(e,Ii(`skill`,``,r.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Ri(`skill-put`)),ut?.(`files`),K(t,200,Ge,{path:c,created:s,warnings:i.warnings},{handler:`skill-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),Hs=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`skill-delete`)||ks(r,t,`skill-delete`))return;let i=Cs(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Ts(i),o=n.searchParams,s=rH({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},At);if(s.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Hr([h(i,r)],`deleted-upstream`);let c=Xie({skillsRoot:a,name:r});if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;W(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`&&(Li(s,Ii(`skill`,``,r),`skill-delete: ${c.path}`),await Ri(`skill-delete`)),ut?.(`files`));let l=Ns(i);l&&await Ps(l,r),K(t,200,Mt,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Us=wH({GET:Bs,PUT:Vs,POST:q(mt,async(e,t,n)=>{try{let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Ss(n.fromName,t,`skill-move`)||!Ss(n.toName,t,`skill-move`)||ks(n.fromName,t,`skill-move`)||ks(n.toName,t,`skill-move`))return;let r=Ts(n.scope);await Hr([h(n.scope,n.fromName)],`renamed`);let i=await Zie({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await Jq(Et,e,t);return n||qq(e,t),n}});if(!i.ok){if(i.error.code===`SKILL_NOT_FOUND`){W(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:i.error.message});return}if(i.error.code===`SKILL_EXISTS`){W(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;W(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=R(r,n.toName,`SKILL.md`),s=``,c=``;try{let e=gs(B(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=qie({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{Js(r,n.fromName,n.toName)}catch(e){F(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let f=Ms(R(r,n.fromName),n.scope),p=Ms(R(r,n.toName),n.scope);n.scope===`project`&&(Li(e,Ii(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Ri(`skill-move`));let m=Ns(n.scope);if(m){let e=await rI(m,n.fromName);if(e){let t=sB(e.hosts);bB(n.fromName,m,t);let i=yB(R(r,n.toName),n.toName,m,t);await nI(m,n.toName,{...e,hosts:i})}}if(ut?.(`files`),a){let e=a.code===`WRITE_ERROR`;W(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}K(t,200,ge,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),DELETE:Hs},{handler:`skill`});function Ws(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 Gs(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Ks(e,t){let n=t.replace(/\.md$/i,``);return`${xt(e).replace(/\/SKILL$/,``)}/${n}`}function qs(e,t){let n=R(e,t,`references`);if(!z(n))return[];let r=[],i=(e,t)=>{for(let n of il(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(R(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}function Js(e,t,n){if(!nt)return;let r=(e,t,n)=>{let r;try{r=B(n,`utf-8`)}catch{nt.deleteDocument(e),it?.deleteDocument(e);return}nt.renameDocument(e,t,r),it?.renameDocument(e,t,r)};r(xt(t),xt(n),R(e,n,`SKILL.md`));for(let i of qs(e,n))r(Ks(t,i),Ks(n,i),R(e,n,i));ut?.(`backlinks`),ut?.(`graph`)}let Ys=wH({GET:q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`skill-file-get`))return;let i=Cs(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Es&&i===`project`?Ds():null,s=o&&a===`SKILL.md`?`reference`:Ws(a);if(s===null){W(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:R(Ts(i),r),l=R(c,a);if(l!==c&&!l.startsWith(`${c}${Uc}`)){W(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(!z(u)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Ti.map(t=>`${e[1]}${t}`).find(e=>e!==a&&z(R(c,e))):void 0;if(n===void 0){W(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=R(c,n)}let f=await Cl(u);if(f.includes(0)){W(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}K(t,200,ae,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:q(lt,async(e,t,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Ss(r.name,t,`skill-file-put`)||ks(r.name,t,`skill-file-put`))return;let i=Ws(r.path);if(i===null){W(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){W(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let a=Ts(r.scope);if(!z(R(a,r.name,`SKILL.md`))){W(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=Gs(r.scope,i,o),c;if(s){let e=Ks(r.name,o);if(ms(e,`skill-file-put`,t))return;if(c=!z(R(a,r.name,o)),c&&HP(R(a,r.name))>=50){W(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}=gi(r),d=await n.getSession(e,i,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{Px(d.dc.document,r.content,`agent`)},d.origin);let f=await vr(e);if(f?.kind===`failure`){br(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){xr(t,`skill-file-put`);return}}else{let e=Jie({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;W(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`&&(Li(e,Ii(`skill`,``,r.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${r.name}/${o}`),await Ri(`skill-file-put`)),ut?.(`files`),K(t,200,hr,{path:o,created:c,kind:i,content:s},{handler:`skill-file-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!Ss(r,t,`skill-file-delete`)||ks(r,t,`skill-file-delete`))return;let i=Cs(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=Ws(a);if(o===null){W(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=rH({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},At);if(s.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=Ts(i);Gs(i,o,a)&&await Hr([Ks(r,a)],`deleted-upstream`);let l=Yie({skillsRoot:c,name:r,relPath:a});if(!l.ok){let e=l.error.code===`UNLINK_FAILED`?500:400;W(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`&&(Li(s,Ii(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Ri(`skill-file-delete`)),l.existed&&ut?.(`files`),K(t,200,ue,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),Xs=q(lr,async(e,t,n)=>{try{let e=Ts(n.scope);if(!Ss(n.name,t,`skill-install`)||ks(n.name,t,`skill-install`))return;if(n.scope===`project`&&!Et){W(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=Ns(n.scope),i=R(e,n.name);if(!z(i)){W(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=pB(i,n.name);if(!a.ok){W(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?Un.filter(e=>n.targets?.some(t=>t===e)):[...Un]:n.targets===void 0?hB(r,$B(r)??void 0):Un.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=sB(eI(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&bB(n.name,r,l);let u=yB(i,n.name,r,o);u.length===0?await rI(r,n.name):await nI(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),ut?.(`files`),K(t,200,rt,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Zs=q(qt,async(e,t,n)=>{try{if(!Ss(n.name,t,`skill-uninstall`)||ks(n.name,t,`skill-uninstall`))return;let e=Ns(n.scope);if(!e){W(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 Ps(e,n.name);ut?.(`files`),K(t,200,be,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Qs=wH({GET:q(tt,CH(async(e,t)=>{let n=Et?$B(Et):null;K(t,200,Ut,{targets:hB(Et??``,n??void 0),configured:n!==null},{handler:`skill-targets-get`})},{handler:`skill-targets-get`,title:`Failed to read skill targets.`}),{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Ee,CH(async(e,t,n)=>{if(!Et){W(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let r=n.targets,i=new Set(r),a=hB(Et,$B(Et)??void 0),o=Ts(`project`);await eV(Et,r);let{reprojected:s,bundleHosts:c}=await XB({projectDir:Et,skillsRoot:o,targets:r});ut?.(`files`),K(t,200,Lt,{targets:r,reprojected:s,bundleHosts:c,removedFrom:a.filter(e=>!i.has(e))},{handler:`skill-targets-put`})},{handler:`skill-targets-put`,title:`Failed to set skill targets.`}),{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),$s=q(Tt,async(e,t,n)=>{try{let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Ss(n.name,t,`skill-restore`)||ks(n.name,t,`skill-restore`))return;if(n.scope===`global`){W(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=T?.current;if(!r){W(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 EG({shadow:r,contentDir:i,contentRoot:qe??`.`,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];W(t,e,n,a.error,{handler:`skill-restore`,detail:a.code});return}let o=[],s=pB(R(i,`.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."),Li(e,Ii(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Ri(`skill-restore`),ut?.(`files`),K(t,200,_ee,{name:n.name,version:n.version,restoredFiles:a.restoredFiles,warnings:o},{handler:`skill-restore`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),ec=q(Be,async(e,t,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!Ss(r.name,t,`skill-update`)||ks(r.name,t,`skill-update`))return;if(!TB(r.name)){W(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`){W(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=AB(r.name);if(i===null||i.version===void 0){W(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=R(Ts(`project`),r.name,`SKILL.md`);if(!z(a)){W(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let o;try{o=DB(B(a,`utf-8`))}catch{}let s,c=T?.current;if(c)try{let e=Ve?.()??`main`;s=(await tk(c,qe??`.`,[BO],e,`Before updating ${r.name} (${o??`unversioned`} → ${i.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:r.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=h(`project`,r.name);if(ms(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Px(m.dc.document,i.content,`agent`)},m.origin);let g=await vr(l);if(g?.kind===`failure`){br(t,g.failure,`skill-update`);return}if(g?.kind===`divergence`){xr(t,`skill-update`);return}Li(e,Ii(`skill`,``,r.name),`skill-pack-update: ${r.name} (${o??`unversioned`} → ${i.version})`),await Ri(`skill-update`),ut?.(`files`),K(t,200,qr,{name:r.name,version:i.version,...o===void 0?{}:{previousVersion:o},...s===void 0?{}:{checkpointRef:s}},{handler:`skill-update`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function tc(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])=>kt({kind:`folder`,path:e,modifiedTs:t}))}function nc(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 rc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function ic(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 ac(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function oc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function sc(e,t,n,r){let i=r.documents.filter(e=>!Ce(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!nn?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};nn.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await nn.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=rn?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=nn.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function cc(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`?nc(e.document.content,t):void 0}}async function lc(e){let t=performance.now();if(vc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await yc(),i=await sc(e.query,e.intent,e.semanticParam,n),a=w(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>cc(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},Cae({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 uc(){let e=Ts(`project`);if(!z(e))return[];let t;try{t=il(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!ki.test(r.name))continue;let t=R(e,r.name,`SKILL.md`);try{let e=ul(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function dc(){let e=[];for(let t of uc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=gs(B(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(kt({kind:`page`,path:h(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function fc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let pc=new Map;async function mc(){let e=[],t=[],n=new Set;for(let[r,i]of m()){if(tS(r)||nS(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(kt({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=fc(i),o=pc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await Cl(i.canonicalPath,`utf-8`)}catch(e){l=!0,J.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=_k(s,r)}catch(e){J.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=kt({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||pc.set(r,{key:a,doc:u}),e.push(u)}for(let e of pc.keys())n.has(e)||pc.delete(e);let r=lq(),i=t,a=!1;return t.length>r&&(a=!0,i=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,r),F(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),RK().add(1)),{documents:[...e,...dc(),...i,...tc([...e,...i])],truncated:a}}function hc(){return uc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function gc(){return b?`gen:${b()}|skills${hc()}`:`${[...m()].filter(([e])=>!tS(e)&&!nS(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${fc(t)}`).join(``)}|skills${hc()}`}let _c=Xt===void 0;Xt?.then(()=>{_c=!0},e=>{_c=!0,J.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function vc(){return!_c}async function yc(){let e=`${i}${Et??``}`,t=gc(),n=Yq.get(e);if(n?.fingerprint===t&&n.corpus)return{corpus:n.corpus,truncated:n.truncated??!1};if(n?.fingerprint===t&&n.pending)return n.pending;let r=n?.corpus,a=n?.pending,o=(async()=>{let e=a?await a.then(e=>e.corpus,()=>void 0):r,{documents:t,truncated:n}=await mc();if(!e)return BK().add(1,{mode:`cold`}),{corpus:pee(t),truncated:n};let i=ee(e,t);if(i.rebuilt){BK().add(1,{mode:`rebuild`,reason:i.rebuildReason});let e=i.rebuildReason===`mutation-failed`?`warn`:`debug`;F(`search`)[e]({reason:i.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else BK().add(1,{mode:`incremental`}),F(`search`).debug({inserted:i.inserted,updated:i.updated,removed:i.removed},`[search] corpus updated incrementally`);return{corpus:i.corpus,truncated:n}})();Yq.set(e,{fingerprint:t,pending:o});try{let n=await o;return Yq.get(e)?.pending===o&&Yq.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw Yq.get(e)?.pending===o&&Yq.delete(e),t}}function bc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{yc().catch(e=>{J.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}bc();let xc=wH({GET:q(tt,CH(async(e,t)=>{let n=vee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=rc(n.get(`intent`)),o=js(n.get(`ranking`)),s=ic(n.get(`scope`)??n.get(`scopes`)),c=ac(n.get(`semantic`)),l=oc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){W(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}K(t,200,C,await lc({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Ot,CH(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=rc(n.intent),a=js(n.ranking),o=ic(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=ac(n.semantic),l=oc(n.source);if(r.length>200){W(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}K(t,200,C,await lc({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),Sc=q(tt,CH(async(e,t)=>{K(t,200,Ze,{...await _z(hl())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>GU(e,t,{handler:`skill-install-state`})});async function Cc(e,t){if(GU(e,t,{handler:`handoff`}))try{await $ae(e,t,{contentDir:i,platform:process.platform,isSchemeRegistered:zn.probeWithCache})}catch(n){t.headersSent||(J.error({err:n,requestId:xS(e)},`[handoff] route wrapper failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function wc(e,t){if(GU(e,t,{handler:`spawn-cursor`}))try{await LF(e,t,{contentDir:i,platform:process.platform})}catch(n){t.headersSent||(J.error({err:n,requestId:xS(e)},`[spawn-cursor] route wrapper failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Tc=q(u,async(e,t,n)=>{try{if(!Et){aR(`no-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`no-remote`},{handler:tR});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!nR(e,n.kind)){aR(`invalid-path`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`invalid-path`},{handler:tR});return}let r=uR(Et);if(r===null){if(mR(Et).kind===`no-remote`){aR(`no-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`no-remote`},{handler:tR});return}aR(`detached-head`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`detached-head`},{handler:tR});return}let a=mR(Et);if(a.kind===`no-remote`){aR(`no-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`no-remote`},{handler:tR});return}if(a.kind===`non-github`){aR(`non-github-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`non-github-remote`},{handler:tR});return}if(!vR(Et,r)){aR(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),K(t,200,or,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:tR});return}let o=Vq(Et,i);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&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=rR(a.host,a.owner,a.repo,r,n.docPath);else{let e=n.folderPath===``?o:n.folderPath;c=iR(a.host,a.owner,a.repo,r,e)}let l=`https://openknowledge.ai/d/${Zte(c)}`,u=await sR(Et,r,o===``?e:e===``?o:`${o}/${e}`,n.kind);aR(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),K(t,200,or,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:tR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:tR,cause:e})}},{handler:tR,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:tR})}),Ec=q(tt,async(e,t)=>{try{if(!Et){W(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lH});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(!Bt(r)){W(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:lH});return}if(!sH(i,a)){W(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:lH});return}K(t,200,ne,await cH(Et,r,i,a),{handler:lH})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lH,cause:e})}},{handler:lH,method:`GET`,skipBodyParse:!0}),Dc=q(Oe,async(e,t,n)=>{try{if(!Et){W(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:PR});return}if(!sH(n.path,n.kind)){W(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:PR});return}let e=Vq(Et,i);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;K(t,200,He,await LR(Et,n.branch,r,n.kind),{handler:PR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:PR,cause:e})}},{handler:PR,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:PR})}),Oc=q(ot,async(e,t,n)=>{if(rH(n,At).kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:mH});return}if(!Et){W(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:mH});return}try{K(t,200,fr,await jo(()=>gH(Et,n.branch,{fastForward:n.fastForward===!0})),{handler:mH})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mH,cause:e})}},{handler:mH,method:`POST`});async function kc(e){let[t,...n]=St,r=[...n,...e];return await new Promise((e,n)=>{let i=Nc(t,r,NA({...Za,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},SR),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 ${SR}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=NR(Buffer.concat(c).toString(`utf-8`)).slice(0,500);J.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Ac=q(tt,async(e,t)=>{if(!mn.tryAcquire(`/api/share/publish/owners`)){W(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:yR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await kc([`share`,`owners`,`--json`]),n=ER(TR(e));MR(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),K(t,200,et,n,{handler:yR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yR,cause:e})}finally{mn.release(`/api/share/publish/owners`)}},{handler:yR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>GU(e,t,{handler:yR})}),jc=q(tt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!wR(r)||!CR(i)){W(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:bR});return}if(!mn.tryAcquire(`/api/share/publish/name-check`)){W(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:bR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await kc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=OR(TR(e));MR(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),K(t,200,Je,n,{handler:bR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:bR,cause:e})}finally{mn.release(`/api/share/publish/name-check`)}},{handler:bR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>GU(e,t,{handler:bR})}),Mc=q(dt,async(e,t,n)=>{if(!Et){MR(`publish-create`,`no-project`),K(t,200,pe,{ok:!1,error:`no-project`},{handler:xR});return}if(!wR(n.owner)||!CR(n.name)){W(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:xR});return}if(!mn.tryAcquire(`/api/share/publish`)){W(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:xR,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,Et,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await kc(e),i=jR(TR(r));MR(`publish-create`,i.ok?`ok`:i.error),i.ok&&bt?.()?.refreshRemote().catch(()=>{}),K(t,200,pe,i,{handler:xR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xR,cause:e})}finally{mn.release(`/api/share/publish`)}},{handler:xR,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:xR})}),Pc=q(cr,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}K(t,200,Xe,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:`client-logs`})}),Fc=Et?aN(Et):null;async function Lc(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:Fc?Wo(Fc)?.port??0:0,singleFile:ln};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}K(t,200,dee,r,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let I=`local-op-embeddings-set-key`,Vc=`local-op-embeddings-clear-key`,Hc=`/api/local-op/embeddings`,Wc=q(kn,async(e,t,n)=>{if(!mn.tryAcquire(Hc)){W(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:I,extraHeaders:{"Retry-After":`5`}});return}try{await new yF(an).set(n.key),K(t,200,ri,{keyPresent:!0},{handler:I,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:I,cause:e})}finally{mn.release(Hc)}},{handler:I,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:I})}),Gc=q(tt,async(e,t)=>{if(!mn.tryAcquire(Hc)){W(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Vc,extraHeaders:{"Retry-After":`5`}});return}try{await bF(an),K(t,200,ri,{keyPresent:!1},{handler:Vc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Vc,cause:e})}finally{mn.release(Hc)}},{handler:Vc,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Vc})}),Kc=q(tt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(nn){let t=nn.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=await new yF(an).get(),o=process.env.OK_EMBEDDINGS_API_KEY??null,s=a?`file`:o?`env`:null,l=s!==null,u=a??o,d=u&&u.length>=8?u.slice(-4):null,f=0;for(let[e]of c())!tS(e)&&!nS(e)&&!Ce(e)&&(f+=1);K(t,200,Ci,{enabled:e,keyPresent:l,keySource:s,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(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 qc(e,t){let n=cn?.()??Mn;try{return(await si(e,NL(i,n,{docName:t,onProblem:e=>J.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 J.warn({err:e,docName:t},`[lint] advisory lint pass failed post-write; omitting advisories`),[]}}let Jc=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!Zq(n))){W(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=cn?.()??Mn,a=[],o=jL(i,n??void 0,e=>a.push(e));K(t,200,hn,{effective:ML(r,o),configFile:o?.file??null,configProblems:a},{handler:`lint-config`})}catch(e){W(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}),Yc=q(_r,async(e,t,n)=>{let r;try{r=qL(R(i),n.ruleId,n.value)}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){W(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}try{let e=cn?.()??Mn,n=[],r=jL(i,void 0,e=>n.push(e));K(t,200,hn,{effective:ML(e,r),configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){W(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`}),Zc=e=>{let n=e.replace(/\.(md|mdx)$/i,``),r=t.documents.get(n);return r===void 0?null:r.getText(`source`).toString()},Qc=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!Zq(n)){W(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=Mq(i,n);if(r===null){W(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let a=cn?.()??Mn;K(t,200,Fr,await PL({projectDir:Et??i,contentDir:i,baseConfig:a,docRelPath:r,liveSourceFor:Zc}),{handler:`lint`})}catch(e){if(e instanceof CI){W(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}W(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),el=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!_q(r)){W(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let a=cn?.()??Mn;K(t,200,er,await IL({projectDir:Et??i,contentDir:i,baseConfig:a,targetPath:r,liveSourceFor:Zc}),{handler:`lint-audit`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),tl=q(ti,async(t,r,a)=>{try{let t=Sq(a.docName,r,`lint-fix`);if(t===null)return;let o=$n(t),s=rH(a,At);if(s.kind===`invalid-summary`){W(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=s.kind===`anonymous`?`principal-anonymous`:s.writerId,l=s.kind===`anonymous`?`Anonymous`:s.displayName,u=s.kind===`anonymous`?c:s.colorSeed,d=s.kind===`agent`?s.clientName:void 0;if(tS(o)||nS(o)){W(r,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`lint-fix`});return}let f=Mq(i,o);if(f===null){W(r,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}Cq(R(i,f),i);let p=cn?.()??Mn,{stored:m}=wi(s.summary),h=await n.getSession(o,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await FL({projectDir:Et??i,contentDir:i,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=jn(d),n=Tn[t]??gr(u??c);gt?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:o,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{uC(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:o}:void 0)},h.origin),s.kind!==`anonymous`&&GD(o,c,l,u,void 0,s.kind===`agent`?_i({clientName:s.clientName,clientVersion:s.clientVersion,label:s.label}):s.actor,m)}finally{gt?.touchMode(c,`idle`)}let t=await vr(o);if(t?.kind===`failure`){br(r,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){xr(r,`lint-fix`);return}ur(o,`lint-fix`);try{b=await si(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,J.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;K(r,200,Dn,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof CI){W(r,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof kS){AS(r,e,`lint-fix`);return}if(e instanceof PS){IS(r,e,`lint-fix`);return}if(e instanceof mC){W(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}J.error({err:e},`[lint-fix] handler failed`),W(r,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),nl=`link-preview`,rl=new jU({cacheDir:ln?null:R(Et??i,`.ok`,`local`,`link-previews`)}),al=null,sl=()=>(al??=rl.init(),al),cl=fn??SU;async function ll(e){let t=await cl(e);return t.ok?{ok:!0,metadata:await DU({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:cl})}:{ok:!1,reason:t.reason}}let pl=()=>{try{return pn?.()===!0}catch{return!1}},ml={"/api/config":Lc,"/api/asset":Ta,"/api/asset-text":P,"/api/document":Gi,"/api/documents":Ki,"/api/backlinks":Xi,"/api/backlink-counts":Zi,"/api/link-preview":q(Kn,async(e,t,n)=>{try{if(!pl()){J.debug({outcome:`disabled`},`[link-preview] request outcome`),K(t,200,dn,{ok:!1,reason:`disabled`},{handler:nl});return}await sl();let e=!1,r=await rl.load(n.url,()=>(e=!0,ll(n.url)));rl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};J.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),K(t,200,dn,i,{handler:nl})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:nl,cause:e})}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>{let n=PU({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?W(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:nl}):W(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:nl}),!1)}}),"/api/forward-links":Qi,"/api/link-graph":ea,"/api/dead-links":ia,"/api/orphans":ta,"/api/hubs":ra,"/api/tags":as,"/api/pages":Va,"/api/folder-config":fs,"/api/template":bs,"/api/template/import":xs,"/api/templates":hs,"/api/skill":Us,"/api/skill-file":Ys,"/api/skills":Is,"/api/skills/management":zs,"/api/skill/install":Xs,"/api/skill/uninstall":Zs,"/api/skill/restore":$s,"/api/skill/update":ec,"/api/skill-targets":Qs,"/api/search":xc,"/api/semantic-status":Kc,"/api/lint/config":Jc,"/api/lint/markdownlint-config":Yc,"/api/lint":Qc,"/api/lint/audit":el,"/api/lint/fix":tl,"/api/suggest-links":Ha,"/api/page-headings":Ia,"/api/create-page":ka,"/api/create-folder":Aa,"/api/duplicate-path":ja,"/api/rename-path":Ra,"/api/delete-path":za,"/api/trash/cleanup":Ba,"/api/upload":Wa,"/api/agent-write":zi,"/api/agent-write-md":Vi,"/api/agent-write-batch":Hi,"/api/frontmatter-patch":Ui,"/api/agent-patch":aa,"/api/agent-undo":oa,"/api/agent-activity":sa,"/api/agent-burst-diff":ca,"/api/save-version":da,"/api/history":fa,"/api/rollback":ma,"/api/metrics/reconciliation":ha,"/api/metrics/parse-health":ga,"/api/metrics/agent-presence":ba,"/api/metrics/agent-effects":xa,"/api/metrics/watcher-recent":Sa,"/api/__embed-detect":Ca,"/api/server-info":_a,"/api/acp/catalog":N,"/api/share/construct-url":Tc,"/api/share/target-status":Dc,"/api/git/branch-info":Ec,"/api/git/checkout":Oc,"/api/share/publish/owners":Ac,"/api/share/publish/name-check":jc,"/api/share/publish":Mc,"/api/principal":ya,"/api/rescue":Da,"/api/workspace":wa,"/api/sync/status":Jo,"/api/sync/trigger":Yo,"/api/sync/conflicts":Zo,"/api/sync/conflict-content":$o,"/api/sync/resolve-conflict":Qo,"/api/local-op/clone":to,"/api/local-op/ok-init":uo,"/api/local-op/auth/login":ko,"/api/local-op/auth/status":Io,"/api/local-op/auth/pat":Ro,"/api/local-op/auth/gh-login":Po,"/api/local-op/auth/repos":Bo,"/api/local-op/auth/signout":Uo,"/api/local-op/auth/set-identity":qo,"/api/local-op/embeddings/set-key":Wc,"/api/local-op/embeddings/clear-key":Gc,"/api/installed-agents":is,"/api/spawn-cursor":wc,"/api/handoff":Cc,"/api/install-skill":rs,"/api/skill/install-state":Sc,"/api/seed/plan":es,"/api/seed/apply":ts,"/api/seed/packs":ns,"/api/client-logs":Pc};_e&&(ml[`/api/test-reset`]=k,ml[`/api/test-flush-git`]=la,ml[`/api/test-rescan-backlinks`]=A,ml[`/api/test-rescan-files`]=ua);let gl=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),_l=[`/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};lae({ts:Date.now(),url:n,method:e.method??``,ua:r(`user-agent`),origin:r(`origin`),referer:r(`referer`),host:r(`host`),remote:e.socket?.remoteAddress,secChUa:r(`sec-ch-ua`),secChUaMobile:r(`sec-ch-ua-mobile`),secChUaPlatform:r(`sec-ch-ua-platform`),secFetchSite:r(`sec-fetch-site`),secFetchDest:r(`sec-fetch-dest`),secFetchMode:r(`sec-fetch-mode`),secFetchUser:r(`sec-fetch-user`)});let i=e.method??`GET`,a=n;n.startsWith(`/api/history/`)?a=`/api/history/:sha`:n.startsWith(`/api/tags/`)?a=`/api/tags/:name`:ml[n]||(a=`/api/*`);let o=n.startsWith(`/api/`)?mre(e):void 0;if(o!==void 0&&(hre(e,o),typeof t.setHeader==`function`&&t.setHeader(yS,o),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,J.info({event:`api.access`,requestId:o,method:i,route:a,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${i} ${a} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!nD(n)){W(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, ${yS}, ${Se.protocol}, ${Se.runtime}, ${Se.kind}`),t.setHeader(`Access-Control-Expose-Headers`,yS)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(gl.has(n)||_l.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!yW(n)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(ln&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!yW(n)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!n.startsWith(`/api/`))return;let s=Pa.extract(La.active(),e.headers),c=Xa(),l=Date.now();await La.with(s,()=>c.startActiveSpan(`HTTP ${i} ${a}`,{kind:Fa.SERVER,attributes:{[wo]:i,[xo]:a,[So]:n,[bo]:`http`,[yo]:e.headers[`user-agent`]??``,"ok.request.id":o}},async r=>{try{let a=ml[n],o=!1;if(a)o=!0,await a(e,t);else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&(o=!0,await pa(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await os(e,t,r))}o||W(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${i} ${n}`});let s=t.statusCode;r.setAttribute(Oo,s),s>=500&&r.setStatus({code:Na.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:Na.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:a,cause:e}),e}finally{r.end();let e=(Date.now()-l)/1e3;TK().record(e,{[wo]:i,[xo]:a,[Oo]:t.statusCode})}}))}}}function eJ(e){let t=e?.code;return typeof t==`string`?t:void 0}function tJ(e){let t;try{t=il(e.contentDir,{withFileTypes:!0})}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&uS(n.name,Bi)&&e.basenameIndex.add(n.name)}async function nJ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await wl(i,{withFileTypes:!0})}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=I(i,o.name),s=Sk(L(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Sl(a)}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Tl(a)}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Ck(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await El(i)}catch(t){let n=eJ(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()&&uS(a,Yi)&&!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()&&uS(a,Yi)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}var rJ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const iJ=F(`conflict-storage`);var aJ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=I(aN(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!z(this.storePath)){this.conflicts=[];return}try{let e=B(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){iJ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){iJ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=Rc(this.storePath);z(e)||$c(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};fl(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){iJ.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-DY72DIzL.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=R(this.projectDir),r=R(t,e);if(!Ck(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);fl(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),iJ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await cO(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){iJ.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}),iJ.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 oJ(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function sJ(e,t){let n=aN(e);try{$c(n,{recursive:!0}),fl(I(n,de),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=To(e);$c(Rc(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};fl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const cJ=new Map;let lJ=!1;function uJ(e,t){try{let n=oJ(e,t);for(let e of cJ.keys())sJ(e,n)}catch{}}function dJ(e){cJ.set(e,(cJ.get(e)??0)+1),lJ||(lJ=!0,process.on(`uncaughtExceptionMonitor`,uJ));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=cJ.get(e)??0;n<=1?cJ.delete(e):cJ.set(e,n-1)}}}function fJ(e){let t=e.scheduler??m,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function pJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mJ(e){if(!z(e))return{};let t;try{t=(0,HE.parse)(B(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(!pJ(t))return{};let n=t.telemetry;if(!pJ(n))return{};let r=n.localSink;return pJ(r)?r:{}}function hJ(e){return typeof e==`boolean`?e:void 0}function gJ(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function _J(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function vJ(e){if(pJ(e))return gJ(e.maxBytes)}function yJ(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=mJ(Ga(`project`,e.projectDir)),n=mJ(Ga(`project-local`,e.projectDir));if((hJ(n.enabled)??hJ(t.enabled)??!0)===!1)return null;let r=vJ(n.spans)??vJ(t.spans)??52428800,i=vJ(n.logs)??vJ(t.logs)??26214400,a=_J(n.attributeDenylist)??_J(t.attributeDenylist)??ea;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var bJ;(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})(bJ||={});var xJ;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(xJ||={});const SJ=bJ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),CJ=e=>{switch(typeof e){case`undefined`:return SJ.undefined;case`string`:return SJ.string;case`number`:return Number.isNaN(e)?SJ.nan:SJ.number;case`boolean`:return SJ.boolean;case`function`:return SJ.function;case`bigint`:return SJ.bigint;case`symbol`:return SJ.symbol;case`object`:return Array.isArray(e)?SJ.array:e===null?SJ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?SJ.promise:typeof Map<`u`&&e instanceof Map?SJ.map:typeof Set<`u`&&e instanceof Set?SJ.set:typeof Date<`u`&&e instanceof Date?SJ.date:SJ.object;default:return SJ.unknown}},Y=bJ.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 wJ=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,bJ.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()}};wJ.create=e=>new wJ(e);const TJ=(e,t)=>{let n;switch(e.code){case Y.invalid_type:n=e.received===SJ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,bJ.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:n=`Unrecognized key(s) in object: ${bJ.joinValues(e.keys,`, `)}`;break;case Y.invalid_union:n=`Invalid input`;break;case Y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${bJ.joinValues(e.options)}`;break;case Y.invalid_enum_value:n=`Invalid enum value. Expected ${bJ.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}"`:bJ.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,bJ.assertNever(e)}return{message:n}};let EJ=TJ;function DJ(){return EJ}const OJ=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=DJ(),r=OJ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===TJ?void 0:TJ].filter(e=>!!e)});e.common.issues.push(r)}var kJ=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 AJ;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 AJ;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 AJ=Object.freeze({status:`aborted`}),jJ=e=>({status:`dirty`,value:e}),MJ=e=>({status:`valid`,value:e}),NJ=e=>e.status===`aborted`,PJ=e=>e.status===`dirty`,FJ=e=>e.status===`valid`,IJ=e=>typeof Promise<`u`&&e instanceof Promise;var LJ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(LJ||={});var RJ=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 zJ=(e,t)=>{if(FJ(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 wJ(e.common.issues);return this._error=t,this._error}}};function BJ(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 VJ=class{get description(){return this._def.description}_getType(e){return CJ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:CJ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new kJ,ctx:{common:e.parent.common,data:e.data,parsedType:CJ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(IJ(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:CJ(e)};return zJ(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:CJ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return FJ(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=>FJ(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:CJ(e)},r=this._parse({data:e,path:n.path,parent:n});return zJ(n,await(IJ(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 UY({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 WY.create(this,this._def)}nullable(){return GY.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wY.create(this)}promise(){return HY.create(this,this._def)}or(e){return DY.create([this,e],this._def)}and(e){return jY.create(this,e,this._def)}transform(e){return new UY({...BJ(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new KY({...BJ(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new YY({typeName:Z.ZodBranded,type:this,...BJ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new qY({...BJ(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 XY.create(this,e)}readonly(){return ZY.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const HJ=/^c[^\s-]{8,}$/i,UJ=/^[0-9a-z]+$/,WJ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GJ=/^[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,KJ=/^[a-z0-9_-]{21}$/i,qJ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,JJ=/^[-+]?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)?)??$/,YJ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let XJ;const ZJ=/^(?:(?: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])$/,QJ=/^(?:(?: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])$/,$J=/^(([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]))$/,eY=/^(([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])$/,tY=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nY=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rY=`((\\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])))`,iY=RegExp(`^${rY}$`);function aY(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 oY(e){return RegExp(`^${aY(e)}$`)}function sY(e){let t=`${rY}T${aY(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function cY(e,t){return!!((t===`v4`||!t)&&ZJ.test(e)||(t===`v6`||!t)&&$J.test(e))}function lY(e,t){if(!qJ.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 uY(e,t){return!!((t===`v4`||!t)&&QJ.test(e)||(t===`v6`||!t)&&eY.test(e))}var dY=class e extends VJ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==SJ.string){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.string,received:t.parsedType}),AJ}let t=new kJ,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`)YJ.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`)XJ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),XJ.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`)GJ.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`)KJ.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`)HJ.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`)UJ.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`)WJ.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`?sY(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`?iY.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?oY(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`?JJ.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`duration`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?cY(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`?lY(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`?uY(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`?tY.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?nY.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64url`,code:Y.invalid_string,message:r.message}),t.dirty()):bJ.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,...LJ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...LJ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...LJ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...LJ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...LJ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...LJ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...LJ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...LJ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...LJ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...LJ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...LJ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...LJ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...LJ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...LJ.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,...LJ.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,...LJ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...LJ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...LJ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...LJ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...LJ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...LJ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...LJ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...LJ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...LJ.errToObj(t)})}nonempty(e){return this.min(1,LJ.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}};dY.create=e=>new dY({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...BJ(e)});function fY(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 pY=class e extends VJ{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)!==SJ.number){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.number,received:t.parsedType}),AJ}let t,n=new kJ;for(let r of this._def.checks)r.kind===`int`?bJ.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`?fY(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()):bJ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,LJ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,LJ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,LJ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,LJ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:LJ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:LJ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:LJ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:LJ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:LJ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:LJ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:LJ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:LJ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:LJ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:LJ.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`&&bJ.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)}};pY.create=e=>new pY({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...BJ(e)});var mY=class e extends VJ{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)!==SJ.bigint)return this._getInvalidInput(e);let t,n=new kJ;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()):bJ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.bigint,received:t.parsedType}),AJ}gte(e,t){return this.setLimit(`min`,e,!0,LJ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,LJ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,LJ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,LJ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:LJ.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:LJ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:LJ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:LJ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:LJ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:LJ.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}};mY.create=e=>new mY({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...BJ(e)});var hY=class extends VJ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==SJ.boolean){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.boolean,received:t.parsedType}),AJ}return MJ(e.data)}};hY.create=e=>new hY({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...BJ(e)});var gY=class e extends VJ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==SJ.date){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.date,received:t.parsedType}),AJ}if(Number.isNaN(e.data.getTime()))return X(this._getOrReturnCtx(e),{code:Y.invalid_date}),AJ;let t=new kJ,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()):bJ.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:LJ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:LJ.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)}};gY.create=e=>new gY({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...BJ(e)});var _Y=class extends VJ{_parse(e){if(this._getType(e)!==SJ.symbol){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.symbol,received:t.parsedType}),AJ}return MJ(e.data)}};_Y.create=e=>new _Y({typeName:Z.ZodSymbol,...BJ(e)});var vY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.undefined,received:t.parsedType}),AJ}return MJ(e.data)}};vY.create=e=>new vY({typeName:Z.ZodUndefined,...BJ(e)});var yY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.null){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.null,received:t.parsedType}),AJ}return MJ(e.data)}};yY.create=e=>new yY({typeName:Z.ZodNull,...BJ(e)});var bY=class extends VJ{constructor(){super(...arguments),this._any=!0}_parse(e){return MJ(e.data)}};bY.create=e=>new bY({typeName:Z.ZodAny,...BJ(e)});var xY=class extends VJ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return MJ(e.data)}};xY.create=e=>new xY({typeName:Z.ZodUnknown,...BJ(e)});var SY=class extends VJ{_parse(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.never,received:t.parsedType}),AJ}};SY.create=e=>new SY({typeName:Z.ZodNever,...BJ(e)});var CY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.void,received:t.parsedType}),AJ}return MJ(e.data)}};CY.create=e=>new CY({typeName:Z.ZodVoid,...BJ(e)});var wY=class e extends VJ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==SJ.array)return X(t,{code:Y.invalid_type,expected:SJ.array,received:t.parsedType}),AJ;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 RJ(t,e,t.path,n)))).then(e=>kJ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new RJ(t,e,t.path,n)));return kJ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:LJ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:LJ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:LJ.toString(n)}})}nonempty(e){return this.min(1,e)}};wY.create=(e,t)=>new wY({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...BJ(t)});function TY(e){if(e instanceof EY){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=WY.create(TY(r))}return new EY({...e._def,shape:()=>t})}else if(e instanceof wY)return new wY({...e._def,type:TY(e.element)});else if(e instanceof WY)return WY.create(TY(e.unwrap()));else if(e instanceof GY)return GY.create(TY(e.unwrap()));else if(e instanceof MY)return MY.create(e.items.map(e=>TY(e)));else return e}var EY=class e extends VJ{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=bJ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==SJ.object){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.object,received:t.parsedType}),AJ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof SY&&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 RJ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof SY){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 RJ(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=>kJ.mergeObjectSync(t,e)):kJ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return LJ.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:LJ.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 bJ.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 bJ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return TY(this)}partial(t){let n={};for(let e of bJ.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 bJ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof WY;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return zY(bJ.objectKeys(this.shape))}};EY.create=(e,t)=>new EY({shape:()=>e,unknownKeys:`strip`,catchall:SY.create(),typeName:Z.ZodObject,...BJ(t)}),EY.strictCreate=(e,t)=>new EY({shape:()=>e,unknownKeys:`strict`,catchall:SY.create(),typeName:Z.ZodObject,...BJ(t)}),EY.lazycreate=(e,t)=>new EY({shape:e,unknownKeys:`strip`,catchall:SY.create(),typeName:Z.ZodObject,...BJ(t)});var DY=class extends VJ{_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 wJ(e.ctx.common.issues));return X(t,{code:Y.invalid_union,unionErrors:n}),AJ}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 wJ(e));return X(t,{code:Y.invalid_union,unionErrors:i}),AJ}}get options(){return this._def.options}};DY.create=(e,t)=>new DY({options:e,typeName:Z.ZodUnion,...BJ(t)});const OY=e=>e instanceof LY?OY(e.schema):e instanceof UY?OY(e.innerType()):e instanceof RY?[e.value]:e instanceof BY?e.options:e instanceof VY?bJ.objectValues(e.enum):e instanceof KY?OY(e._def.innerType):e instanceof vY?[void 0]:e instanceof yY?[null]:e instanceof WY?[void 0,...OY(e.unwrap())]:e instanceof GY?[null,...OY(e.unwrap())]:e instanceof YY||e instanceof ZY?OY(e.unwrap()):e instanceof qY?OY(e._def.innerType):[];var kY=class e extends VJ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==SJ.object)return X(t,{code:Y.invalid_type,expected:SJ.object,received:t.parsedType}),AJ;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]}),AJ)}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=OY(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,...BJ(r)})}};function AY(e,t){let n=CJ(e),r=CJ(t);if(e===t)return{valid:!0,data:e};if(n===SJ.object&&r===SJ.object){let n=bJ.objectKeys(t),r=bJ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=AY(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===SJ.array&&r===SJ.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=AY(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===SJ.date&&r===SJ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var jY=class extends VJ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(NJ(e)||NJ(r))return AJ;let i=AY(e.value,r.value);return i.valid?((PJ(e)||PJ(r))&&t.dirty(),{status:t.value,value:i.data}):(X(n,{code:Y.invalid_intersection_types}),AJ)};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}))}};jY.create=(e,t,n)=>new jY({left:e,right:t,typeName:Z.ZodIntersection,...BJ(n)});var MY=class e extends VJ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==SJ.array)return X(n,{code:Y.invalid_type,expected:SJ.array,received:n.parsedType}),AJ;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`}),AJ;!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 RJ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>kJ.mergeArray(t,e)):kJ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};MY.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new MY({items:e,typeName:Z.ZodTuple,rest:null,...BJ(t)})};var NY=class e extends VJ{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!==SJ.object)return X(n,{code:Y.invalid_type,expected:SJ.object,received:n.parsedType}),AJ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new RJ(n,e,n.path,e)),value:a._parse(new RJ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?kJ.mergeObjectAsync(t,r):kJ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof VJ?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...BJ(r)}):new e({keyType:dY.create(),valueType:t,typeName:Z.ZodRecord,...BJ(n)})}},PY=class extends VJ{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!==SJ.map)return X(n,{code:Y.invalid_type,expected:SJ.map,received:n.parsedType}),AJ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new RJ(n,e,n.path,[a,`key`])),value:i._parse(new RJ(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 AJ;(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 AJ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};PY.create=(e,t,n)=>new PY({valueType:t,keyType:e,typeName:Z.ZodMap,...BJ(n)});var FY=class e extends VJ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==SJ.set)return X(n,{code:Y.invalid_type,expected:SJ.set,received:n.parsedType}),AJ;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 AJ;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 RJ(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:LJ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:LJ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};FY.create=(e,t)=>new FY({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...BJ(t)});var IY=class e extends VJ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==SJ.function)return X(t,{code:Y.invalid_type,expected:SJ.function,received:t.parsedType}),AJ;function n(e,n){return OJ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,DJ(),TJ].filter(e=>!!e),issueData:{code:Y.invalid_arguments,argumentsError:n}})}function r(e,n){return OJ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,DJ(),TJ].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 HY){let e=this;return MJ(async function(...t){let o=new wJ([]),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 MJ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new wJ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new wJ([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:MY.create(t).rest(xY.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||MY.create([]).rest(xY.create()),returns:n||xY.create(),typeName:Z.ZodFunction,...BJ(r)})}},LY=class extends VJ{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})}};LY.create=(e,t)=>new LY({getter:e,typeName:Z.ZodLazy,...BJ(t)});var RY=class extends VJ{_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}),AJ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};RY.create=(e,t)=>new RY({value:e,typeName:Z.ZodLiteral,...BJ(t)});function zY(e,t){return new BY({values:e,typeName:Z.ZodEnum,...BJ(t)})}var BY=class e extends VJ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return X(t,{expected:bJ.joinValues(n),received:t.parsedType,code:Y.invalid_type}),AJ}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}),AJ}return MJ(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})}};BY.create=zY;var VY=class extends VJ{_parse(e){let t=bJ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==SJ.string&&n.parsedType!==SJ.number){let e=bJ.objectValues(t);return X(n,{expected:bJ.joinValues(e),received:n.parsedType,code:Y.invalid_type}),AJ}if(this._cache||=new Set(bJ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=bJ.objectValues(t);return X(n,{received:n.data,code:Y.invalid_enum_value,options:e}),AJ}return MJ(e.data)}get enum(){return this._def.values}};VY.create=(e,t)=>new VY({values:e,typeName:Z.ZodNativeEnum,...BJ(t)});var HY=class extends VJ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==SJ.promise&&t.common.async===!1?(X(t,{code:Y.invalid_type,expected:SJ.promise,received:t.parsedType}),AJ):MJ((t.parsedType===SJ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};HY.create=(e,t)=>new HY({type:e,typeName:Z.ZodPromise,...BJ(t)});var UY=class extends VJ{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 AJ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?AJ:r.status===`dirty`||t.value===`dirty`?jJ(r.value):r});{if(t.value===`aborted`)return AJ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?AJ:r.status===`dirty`||t.value===`dirty`?jJ(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`?AJ:(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`?AJ:(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(!FJ(e))return AJ;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=>FJ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):AJ);bJ.assertNever(r)}};UY.create=(e,t,n)=>new UY({schema:e,typeName:Z.ZodEffects,effect:t,...BJ(n)}),UY.createWithPreprocess=(e,t,n)=>new UY({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...BJ(n)});var WY=class extends VJ{_parse(e){return this._getType(e)===SJ.undefined?MJ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};WY.create=(e,t)=>new WY({innerType:e,typeName:Z.ZodOptional,...BJ(t)});var GY=class extends VJ{_parse(e){return this._getType(e)===SJ.null?MJ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};GY.create=(e,t)=>new GY({innerType:e,typeName:Z.ZodNullable,...BJ(t)});var KY=class extends VJ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===SJ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};KY.create=(e,t)=>new KY({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...BJ(t)});var qY=class extends VJ{_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 IJ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new wJ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new wJ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};qY.create=(e,t)=>new qY({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...BJ(t)});var JY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.nan){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.nan,received:t.parsedType}),AJ}return{status:`valid`,value:e.data}}};JY.create=e=>new JY({typeName:Z.ZodNaN,...BJ(e)});var YY=class extends VJ{_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}},XY=class e extends VJ{_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`?AJ:e.status===`dirty`?(t.dirty(),jJ(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`?AJ: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})}},ZY=class extends VJ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(FJ(e)&&(e.value=Object.freeze(e.value)),e);return IJ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};ZY.create=(e,t)=>new ZY({innerType:e,typeName:Z.ZodReadonly,...BJ(t)}),EY.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||={}),dY.create,pY.create,JY.create,mY.create,hY.create,gY.create,_Y.create,vY.create,yY.create,bY.create,xY.create,SY.create,CY.create,wY.create;const QY=EY.create;EY.strictCreate,DY.create,kY.create,jY.create,MY.create,NY.create,PY.create,FY.create,IY.create,LY.create,RY.create,BY.create,VY.create,HY.create,UY.create,WY.create,GY.create,UY.createWithPreprocess,XY.create;const $Y=Ui(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Da.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>ja(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Aa(e,t,n),e.parseAsync=async(t,n)=>la(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ta(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)=>ka(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),eX=Ui(`ZodMiniObject`,(e,t)=>{ca.init(e,t),$Y.init(e,t),ra(e,`shape`,()=>t.shape)});function tX(e,t){return new eX({type:`object`,shape:e??{},...Wi(t)})}function nX(e){return!!e._zod}function rX(e){let t=Object.values(e);if(t.length===0)return tX({});let n=t.every(nX),r=t.every(e=>!nX(e));if(n)return tX(e);if(r)return QY(e);throw Error(`Mixed Zod versions detected in object shape.`)}function iX(e,t){return nX(e)?Aa(e,t):e.safeParse(t)}async function aX(e,t){return nX(e)?await ta(e,t):await e.safeParseAsync(t)}function oX(e){if(!e)return;let t;if(t=nX(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function sX(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 rX(e)}}if(nX(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 cX(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 lX(e){return e.description}function uX(e){if(nX(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function dX(e){if(nX(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 fX=`2025-11-25`,pX=[fX,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],mX=`io.modelcontextprotocol/related-task`,hX=oa(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),gX=P([M(),j().int()]),_X=M();Ca({ttl:j().optional(),pollInterval:j().optional()});const vX=O({ttl:j().optional()}),yX=O({taskId:M()}),bX=Ca({progressToken:gX.optional(),[mX]:yX.optional()}),xX=O({_meta:bX.optional()}),SX=xX.extend({task:vX.optional()}),CX=e=>SX.safeParse(e).success,wX=O({method:M(),params:xX.loose().optional()}),TX=O({_meta:bX.optional()}),EX=O({method:M(),params:TX.loose().optional()}),DX=Ca({_meta:bX.optional()}),OX=P([M(),j().int()]),kX=O({jsonrpc:N(`2.0`),id:OX,...wX.shape}).strict(),AX=e=>kX.safeParse(e).success,jX=O({jsonrpc:N(`2.0`),...EX.shape}).strict(),MX=e=>jX.safeParse(e).success,NX=O({jsonrpc:N(`2.0`),id:OX,result:DX}).strict(),PX=e=>NX.safeParse(e).success;var FX;(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`})(FX||={});const IX=O({jsonrpc:N(`2.0`),id:OX.optional(),error:O({code:j().int(),message:M(),data:A().optional()})}).strict(),LX=e=>IX.safeParse(e).success,RX=P([kX,jX,NX,IX]);P([NX,IX]);const zX=DX.strict(),BX=TX.extend({requestId:OX.optional(),reason:M().optional()}),VX=EX.extend({method:N(`notifications/cancelled`),params:BX}),HX=O({icons:D(O({src:M(),mimeType:M().optional(),sizes:D(M()).optional(),theme:Ji([`light`,`dark`]).optional()})).optional()}),UX=O({name:M(),title:M().optional()}),WX=UX.extend({...UX.shape,...HX.shape,version:M(),websiteUrl:M().optional(),description:M().optional()}),GX=wa(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ua(O({form:ua(O({applyDefaults:E().optional()}),k(M(),A())).optional(),url:hX.optional()}),k(M(),A()).optional())),KX=Ca({list:hX.optional(),cancel:hX.optional(),requests:Ca({sampling:Ca({createMessage:hX.optional()}).optional(),elicitation:Ca({create:hX.optional()}).optional()}).optional()}),qX=Ca({list:hX.optional(),cancel:hX.optional(),requests:Ca({tools:Ca({call:hX.optional()}).optional()}).optional()}),JX=O({experimental:k(M(),hX).optional(),sampling:O({context:hX.optional(),tools:hX.optional()}).optional(),elicitation:GX.optional(),roots:O({listChanged:E().optional()}).optional(),tasks:KX.optional(),extensions:k(M(),hX).optional()}),YX=xX.extend({protocolVersion:M(),capabilities:JX,clientInfo:WX}),XX=wX.extend({method:N(`initialize`),params:YX}),ZX=e=>XX.safeParse(e).success,QX=O({experimental:k(M(),hX).optional(),logging:hX.optional(),completions:hX.optional(),prompts:O({listChanged:E().optional()}).optional(),resources:O({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:O({listChanged:E().optional()}).optional(),tasks:qX.optional(),extensions:k(M(),hX).optional()}),$X=DX.extend({protocolVersion:M(),capabilities:QX,serverInfo:WX,instructions:M().optional()}),eZ=EX.extend({method:N(`notifications/initialized`),params:TX.optional()}),tZ=e=>eZ.safeParse(e).success,nZ=wX.extend({method:N(`ping`),params:xX.optional()}),rZ=O({progress:j(),total:ya(j()),message:ya(M())}),iZ=O({...TX.shape,...rZ.shape,progressToken:gX}),aZ=EX.extend({method:N(`notifications/progress`),params:iZ}),oZ=xX.extend({cursor:_X.optional()}),sZ=wX.extend({params:oZ.optional()}),cZ=DX.extend({nextCursor:_X.optional()}),lZ=Ji([`working`,`input_required`,`completed`,`failed`,`cancelled`]),uZ=O({taskId:M(),status:lZ,ttl:P([j(),xa()]),createdAt:M(),lastUpdatedAt:M(),pollInterval:ya(j()),statusMessage:ya(M())}),dZ=DX.extend({task:uZ}),fZ=TX.merge(uZ),pZ=EX.extend({method:N(`notifications/tasks/status`),params:fZ}),mZ=wX.extend({method:N(`tasks/get`),params:xX.extend({taskId:M()})}),hZ=DX.merge(uZ),gZ=wX.extend({method:N(`tasks/result`),params:xX.extend({taskId:M()})});DX.loose();const _Z=sZ.extend({method:N(`tasks/list`)}),vZ=cZ.extend({tasks:D(uZ)}),yZ=wX.extend({method:N(`tasks/cancel`),params:xX.extend({taskId:M()})}),bZ=DX.merge(uZ),xZ=O({uri:M(),mimeType:ya(M()),_meta:k(M(),A()).optional()}),SZ=xZ.extend({text:M()}),CZ=M().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),wZ=xZ.extend({blob:CZ}),TZ=Ji([`user`,`assistant`]),EZ=O({audience:D(TZ).optional(),priority:j().min(0).max(1).optional(),lastModified:ba({offset:!0}).optional()}),DZ=O({...UX.shape,...HX.shape,uri:M(),description:ya(M()),mimeType:ya(M()),size:ya(j()),annotations:EZ.optional(),_meta:ya(Ca({}))}),OZ=O({...UX.shape,...HX.shape,uriTemplate:M(),description:ya(M()),mimeType:ya(M()),annotations:EZ.optional(),_meta:ya(Ca({}))}),kZ=sZ.extend({method:N(`resources/list`)}),AZ=cZ.extend({resources:D(DZ)}),jZ=sZ.extend({method:N(`resources/templates/list`)}),MZ=cZ.extend({resourceTemplates:D(OZ)}),NZ=xX.extend({uri:M()}),PZ=NZ,FZ=wX.extend({method:N(`resources/read`),params:PZ}),IZ=DX.extend({contents:D(P([SZ,wZ]))}),LZ=EX.extend({method:N(`notifications/resources/list_changed`),params:TX.optional()}),RZ=NZ,zZ=wX.extend({method:N(`resources/subscribe`),params:RZ}),BZ=NZ,VZ=wX.extend({method:N(`resources/unsubscribe`),params:BZ}),HZ=TX.extend({uri:M()}),UZ=EX.extend({method:N(`notifications/resources/updated`),params:HZ}),WZ=O({name:M(),description:ya(M()),required:ya(E())}),GZ=O({...UX.shape,...HX.shape,description:ya(M()),arguments:ya(D(WZ)),_meta:ya(Ca({}))}),KZ=sZ.extend({method:N(`prompts/list`)}),qZ=cZ.extend({prompts:D(GZ)}),JZ=xX.extend({name:M(),arguments:k(M(),M()).optional()}),YZ=wX.extend({method:N(`prompts/get`),params:JZ}),XZ=O({type:N(`text`),text:M(),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),ZZ=O({type:N(`image`),data:CZ,mimeType:M(),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),QZ=O({type:N(`audio`),data:CZ,mimeType:M(),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),$Z=O({type:N(`tool_use`),name:M(),id:M(),input:k(M(),A()),_meta:k(M(),A()).optional()}),eQ=O({type:N(`resource`),resource:P([SZ,wZ]),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),tQ=P([XZ,ZZ,QZ,DZ.extend({type:N(`resource_link`)}),eQ]),nQ=O({role:TZ,content:tQ}),rQ=DX.extend({description:M().optional(),messages:D(nQ)}),iQ=EX.extend({method:N(`notifications/prompts/list_changed`),params:TX.optional()}),aQ=O({title:M().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),oQ=O({taskSupport:Ji([`required`,`optional`,`forbidden`]).optional()}),sQ=O({...UX.shape,...HX.shape,description:M().optional(),inputSchema:O({type:N(`object`),properties:k(M(),hX).optional(),required:D(M()).optional()}).catchall(A()),outputSchema:O({type:N(`object`),properties:k(M(),hX).optional(),required:D(M()).optional()}).catchall(A()).optional(),annotations:aQ.optional(),execution:oQ.optional(),_meta:k(M(),A()).optional()}),cQ=sZ.extend({method:N(`tools/list`)}),lQ=cZ.extend({tools:D(sQ)}),uQ=DX.extend({content:D(tQ).default([]),structuredContent:k(M(),A()).optional(),isError:E().optional()});uQ.or(DX.extend({toolResult:A()}));const dQ=SX.extend({name:M(),arguments:k(M(),A()).optional()}),fQ=wX.extend({method:N(`tools/call`),params:dQ}),pQ=EX.extend({method:N(`notifications/tools/list_changed`),params:TX.optional()});O({autoRefresh:E().default(!0),debounceMs:j().int().nonnegative().default(300)});const mQ=Ji([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),hQ=xX.extend({level:mQ}),gQ=wX.extend({method:N(`logging/setLevel`),params:hQ}),_Q=TX.extend({level:mQ,logger:M().optional(),data:A()}),vQ=EX.extend({method:N(`notifications/message`),params:_Q}),yQ=O({hints:D(O({name:M().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),bQ=O({mode:Ji([`auto`,`required`,`none`]).optional()}),xQ=O({type:N(`tool_result`),toolUseId:M().describe(`The unique identifier for the corresponding tool call.`),content:D(tQ).default([]),structuredContent:O({}).loose().optional(),isError:E().optional(),_meta:k(M(),A()).optional()}),SQ=Qi(`type`,[XZ,ZZ,QZ]),CQ=Qi(`type`,[XZ,ZZ,QZ,$Z,xQ]),wQ=O({role:TZ,content:P([CQ,D(CQ)]),_meta:k(M(),A()).optional()}),TQ=SX.extend({messages:D(wQ),modelPreferences:yQ.optional(),systemPrompt:M().optional(),includeContext:Ji([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:D(M()).optional(),metadata:hX.optional(),tools:D(sQ).optional(),toolChoice:bQ.optional()}),EQ=wX.extend({method:N(`sampling/createMessage`),params:TQ}),DQ=DX.extend({model:M(),stopReason:ya(Ji([`endTurn`,`stopSequence`,`maxTokens`]).or(M())),role:TZ,content:SQ}),OQ=DX.extend({model:M(),stopReason:ya(Ji([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(M())),role:TZ,content:P([CQ,D(CQ)])}),kQ=O({type:N(`boolean`),title:M().optional(),description:M().optional(),default:E().optional()}),AQ=O({type:N(`string`),title:M().optional(),description:M().optional(),minLength:j().optional(),maxLength:j().optional(),format:Ji([`email`,`uri`,`date`,`date-time`]).optional(),default:M().optional()}),jQ=O({type:Ji([`number`,`integer`]),title:M().optional(),description:M().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),MQ=O({type:N(`string`),title:M().optional(),description:M().optional(),enum:D(M()),default:M().optional()}),NQ=O({type:N(`string`),title:M().optional(),description:M().optional(),oneOf:D(O({const:M(),title:M()})),default:M().optional()}),PQ=P([P([O({type:N(`string`),title:M().optional(),description:M().optional(),enum:D(M()),enumNames:D(M()).optional(),default:M().optional()}),P([MQ,NQ]),P([O({type:N(`array`),title:M().optional(),description:M().optional(),minItems:j().optional(),maxItems:j().optional(),items:O({type:N(`string`),enum:D(M())}),default:D(M()).optional()}),O({type:N(`array`),title:M().optional(),description:M().optional(),minItems:j().optional(),maxItems:j().optional(),items:O({anyOf:D(O({const:M(),title:M()}))}),default:D(M()).optional()})])]),kQ,AQ,jQ]),FQ=P([SX.extend({mode:N(`form`).optional(),message:M(),requestedSchema:O({type:N(`object`),properties:k(M(),PQ),required:D(M()).optional()})}),SX.extend({mode:N(`url`),message:M(),elicitationId:M(),url:M().url()})]),IQ=wX.extend({method:N(`elicitation/create`),params:FQ}),LQ=TX.extend({elicitationId:M()}),RQ=EX.extend({method:N(`notifications/elicitation/complete`),params:LQ}),zQ=DX.extend({action:Ji([`accept`,`decline`,`cancel`]),content:wa(e=>e===null?void 0:e,k(M(),P([M(),j(),E(),D(M())])).optional())}),BQ=O({type:N(`ref/resource`),uri:M()}),VQ=O({type:N(`ref/prompt`),name:M()}),HQ=xX.extend({ref:P([VQ,BQ]),argument:O({name:M(),value:M()}),context:O({arguments:k(M(),M()).optional()}).optional()}),UQ=wX.extend({method:N(`completion/complete`),params:HQ});function WQ(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function GQ(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const KQ=DX.extend({completion:Ca({values:D(M()).max(100),total:ya(j().int()),hasMore:ya(E())})}),qQ=O({uri:M().startsWith(`file://`),name:M().optional(),_meta:k(M(),A()).optional()}),JQ=wX.extend({method:N(`roots/list`),params:xX.optional()}),YQ=DX.extend({roots:D(qQ)}),XQ=EX.extend({method:N(`notifications/roots/list_changed`),params:TX.optional()});P([nZ,XX,UQ,gQ,YZ,KZ,kZ,jZ,FZ,zZ,VZ,fQ,cQ,mZ,gZ,_Z,yZ]),P([VX,aZ,eZ,XQ,pZ]),P([zX,DQ,OQ,zQ,YQ,hZ,vZ,dZ]),P([nZ,EQ,IQ,JQ,mZ,gZ,_Z,yZ]),P([VX,aZ,vQ,UZ,LZ,pQ,iQ,pZ,RQ]),P([zX,$X,KQ,rQ,qZ,AZ,MZ,IZ,uQ,lQ,hZ,vZ,dZ]);var ZQ=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===FX.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new QQ(e.elicitations,n)}return new e(t,n,r)}},QQ=class extends ZQ{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(FX.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function $Q(e){return e===`completed`||e===`failed`||e===`cancelled`}const e$=Symbol(`Let zodToJsonSchema decide on which parser to use`),t$={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`},n$=e=>typeof e==`string`?{...t$,name:e}:{...t$,...e},r$=e=>{let t=n$(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 i$(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function a$(e,t,n,r,i){e[t]=n,i$(e,t,r,i)}const o$=(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 s$(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?o$(t,e.currentPath):t.join(`/`)}}function c$(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=Q$(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&a$(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&a$(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(a$(n,`minItems`,e.exactLength.value,e.exactLength.message,t),a$(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function l$(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?a$(n,`minimum`,r.value,r.message,t):a$(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),a$(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?a$(n,`maximum`,r.value,r.message,t):a$(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),a$(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:a$(n,`multipleOf`,r.value,r.message,t);break}return n}function u$(){return{type:`boolean`}}function d$(e,t){return Q$(e.type._def,t)}const f$=(e,t)=>Q$(e.innerType._def,t);function p$(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>p$(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 m$(e,t)}}const m$=(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`:a$(n,`minimum`,r.value,r.message,t);break;case`max`:a$(n,`maximum`,r.value,r.message,t);break}return n};function h$(e,t){return{...Q$(e.innerType._def,t),default:e.defaultValue()}}function g$(e,t){return t.effectStrategy===`input`?Q$(e.schema._def,t):s$(t)}function _$(e){return{type:`string`,enum:Array.from(e.values)}}const v$=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function y$(e,t){let n=[Q$(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Q$(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(v$(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 b$(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 x$;const S$={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:()=>(x$===void 0&&(x$=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),x$),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 C$(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:a$(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:a$(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`:D$(n,`email`,r.message,t);break;case`format:idn-email`:D$(n,`idn-email`,r.message,t);break;case`pattern:zod`:O$(n,S$.email,r.message,t);break}break;case`url`:D$(n,`uri`,r.message,t);break;case`uuid`:D$(n,`uuid`,r.message,t);break;case`regex`:O$(n,r.regex,r.message,t);break;case`cuid`:O$(n,S$.cuid,r.message,t);break;case`cuid2`:O$(n,S$.cuid2,r.message,t);break;case`startsWith`:O$(n,RegExp(`^${w$(r.value,t)}`),r.message,t);break;case`endsWith`:O$(n,RegExp(`${w$(r.value,t)}$`),r.message,t);break;case`datetime`:D$(n,`date-time`,r.message,t);break;case`date`:D$(n,`date`,r.message,t);break;case`time`:D$(n,`time`,r.message,t);break;case`duration`:D$(n,`duration`,r.message,t);break;case`length`:a$(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),a$(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:O$(n,RegExp(w$(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&D$(n,`ipv4`,r.message,t),r.version!==`v4`&&D$(n,`ipv6`,r.message,t);break;case`base64url`:O$(n,S$.base64url,r.message,t);break;case`jwt`:O$(n,S$.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&O$(n,S$.ipv4Cidr,r.message,t),r.version!==`v4`&&O$(n,S$.ipv6Cidr,r.message,t);break;case`emoji`:O$(n,S$.emoji(),r.message,t);break;case`ulid`:O$(n,S$.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:D$(n,`binary`,r.message,t);break;case`contentEncoding:base64`:a$(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:O$(n,S$.base64,r.message,t);break}break;case`nanoid`:O$(n,S$.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function w$(e,t){return t.patternStrategy===`escape`?E$(e):e}const T$=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function E$(e){let t=``;for(let n=0;n<e.length;n++)T$.has(e[n])||(t+=`\\`),t+=e[n];return t}function D$(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}}})):a$(e,`format`,t,n,r)}function O$(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:k$(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):a$(e,`pattern`,k$(t,r),n,r)}function k$(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
1226
+ `);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=>{J.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),mn.release(mo))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),mn.release(mo))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),mn.release(mo))})}let Ho=`local-op-auth-signout`,Uo=q(jr,async(e,t,n)=>{let r=n.host??vo();if(!mn.tryAcquire(go)){W(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Ho,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=St,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=Nc(e,i,NA({...Qa,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),K(t,200,li,{},{handler:Ho})}catch(e){W(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Ho,cause:e})}finally{mn.release(go)}},{handler:Ho,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Ho})}),Go=`/api/local-op/auth/set-identity`,Ko=`local-op-auth-set-identity`,qo=q(_n,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!Et){W(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ko});return}if(!mn.tryAcquire(Go)){W(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ko,extraHeaders:{"Retry-After":`5`}});return}try{SH(Et,r,i),bt?.()?.refreshIdentity().catch(()=>{}),K(t,200,li,{},{handler:Ko})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ko,cause:e})}finally{mn.release(Go)}},{handler:Ko,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Ko})});async function Jo(e,t){if(GU(e,t,{handler:`sync-status`})){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=bt?.();if(!e){K(t,200,Dt,{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(),K(t,200,Dt,e.getStatus(),{handler:`sync-status`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Yo=q(x,async(e,t,n)=>{let r=bt?.();if(!r){W(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;K(t,202,Si,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:`sync-trigger`})?bt?.()?!0:(W(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Zo(e,t){if(GU(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=bt?.();K(t,200,Ni,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Qo=q(Sn,async(e,t,n)=>{let r=bt?.();if(!r){W(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),K(t,200,Di,{},{handler:`sync-resolve-conflict`})}catch(e){W(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)=>GU(e,t,{handler:`sync-resolve-conflict`})?bt?.()?!0:(W(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function $o(e,n){if(!GU(e,n,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){W(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!Et){W(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){W(n,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){W(n,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=dS(i),o=t.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,s=bt?.(),c=s?s.getConflicts().some(e=>e.file===i):!1;if(!o&&!c){W(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=Ao({baseDir:Et,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=dS(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=$t?$t(e):null;t!==null&&!KK(t)?u=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else J.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}K(n,200,fee,{file:i,base:o,ours:u,theirs:s,kind:c,lifecycleStatus:f},{handler:`sync-conflict-content`})}catch(e){W(n,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function es(e,t){if(!GU(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),r=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=rG(a);if(a!==null&&a!==``&&o===void 0){W(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{K(t,200,un,{plan:await yG({projectDir:i,rootDir:r,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof GW){W(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof KW){W(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}W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let ts=q(wr,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){W(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let a=r,o=n.packId,s=rG(o);if(typeof o==`string`&&o.length>0&&s===void 0){W(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${o}" is not registered.`});return}try{K(t,200,lee,{result:await mG(a,{projectDir:i,packId:s})},{handler:`seed-apply`})}catch(e){W(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)=>GU(e,t,{handler:`seed-apply`})});async function ns(e,t){if(GU(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}K(t,200,Gn,{packs:aG()},{handler:`seed-packs`})}}let rs=q(cee,async(e,t,n)=>{if(n.out!==void 0&&!HU(n.out)){W(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{K(t,200,Br,await jz({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){W(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)=>GU(e,t,{handler:`install-skill`})});async function is(e,t){if(GU(e,t,{handler:`installed-agents`}))try{await Wae(e,t,zn.probeAll)}catch(n){t.headersSent||(J.error({err:n,requestId:xS(e)},`[installed-agents] route wrapper failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let as=q(tt,async(e,t)=>{if(!it){W(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{K(t,200,on,{tags:it.getAllTags()},{handler:`tags-list`})}catch(e){W(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 os(e,t,n){if(e.method!==`GET`){W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!it){W(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{W(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){W(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=it.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:qn(e),matchingTags:t,snippet:null}));K(t,200,Qt,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function ss(e,t,n=`path`,r=`folder-config`){let a=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(a.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return W(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let o=R(i),s=a===``?o:R(o,a);return s!==o&&!s.startsWith(`${o}${Uc}`)?(W(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:a,resolvedContentDir:o}}let cs=/^[A-Za-z0-9_-]+$/;function ls(e,t,n=`template`){return!e||!cs.test(e)?(W(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function us(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:R(e,i);if(a!==e&&!a.startsWith(`${e}${Uc}`))continue;let o=R(a,`.ok`,`templates`,`${n}.md`);if(z(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function ds(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}let fs=wH({GET:q(tt,async(e,t)=>{try{let n=ss(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await OP(n.folderRel,{projectDir:n.resolvedContentDir}),i=R(R(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(z(i))try{let e=(0,HE.parse)(await Cl(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);J.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}K(t,200,yi,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Fi,async(e,t,n)=>{try{if(ln){W(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=ss(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=NP({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;W(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`&&(Li(e,Ii(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Ri(`folder-config-put`))}K(t,200,wn,{applied:i},{handler:`folder-config-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function ps(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&&DS(o)?(AS(i,new kS({file:`${a}.md`}),r),!0):!1}function ms(e,n,r){let i=t.documents.get(e);return i&&DS(i)?(AS(r,new kS({file:`${e}.md`}),n),!0):!1}let hs=q(tt,CH(async(e,t)=>{let n=cP(R(i));K(t,200,Ir,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),gs=e=>{let{body:t}=en(e);return{frontmatter:Qe(e)??{},body:t}},_s=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ls(r,t,`template-get`))return;let i=ss(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,c=us(o,a,r);if(!c){W(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:l,folder:u,scope:d}=c,f=sn(await Cl(l,`utf-8`)),p=f.identity,m=f.starterContent;K(t,200,s,{template:{name:r,folder:u,scope:d,path:L(o,l).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:p,body:m}},{handler:`template-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),vs=q(tr,async(e,t,r)=>{try{if(ln){W(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let i=r.name;if(!ls(i,t,`template-put`))return;let a=ss(r.folder,t,`folder`,`template-put`);if(!a||ps(a.folderRel,i,`template-put`,t))return;let o=$P({name:i,body:typeof r.body==`string`?r.body:``,frontmatter:ds(r.frontmatter)});if(!o.ok){W(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=R(a.resolvedContentDir,a.folderRel,`.ok`,`templates`,`${i}.md`),c=!z(s),l=L(a.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=As(a.folderRel,i),{agentId:d,agentName:f,colorSeed:p,clientName:m}=gi(r),h=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Px(h.dc.document,o.content,`agent`)},h.origin);let g=await vr(u);if(g?.kind===`failure`){br(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){xr(t,`template-put`);return}Li(e,Ii(`template`,a.folderRel,i),`${c?`template-create`:`template-edit`}: ${l}`),await Ri(`template-put`),K(t,200,gn,{path:l,created:c,warnings:o.warnings},{handler:`template-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),ys=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ls(r,t,`template-delete`))return;let i=ss(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=rH({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},At);if(o.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(ps(i.folderRel,r,`template-delete`,t))return;await Hr([As(i.folderRel,r)],`deleted-upstream`);let s=iae({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;W(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&&(Li(o,Ii(`template`,i.folderRel,r),`template-delete: ${s.path}`),await Ri(`template-delete`)),K(t,200,yt,{existed:s.existed,path:s.path},{handler:`template-delete`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),bs=wH({GET:_s,PUT:vs,POST:q(Ar,async(e,t,n)=>{try{let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!ls(n.fromName,t,`template-move`)||!ls(n.toName,t,`template-move`))return;let r=ss(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=ss(n.toFolder,t,`folder`,`template-move`);if(!i||ps(r.folderRel,n.fromName,`template-move`,t))return;await Hr([As(r.folderRel,n.fromName)],`renamed`);let a=await aae({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await Jq(Et,e,t);return n||qq(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=us(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){W(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}W(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`){W(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;W(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=Hn(B(R(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=rae({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ds(n.frontmatter)});t.ok||(o=t.error)}}if(Li(e,Ii(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Ri(`template-move`),ut?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;W(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}K(t,200,Zr,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:ys},{handler:`template`}),xs=q(oee,async(e,r,a)=>{try{if(ln){W(r,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=rH(a,At);if(e.kind===`invalid-summary`){W(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let o=a.sourcePath;if(!Zq(o)){W(r,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let s=$n(o);if(tS(s)||nS(s)){W(r,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`template-import`});return}let c=wq(i,`file`,s);if(!z(c)){W(r,404,`urn:ok:error:doc-not-found`,`Source document not found: ${s}.`,{handler:`template-import`});return}let l=t.documents.get(s);if(a.deleteSource){let e=bt?.(),t=new Set(e?e.getConflicts().map(e=>e.file):[]),n=l!==void 0&&DS(l),i=t.has(o);if(n||i){AS(r,new kS({file:o}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await t.openDirectConnection(s);try{let t=e.document;if(!t){W(r,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=t.getText(`source`).toString()}finally{await e.disconnect()}}let d=a.name;if(!d){let{basename:e}=Tq(o);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!ls(d,r,`template-import`))return;let f=ss(a.targetFolder,r,`folder`,`template-import`);if(!f||ps(f.folderRel,d,`template-import`,r))return;let{frontmatter:p,body:m}=en(u),h=Yt(p),g={};try{h.trim()&&(g=(0,HE.parse)(h))}catch{}let _=a.title||g?.title||_k(u,d),v=g?.description||``,b=Array.isArray(g?.tags)?g.tags:[],x={...g};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,HE.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=$P({name:d,body:S,frontmatter:{title:_,description:v,tags:b}});if(!C.ok){W(r,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let ee=R(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),te=!z(ee),ne=L(f.resolvedContentDir,ee).split(/[\\/]/).filter(Boolean).join(`/`),re=As(f.folderRel,d),{agentId:ie,agentName:ae,colorSeed:w,clientName:oe}=gi(a),se=await n.getSession(re,ie,{displayName:ae,colorSeed:w,clientName:oe});se.dc.document.transact(()=>{Px(se.dc.document,C.content,`agent`)},se.origin);let ce=await vr(re);if(ce?.kind===`failure`){br(r,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){xr(r,`template-import`);return}Li(e,Ii(`template`,f.folderRel,d),`template-import: ${ne}`),a.deleteSource&&(await Hr([s],`deleted-upstream`),Zt&&Zt.setDeleted(s),eo(c),y?.({kind:`delete`,path:c,docName:s})),await Ri(`template-import`),ut?.(`files`),K(r,200,ci,{path:ne,created:te,warnings:C.warnings},{handler:`template-import`})}catch(e){W(r,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Ss(e,t,n){return!e||e.length>64||!ki.test(e)?(W(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 Cs(e,t,n){let r=v.safeParse(e??`project`);return r.success?r.data:(W(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let ws=Nt??hl();function Ts(e){return R(e===`global`?ws:i,`.ok`,`skills`)}let Es=RR.project;function Ds(){if(!Et)return null;let e=[],t=null;for(let n of Un){let r=Sr[n];if(!r)continue;let i=R(Et,...r.split(`/`),Es);z(R(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=R(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:L(Et,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Os(){let e=Ds();if(!e)return null;let t;try{let{frontmatter:n}=gs(B(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Es,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function ks(e,t,n){return BR(e)?(W(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 As(e,t){return`${dr}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function js(e){return e===`navigation`||e===`relevance`?e:void 0}function Ms(e,t){return L(t===`global`?ws:i,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Ns(e){return e===`global`?ws:Et}async function Ps(e,t){let n=await rI(e,t);return bB(t,e,Un),n!==null}function Fs(e,t){let n=[];if(!z(e))return{skills:n,truncated:!1};let r;try{r=il(e,{withFileTypes:!0})}catch(r){return F(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!ki.test(a.name))continue;if(n.length>=500){i=!0;break}let r=R(e,a.name,`SKILL.md`);if(!z(r))continue;let o,s;try{let{frontmatter:e}=gs(B(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:Ms(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Is=q(tt,CH(async(e,t)=>{let n=Fs(Ts(`project`),`project`),r=Fs(Ts(`global`),`global`),i=Et?eI(Et).skills:{},a=eI(ws).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=MB(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Es)?null:Os();K(t,200,Ie,{skills:[...o(n,i),...o(r,a),...s?[s]:[]],truncated:n.truncated||r.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Ls=O({managed:E().nullable(),importable:j().int().nonnegative()}),Rs=()=>({managed:Et?Fz(Et)?.manageEditorSkills??null:null,importable:Et?KB({projectDir:Et,skillsRoot:Ts(`project`)}):0}),zs=wH({GET:q(tt,async(e,t)=>{if(!Et){W(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}K(t,200,Ls,Rs(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:q(O({manageEditorSkills:E()}),async(e,t,n)=>{if(!Et){W(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await Iz(Et,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await qB({projectDir:Et,skillsRoot:Ts(`project`)});e.adopted.length+e.collided.length>0&&ut?.(`files`)}K(t,200,Ls,Rs(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),Bs=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`skill-get`))return;let i=Cs(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Es&&i===`project`){let e=Ds();if(e){let{frontmatter:n,body:a}=gs(await Cl(e.skillMd,`utf-8`));K(t,200,p,{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:wB(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=Ts(i),o=R(a,r,`SKILL.md`);if(!z(o)){W(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}=gs(await Cl(o,`utf-8`));K(t,200,p,{skill:{name:r,scope:i,path:Ms(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:wB(R(a,r))}},{handler:`skill-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),Vs=q(je,async(e,t,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Ss(r.name,t,`skill-put`)||ks(r.name,t,`skill-put`))return;let i=BP({name:r.name,body:typeof r.body==`string`?r.body:``,frontmatter:{name:r.frontmatter.name,description:r.frontmatter.description}});if(!i.ok){W(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=Ts(r.scope),o=R(a,r.name,`SKILL.md`),s=!z(o),c=L(a,o).split(/[\\/]/).filter(Boolean).join(`/`),l=h(r.scope,r.name);if(ms(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Px(m.dc.document,i.content,`agent`)},m.origin);let g=await vr(l);if(g?.kind===`failure`){br(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){xr(t,`skill-put`);return}r.scope===`project`&&(Li(e,Ii(`skill`,``,r.name),`${s?`skill-create`:`skill-edit`}: ${c}`),await Ri(`skill-put`)),ut?.(`files`),K(t,200,Ge,{path:c,created:s,warnings:i.warnings},{handler:`skill-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),Hs=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`skill-delete`)||ks(r,t,`skill-delete`))return;let i=Cs(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=Ts(i),o=n.searchParams,s=rH({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},At);if(s.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Hr([h(i,r)],`deleted-upstream`);let c=Xie({skillsRoot:a,name:r});if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;W(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`&&(Li(s,Ii(`skill`,``,r),`skill-delete: ${c.path}`),await Ri(`skill-delete`)),ut?.(`files`));let l=Ns(i);l&&await Ps(l,r),K(t,200,Mt,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Us=wH({GET:Bs,PUT:Vs,POST:q(mt,async(e,t,n)=>{try{let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Ss(n.fromName,t,`skill-move`)||!Ss(n.toName,t,`skill-move`)||ks(n.fromName,t,`skill-move`)||ks(n.toName,t,`skill-move`))return;let r=Ts(n.scope);await Hr([h(n.scope,n.fromName)],`renamed`);let i=await Zie({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await Jq(Et,e,t);return n||qq(e,t),n}});if(!i.ok){if(i.error.code===`SKILL_NOT_FOUND`){W(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:i.error.message});return}if(i.error.code===`SKILL_EXISTS`){W(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;W(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=R(r,n.toName,`SKILL.md`),s=``,c=``;try{let e=gs(B(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=qie({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{Js(r,n.fromName,n.toName)}catch(e){F(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let f=Ms(R(r,n.fromName),n.scope),p=Ms(R(r,n.toName),n.scope);n.scope===`project`&&(Li(e,Ii(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await Ri(`skill-move`));let m=Ns(n.scope);if(m){let e=await rI(m,n.fromName);if(e){let t=sB(e.hosts);bB(n.fromName,m,t);let i=yB(R(r,n.toName),n.toName,m,t);await nI(m,n.toName,{...e,hosts:i})}}if(ut?.(`files`),a){let e=a.code===`WRITE_ERROR`;W(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}K(t,200,ge,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),DELETE:Hs},{handler:`skill`});function Ws(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 Gs(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Ks(e,t){let n=t.replace(/\.md$/i,``);return`${xt(e).replace(/\/SKILL$/,``)}/${n}`}function qs(e,t){let n=R(e,t,`references`);if(!z(n))return[];let r=[],i=(e,t)=>{for(let n of il(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(R(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}function Js(e,t,n){if(!nt)return;let r=(e,t,n)=>{let r;try{r=B(n,`utf-8`)}catch{nt.deleteDocument(e),it?.deleteDocument(e);return}nt.renameDocument(e,t,r),it?.renameDocument(e,t,r)};r(xt(t),xt(n),R(e,n,`SKILL.md`));for(let i of qs(e,n))r(Ks(t,i),Ks(n,i),R(e,n,i));ut?.(`backlinks`),ut?.(`graph`)}let Ys=wH({GET:q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`skill-file-get`))return;let i=Cs(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Es&&i===`project`?Ds():null,s=o&&a===`SKILL.md`?`reference`:Ws(a);if(s===null){W(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:R(Ts(i),r),l=R(c,a);if(l!==c&&!l.startsWith(`${c}${Uc}`)){W(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(!z(u)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Ti.map(t=>`${e[1]}${t}`).find(e=>e!==a&&z(R(c,e))):void 0;if(n===void 0){W(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=R(c,n)}let f=await Cl(u);if(f.includes(0)){W(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}K(t,200,ae,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:q(lt,async(e,t,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Ss(r.name,t,`skill-file-put`)||ks(r.name,t,`skill-file-put`))return;let i=Ws(r.path);if(i===null){W(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){W(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let a=Ts(r.scope);if(!z(R(a,r.name,`SKILL.md`))){W(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=Gs(r.scope,i,o),c;if(s){let e=Ks(r.name,o);if(ms(e,`skill-file-put`,t))return;if(c=!z(R(a,r.name,o)),c&&HP(R(a,r.name))>=50){W(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}=gi(r),d=await n.getSession(e,i,{displayName:s,colorSeed:l,clientName:u});d.dc.document.transact(()=>{Px(d.dc.document,r.content,`agent`)},d.origin);let f=await vr(e);if(f?.kind===`failure`){br(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){xr(t,`skill-file-put`);return}}else{let e=Jie({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;W(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`&&(Li(e,Ii(`skill`,``,r.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${r.name}/${o}`),await Ri(`skill-file-put`)),ut?.(`files`),K(t,200,hr,{path:o,created:c,kind:i,content:s},{handler:`skill-file-put`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!Ss(r,t,`skill-file-delete`)||ks(r,t,`skill-file-delete`))return;let i=Cs(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=Ws(a);if(o===null){W(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=rH({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},At);if(s.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=Ts(i);Gs(i,o,a)&&await Hr([Ks(r,a)],`deleted-upstream`);let l=Yie({skillsRoot:c,name:r,relPath:a});if(!l.ok){let e=l.error.code===`UNLINK_FAILED`?500:400;W(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`&&(Li(s,Ii(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await Ri(`skill-file-delete`)),l.existed&&ut?.(`files`),K(t,200,ue,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),Xs=q(lr,async(e,t,n)=>{try{let e=Ts(n.scope);if(!Ss(n.name,t,`skill-install`)||ks(n.name,t,`skill-install`))return;if(n.scope===`project`&&!Et){W(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=Ns(n.scope),i=R(e,n.name);if(!z(i)){W(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=pB(i,n.name);if(!a.ok){W(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?Un.filter(e=>n.targets?.some(t=>t===e)):[...Un]:n.targets===void 0?hB(r,$B(r)??void 0):Un.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=sB(eI(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&bB(n.name,r,l);let u=yB(i,n.name,r,o);u.length===0?await rI(r,n.name):await nI(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),ut?.(`files`),K(t,200,rt,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Zs=q(qt,async(e,t,n)=>{try{if(!Ss(n.name,t,`skill-uninstall`)||ks(n.name,t,`skill-uninstall`))return;let e=Ns(n.scope);if(!e){W(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 Ps(e,n.name);ut?.(`files`),K(t,200,be,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Qs=wH({GET:q(tt,CH(async(e,t)=>{let n=Et?$B(Et):null;K(t,200,Ut,{targets:hB(Et??``,n??void 0),configured:n!==null},{handler:`skill-targets-get`})},{handler:`skill-targets-get`,title:`Failed to read skill targets.`}),{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Ee,CH(async(e,t,n)=>{if(!Et){W(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let r=n.targets,i=new Set(r),a=hB(Et,$B(Et)??void 0),o=Ts(`project`);await eV(Et,r);let{reprojected:s,bundleHosts:c}=await XB({projectDir:Et,skillsRoot:o,targets:r});ut?.(`files`),K(t,200,Lt,{targets:r,reprojected:s,bundleHosts:c,removedFrom:a.filter(e=>!i.has(e))},{handler:`skill-targets-put`})},{handler:`skill-targets-put`,title:`Failed to set skill targets.`}),{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),$s=q(Tt,async(e,t,n)=>{try{let e=rH(n,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Ss(n.name,t,`skill-restore`)||ks(n.name,t,`skill-restore`))return;if(n.scope===`global`){W(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=T?.current;if(!r){W(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 EG({shadow:r,contentDir:i,contentRoot:qe??`.`,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];W(t,e,n,a.error,{handler:`skill-restore`,detail:a.code});return}let o=[],s=pB(R(i,`.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."),Li(e,Ii(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Ri(`skill-restore`),ut?.(`files`),K(t,200,_ee,{name:n.name,version:n.version,restoredFiles:a.restoredFiles,warnings:o},{handler:`skill-restore`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),ec=q(Be,async(e,t,r)=>{try{let e=rH(r,At);if(e.kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!Ss(r.name,t,`skill-update`)||ks(r.name,t,`skill-update`))return;if(!TB(r.name)){W(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`){W(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=AB(r.name);if(i===null||i.version===void 0){W(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=R(Ts(`project`),r.name,`SKILL.md`);if(!z(a)){W(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let o;try{o=DB(B(a,`utf-8`))}catch{}let s,c=T?.current;if(c)try{let e=Ve?.()??`main`;s=(await tk(c,qe??`.`,[BO],e,`Before updating ${r.name} (${o??`unversioned`} → ${i.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:r.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=h(`project`,r.name);if(ms(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=gi(r),m=await n.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{Px(m.dc.document,i.content,`agent`)},m.origin);let g=await vr(l);if(g?.kind===`failure`){br(t,g.failure,`skill-update`);return}if(g?.kind===`divergence`){xr(t,`skill-update`);return}Li(e,Ii(`skill`,``,r.name),`skill-pack-update: ${r.name} (${o??`unversioned`} → ${i.version})`),await Ri(`skill-update`),ut?.(`files`),K(t,200,qr,{name:r.name,version:i.version,...o===void 0?{}:{previousVersion:o},...s===void 0?{}:{checkpointRef:s}},{handler:`skill-update`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function tc(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])=>kt({kind:`folder`,path:e,modifiedTs:t}))}function nc(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 rc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function ic(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 ac(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function oc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function sc(e,t,n,r){let i=r.documents.filter(e=>!Ce(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!nn?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};nn.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await nn.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=rn?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=nn.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function cc(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`?nc(e.document.content,t):void 0}}async function lc(e){let t=performance.now();if(vc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await yc(),i=await sc(e.query,e.intent,e.semanticParam,n),a=w(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>cc(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},Cae({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 uc(){let e=Ts(`project`);if(!z(e))return[];let t;try{t=il(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!ki.test(r.name))continue;let t=R(e,r.name,`SKILL.md`);try{let e=ul(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function dc(){let e=[];for(let t of uc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=gs(B(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(kt({kind:`page`,path:h(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function fc(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let pc=new Map;async function mc(){let e=[],t=[],n=new Set;for(let[r,i]of m()){if(tS(r)||nS(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(kt({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=fc(i),o=pc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await Cl(i.canonicalPath,`utf-8`)}catch(e){l=!0,J.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=_k(s,r)}catch(e){J.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=kt({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||pc.set(r,{key:a,doc:u}),e.push(u)}for(let e of pc.keys())n.has(e)||pc.delete(e);let r=lq(),i=t,a=!1;return t.length>r&&(a=!0,i=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,r),F(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),RK().add(1)),{documents:[...e,...dc(),...i,...tc([...e,...i])],truncated:a}}function hc(){return uc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function gc(){return b?`gen:${b()}|skills${hc()}`:`${[...m()].filter(([e])=>!tS(e)&&!nS(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${fc(t)}`).join(``)}|skills${hc()}`}let _c=Xt===void 0;Xt?.then(()=>{_c=!0},e=>{_c=!0,J.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function vc(){return!_c}async function yc(){let e=`${i}${Et??``}`,t=gc(),n=Yq.get(e);if(n?.fingerprint===t&&n.corpus)return{corpus:n.corpus,truncated:n.truncated??!1};if(n?.fingerprint===t&&n.pending)return n.pending;let r=n?.corpus,a=n?.pending,o=(async()=>{let e=a?await a.then(e=>e.corpus,()=>void 0):r,{documents:t,truncated:n}=await mc();if(!e)return BK().add(1,{mode:`cold`}),{corpus:pee(t),truncated:n};let i=ee(e,t);if(i.rebuilt){BK().add(1,{mode:`rebuild`,reason:i.rebuildReason});let e=i.rebuildReason===`mutation-failed`?`warn`:`debug`;F(`search`)[e]({reason:i.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else BK().add(1,{mode:`incremental`}),F(`search`).debug({inserted:i.inserted,updated:i.updated,removed:i.removed},`[search] corpus updated incrementally`);return{corpus:i.corpus,truncated:n}})();Yq.set(e,{fingerprint:t,pending:o});try{let n=await o;return Yq.get(e)?.pending===o&&Yq.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw Yq.get(e)?.pending===o&&Yq.delete(e),t}}function bc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{yc().catch(e=>{J.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}bc();let xc=wH({GET:q(tt,CH(async(e,t)=>{let n=vee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=rc(n.get(`intent`)),o=js(n.get(`ranking`)),s=ic(n.get(`scope`)??n.get(`scopes`)),c=ac(n.get(`semantic`)),l=oc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){W(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}K(t,200,C,await lc({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Ot,CH(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=rc(n.intent),a=js(n.ranking),o=ic(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=ac(n.semantic),l=oc(n.source);if(r.length>200){W(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}K(t,200,C,await lc({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),Sc=q(tt,CH(async(e,t)=>{K(t,200,Ze,{...await _z(hl())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>GU(e,t,{handler:`skill-install-state`})});async function Cc(e,t){if(GU(e,t,{handler:`handoff`}))try{await $ae(e,t,{contentDir:i,platform:process.platform,isSchemeRegistered:zn.probeWithCache})}catch(n){t.headersSent||(J.error({err:n,requestId:xS(e)},`[handoff] route wrapper failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function wc(e,t){if(GU(e,t,{handler:`spawn-cursor`}))try{await LF(e,t,{contentDir:i,platform:process.platform})}catch(n){t.headersSent||(J.error({err:n,requestId:xS(e)},`[spawn-cursor] route wrapper failed`),W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Tc=q(u,async(e,t,n)=>{try{if(!Et){aR(`no-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`no-remote`},{handler:tR});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!nR(e,n.kind)){aR(`invalid-path`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`invalid-path`},{handler:tR});return}let r=uR(Et);if(r===null){if(mR(Et).kind===`no-remote`){aR(`no-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`no-remote`},{handler:tR});return}aR(`detached-head`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`detached-head`},{handler:tR});return}let a=mR(Et);if(a.kind===`no-remote`){aR(`no-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`no-remote`},{handler:tR});return}if(a.kind===`non-github`){aR(`non-github-remote`,{kind:n.kind}),K(t,200,or,{ok:!1,error:`non-github-remote`},{handler:tR});return}if(!vR(Et,r)){aR(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),K(t,200,or,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:tR});return}let o=Vq(Et,i);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&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=rR(a.host,a.owner,a.repo,r,n.docPath);else{let e=n.folderPath===``?o:n.folderPath;c=iR(a.host,a.owner,a.repo,r,e)}let l=`https://openknowledge.ai/d/${Zte(c)}`,u=await sR(Et,r,o===``?e:e===``?o:`${o}/${e}`,n.kind);aR(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),K(t,200,or,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:tR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:tR,cause:e})}},{handler:tR,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:tR})}),Ec=q(tt,async(e,t)=>{try{if(!Et){W(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lH});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(!Bt(r)){W(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:lH});return}if(!sH(i,a)){W(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:lH});return}K(t,200,ne,await cH(Et,r,i,a),{handler:lH})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lH,cause:e})}},{handler:lH,method:`GET`,skipBodyParse:!0}),Dc=q(Oe,async(e,t,n)=>{try{if(!Et){W(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:PR});return}if(!sH(n.path,n.kind)){W(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:PR});return}let e=Vq(Et,i);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;K(t,200,He,await LR(Et,n.branch,r,n.kind),{handler:PR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:PR,cause:e})}},{handler:PR,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:PR})}),Oc=q(ot,async(e,t,n)=>{if(rH(n,At).kind===`invalid-summary`){W(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:mH});return}if(!Et){W(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:mH});return}try{K(t,200,fr,await jo(()=>gH(Et,n.branch,{fastForward:n.fastForward===!0})),{handler:mH})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mH,cause:e})}},{handler:mH,method:`POST`});async function kc(e){let[t,...n]=St,r=[...n,...e];return await new Promise((e,n)=>{let i=Nc(t,r,NA({...Za,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},SR),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 ${SR}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=NR(Buffer.concat(c).toString(`utf-8`)).slice(0,500);J.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Ac=q(tt,async(e,t)=>{if(!mn.tryAcquire(`/api/share/publish/owners`)){W(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:yR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await kc([`share`,`owners`,`--json`]),n=ER(TR(e));MR(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),K(t,200,et,n,{handler:yR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yR,cause:e})}finally{mn.release(`/api/share/publish/owners`)}},{handler:yR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>GU(e,t,{handler:yR})}),jc=q(tt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!wR(r)||!CR(i)){W(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:bR});return}if(!mn.tryAcquire(`/api/share/publish/name-check`)){W(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:bR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await kc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=OR(TR(e));MR(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),K(t,200,Je,n,{handler:bR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:bR,cause:e})}finally{mn.release(`/api/share/publish/name-check`)}},{handler:bR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>GU(e,t,{handler:bR})}),Mc=q(dt,async(e,t,n)=>{if(!Et){MR(`publish-create`,`no-project`),K(t,200,pe,{ok:!1,error:`no-project`},{handler:xR});return}if(!wR(n.owner)||!CR(n.name)){W(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:xR});return}if(!mn.tryAcquire(`/api/share/publish`)){W(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:xR,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,Et,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await kc(e),i=jR(TR(r));MR(`publish-create`,i.ok?`ok`:i.error),i.ok&&bt?.()?.refreshRemote().catch(()=>{}),K(t,200,pe,i,{handler:xR})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xR,cause:e})}finally{mn.release(`/api/share/publish`)}},{handler:xR,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:xR})}),Pc=q(cr,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}K(t,200,Xe,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:`client-logs`})}),Fc=Et?aN(Et):null;async function Lc(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:Fc?Wo(Fc)?.port??0:0,singleFile:ln};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}K(t,200,dee,r,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}W(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let I=`local-op-embeddings-set-key`,Vc=`local-op-embeddings-clear-key`,Hc=`/api/local-op/embeddings`,Wc=q(kn,async(e,t,n)=>{if(!mn.tryAcquire(Hc)){W(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:I,extraHeaders:{"Retry-After":`5`}});return}try{await new yF(an).set(n.key),K(t,200,ri,{keyPresent:!0},{handler:I,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:I,cause:e})}finally{mn.release(Hc)}},{handler:I,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:I})}),Gc=q(tt,async(e,t)=>{if(!mn.tryAcquire(Hc)){W(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Vc,extraHeaders:{"Retry-After":`5`}});return}try{await bF(an),K(t,200,ri,{keyPresent:!1},{handler:Vc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Vc,cause:e})}finally{mn.release(Hc)}},{handler:Vc,method:`POST`,preBodyGate:(e,t)=>GU(e,t,{handler:Vc})}),Kc=q(tt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(nn){let t=nn.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=await new yF(an).get(),o=process.env.OK_EMBEDDINGS_API_KEY??null,s=a?`file`:o?`env`:null,l=s!==null,u=a??o,d=u&&u.length>=8?u.slice(-4):null,f=0;for(let[e]of c())!tS(e)&&!nS(e)&&!Ce(e)&&(f+=1);K(t,200,Ci,{enabled:e,keyPresent:l,keySource:s,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){W(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 qc(e,t){let n=cn?.()??Mn;try{return(await si(e,NL(i,n,{docName:t,onProblem:e=>J.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 J.warn({err:e,docName:t},`[lint] advisory lint pass failed post-write; omitting advisories`),[]}}let Jc=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!Zq(n))){W(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=cn?.()??Mn,a=[],o=jL(i,n??void 0,e=>a.push(e));K(t,200,hn,{effective:ML(r,o),configFile:o?.file??null,configProblems:a},{handler:`lint-config`})}catch(e){W(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}),Yc=q(_r,async(e,t,n)=>{let r;try{r=qL(R(i),n.ruleId,n.value)}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){W(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}try{let e=cn?.()??Mn,n=[],r=jL(i,void 0,e=>n.push(e));K(t,200,hn,{effective:ML(e,r),configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){W(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`}),Zc=e=>{let n=e.replace(/\.(md|mdx)$/i,``),r=t.documents.get(n);return r===void 0?null:r.getText(`source`).toString()},Qc=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!Zq(n)){W(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=Mq(i,n);if(r===null){W(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let a=cn?.()??Mn;K(t,200,Fr,await PL({projectDir:Et??i,contentDir:i,baseConfig:a,docRelPath:r,liveSourceFor:Zc}),{handler:`lint`})}catch(e){if(e instanceof CI){W(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}W(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),el=q(tt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!_q(r)){W(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let a=cn?.()??Mn;K(t,200,er,await IL({projectDir:Et??i,contentDir:i,baseConfig:a,targetPath:r,liveSourceFor:Zc}),{handler:`lint-audit`})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),tl=q(ti,async(t,r,a)=>{try{let t=Sq(a.docName,r,`lint-fix`);if(t===null)return;let o=$n(t),s=rH(a,At);if(s.kind===`invalid-summary`){W(r,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=s.kind===`anonymous`?`principal-anonymous`:s.writerId,l=s.kind===`anonymous`?`Anonymous`:s.displayName,u=s.kind===`anonymous`?c:s.colorSeed,d=s.kind===`agent`?s.clientName:void 0;if(tS(o)||nS(o)){W(r,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`lint-fix`});return}let f=Mq(i,o);if(f===null){W(r,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}Cq(R(i,f),i);let p=cn?.()??Mn,{stored:m}=wi(s.summary),h=await n.getSession(o,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await FL({projectDir:Et??i,contentDir:i,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=jn(d),n=Tn[t]??gr(u??c);gt?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:o,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{uC(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:o}:void 0)},h.origin),s.kind!==`anonymous`&&GD(o,c,l,u,void 0,s.kind===`agent`?_i({clientName:s.clientName,clientVersion:s.clientVersion,label:s.label}):s.actor,m)}finally{gt?.touchMode(c,`idle`)}let t=await vr(o);if(t?.kind===`failure`){br(r,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){xr(r,`lint-fix`);return}ur(o,`lint-fix`);try{b=await si(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,J.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;K(r,200,Dn,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof CI){W(r,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof kS){AS(r,e,`lint-fix`);return}if(e instanceof PS){IS(r,e,`lint-fix`);return}if(e instanceof mC){W(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}J.error({err:e},`[lint-fix] handler failed`),W(r,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),nl=`link-preview`,rl=new jU({cacheDir:ln?null:R(Et??i,`.ok`,`local`,`link-previews`)}),al=null,sl=()=>(al??=rl.init(),al),cl=fn??SU;async function ll(e){let t=await cl(e);return t.ok?{ok:!0,metadata:await DU({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:cl})}:{ok:!1,reason:t.reason}}let pl=()=>{try{return pn?.()===!0}catch{return!1}},ml={"/api/config":Lc,"/api/asset":Ta,"/api/asset-text":P,"/api/document":Gi,"/api/documents":Ki,"/api/backlinks":Xi,"/api/backlink-counts":Zi,"/api/link-preview":q(Kn,async(e,t,n)=>{try{if(!pl()){J.debug({outcome:`disabled`},`[link-preview] request outcome`),K(t,200,dn,{ok:!1,reason:`disabled`},{handler:nl});return}await sl();let e=!1,r=await rl.load(n.url,()=>(e=!0,ll(n.url)));rl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};J.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),K(t,200,dn,i,{handler:nl})}catch(e){W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:nl,cause:e})}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>{let n=PU({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?W(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:nl}):W(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:nl}),!1)}}),"/api/forward-links":Qi,"/api/link-graph":ea,"/api/dead-links":ia,"/api/orphans":ta,"/api/hubs":ra,"/api/tags":as,"/api/pages":Va,"/api/folder-config":fs,"/api/template":bs,"/api/template/import":xs,"/api/templates":hs,"/api/skill":Us,"/api/skill-file":Ys,"/api/skills":Is,"/api/skills/management":zs,"/api/skill/install":Xs,"/api/skill/uninstall":Zs,"/api/skill/restore":$s,"/api/skill/update":ec,"/api/skill-targets":Qs,"/api/search":xc,"/api/semantic-status":Kc,"/api/lint/config":Jc,"/api/lint/markdownlint-config":Yc,"/api/lint":Qc,"/api/lint/audit":el,"/api/lint/fix":tl,"/api/suggest-links":Ha,"/api/page-headings":Ia,"/api/create-page":ka,"/api/create-folder":Aa,"/api/duplicate-path":ja,"/api/rename-path":Ra,"/api/delete-path":za,"/api/trash/cleanup":Ba,"/api/upload":Wa,"/api/agent-write":zi,"/api/agent-write-md":Vi,"/api/agent-write-batch":Hi,"/api/frontmatter-patch":Ui,"/api/agent-patch":aa,"/api/agent-undo":oa,"/api/agent-activity":sa,"/api/agent-burst-diff":ca,"/api/save-version":da,"/api/history":fa,"/api/rollback":ma,"/api/metrics/reconciliation":ha,"/api/metrics/parse-health":ga,"/api/metrics/agent-presence":ba,"/api/metrics/agent-effects":xa,"/api/metrics/watcher-recent":Sa,"/api/__embed-detect":Ca,"/api/server-info":_a,"/api/acp/catalog":N,"/api/share/construct-url":Tc,"/api/share/target-status":Dc,"/api/git/branch-info":Ec,"/api/git/checkout":Oc,"/api/share/publish/owners":Ac,"/api/share/publish/name-check":jc,"/api/share/publish":Mc,"/api/principal":ya,"/api/rescue":Da,"/api/workspace":wa,"/api/sync/status":Jo,"/api/sync/trigger":Yo,"/api/sync/conflicts":Zo,"/api/sync/conflict-content":$o,"/api/sync/resolve-conflict":Qo,"/api/local-op/clone":to,"/api/local-op/ok-init":uo,"/api/local-op/auth/login":ko,"/api/local-op/auth/status":Io,"/api/local-op/auth/pat":Ro,"/api/local-op/auth/gh-login":Po,"/api/local-op/auth/repos":Bo,"/api/local-op/auth/signout":Uo,"/api/local-op/auth/set-identity":qo,"/api/local-op/embeddings/set-key":Wc,"/api/local-op/embeddings/clear-key":Gc,"/api/installed-agents":is,"/api/spawn-cursor":wc,"/api/handoff":Cc,"/api/install-skill":rs,"/api/skill/install-state":Sc,"/api/seed/plan":es,"/api/seed/apply":ts,"/api/seed/packs":ns,"/api/client-logs":Pc};_e&&(ml[`/api/test-reset`]=k,ml[`/api/test-flush-git`]=la,ml[`/api/test-rescan-backlinks`]=A,ml[`/api/test-rescan-files`]=ua);let gl=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),_l=[`/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};lae({ts:Date.now(),url:n,method:e.method??``,ua:r(`user-agent`),origin:r(`origin`),referer:r(`referer`),host:r(`host`),remote:e.socket?.remoteAddress,secChUa:r(`sec-ch-ua`),secChUaMobile:r(`sec-ch-ua-mobile`),secChUaPlatform:r(`sec-ch-ua-platform`),secFetchSite:r(`sec-fetch-site`),secFetchDest:r(`sec-fetch-dest`),secFetchMode:r(`sec-fetch-mode`),secFetchUser:r(`sec-fetch-user`)});let i=e.method??`GET`,a=n;n.startsWith(`/api/history/`)?a=`/api/history/:sha`:n.startsWith(`/api/tags/`)?a=`/api/tags/:name`:ml[n]||(a=`/api/*`);let o=n.startsWith(`/api/`)?mre(e):void 0;if(o!==void 0&&(hre(e,o),typeof t.setHeader==`function`&&t.setHeader(yS,o),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,J.info({event:`api.access`,requestId:o,method:i,route:a,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${i} ${a} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!nD(n)){W(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, ${yS}, ${Se.protocol}, ${Se.runtime}, ${Se.kind}`),t.setHeader(`Access-Control-Expose-Headers`,yS)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(gl.has(n)||_l.some(e=>n.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!yW(n)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(ln&&n.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!yW(n)){W(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!bW(e.headers.host)){W(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!n.startsWith(`/api/`))return;let s=Pa.extract(La.active(),e.headers),c=Xa(),l=Date.now();await La.with(s,()=>c.startActiveSpan(`HTTP ${i} ${a}`,{kind:Fa.SERVER,attributes:{[wo]:i,[xo]:a,[So]:n,[bo]:`http`,[yo]:e.headers[`user-agent`]??``,"ok.request.id":o}},async r=>{try{let a=ml[n],o=!1;if(a)o=!0,await a(e,t);else if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&(o=!0,await pa(e,t,r))}else if(n.startsWith(`/api/tags/`)){let r=n.slice(10);r&&(o=!0,await os(e,t,r))}o||W(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${i} ${n}`});let s=t.statusCode;r.setAttribute(Oo,s),s>=500&&r.setStatus({code:Na.ERROR,message:`status ${s}`})}catch(e){throw r.recordException(e),r.setStatus({code:Na.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&W(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:a,cause:e}),e}finally{r.end();let e=(Date.now()-l)/1e3;TK().record(e,{[wo]:i,[xo]:a,[Oo]:t.statusCode})}}))}}}function eJ(e){let t=e?.code;return typeof t==`string`?t:void 0}function tJ(e){let t;try{t=il(e.contentDir,{withFileTypes:!0})}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&uS(n.name,Bi)&&e.basenameIndex.add(n.name)}async function nJ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await wl(i,{withFileTypes:!0})}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=I(i,o.name),s=Sk(L(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Sl(a)}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Tl(a)}catch(t){let n=eJ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Ck(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await El(i)}catch(t){let n=eJ(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()&&uS(a,Yi)&&!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()&&uS(a,Yi)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}var rJ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const iJ=F(`conflict-storage`);var aJ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=I(aN(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!z(this.storePath)){this.conflicts=[];return}try{let e=B(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){iJ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){iJ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=Rc(this.storePath);z(e)||$c(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};fl(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){iJ.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-DluCIpMR.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=R(this.projectDir),r=R(t,e);if(!Ck(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);fl(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),iJ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await cO(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){iJ.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}),iJ.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 oJ(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function sJ(e,t){let n=aN(e);try{$c(n,{recursive:!0}),fl(I(n,de),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=To(e);$c(Rc(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};fl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const cJ=new Map;let lJ=!1;function uJ(e,t){try{let n=oJ(e,t);for(let e of cJ.keys())sJ(e,n)}catch{}}function dJ(e){cJ.set(e,(cJ.get(e)??0)+1),lJ||(lJ=!0,process.on(`uncaughtExceptionMonitor`,uJ));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=cJ.get(e)??0;n<=1?cJ.delete(e):cJ.set(e,n-1)}}}function fJ(e){let t=e.scheduler??m,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function pJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mJ(e){if(!z(e))return{};let t;try{t=(0,HE.parse)(B(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(!pJ(t))return{};let n=t.telemetry;if(!pJ(n))return{};let r=n.localSink;return pJ(r)?r:{}}function hJ(e){return typeof e==`boolean`?e:void 0}function gJ(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function _J(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function vJ(e){if(pJ(e))return gJ(e.maxBytes)}function yJ(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=mJ(Ga(`project`,e.projectDir)),n=mJ(Ga(`project-local`,e.projectDir));if((hJ(n.enabled)??hJ(t.enabled)??!0)===!1)return null;let r=vJ(n.spans)??vJ(t.spans)??52428800,i=vJ(n.logs)??vJ(t.logs)??26214400,a=_J(n.attributeDenylist)??_J(t.attributeDenylist)??ea;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var bJ;(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})(bJ||={});var xJ;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(xJ||={});const SJ=bJ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),CJ=e=>{switch(typeof e){case`undefined`:return SJ.undefined;case`string`:return SJ.string;case`number`:return Number.isNaN(e)?SJ.nan:SJ.number;case`boolean`:return SJ.boolean;case`function`:return SJ.function;case`bigint`:return SJ.bigint;case`symbol`:return SJ.symbol;case`object`:return Array.isArray(e)?SJ.array:e===null?SJ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?SJ.promise:typeof Map<`u`&&e instanceof Map?SJ.map:typeof Set<`u`&&e instanceof Set?SJ.set:typeof Date<`u`&&e instanceof Date?SJ.date:SJ.object;default:return SJ.unknown}},Y=bJ.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 wJ=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,bJ.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()}};wJ.create=e=>new wJ(e);const TJ=(e,t)=>{let n;switch(e.code){case Y.invalid_type:n=e.received===SJ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Y.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,bJ.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:n=`Unrecognized key(s) in object: ${bJ.joinValues(e.keys,`, `)}`;break;case Y.invalid_union:n=`Invalid input`;break;case Y.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${bJ.joinValues(e.options)}`;break;case Y.invalid_enum_value:n=`Invalid enum value. Expected ${bJ.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}"`:bJ.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,bJ.assertNever(e)}return{message:n}};let EJ=TJ;function DJ(){return EJ}const OJ=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=DJ(),r=OJ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===TJ?void 0:TJ].filter(e=>!!e)});e.common.issues.push(r)}var kJ=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 AJ;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 AJ;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 AJ=Object.freeze({status:`aborted`}),jJ=e=>({status:`dirty`,value:e}),MJ=e=>({status:`valid`,value:e}),NJ=e=>e.status===`aborted`,PJ=e=>e.status===`dirty`,FJ=e=>e.status===`valid`,IJ=e=>typeof Promise<`u`&&e instanceof Promise;var LJ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(LJ||={});var RJ=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 zJ=(e,t)=>{if(FJ(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 wJ(e.common.issues);return this._error=t,this._error}}};function BJ(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 VJ=class{get description(){return this._def.description}_getType(e){return CJ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:CJ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new kJ,ctx:{common:e.parent.common,data:e.data,parsedType:CJ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(IJ(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:CJ(e)};return zJ(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:CJ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return FJ(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=>FJ(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:CJ(e)},r=this._parse({data:e,path:n.path,parent:n});return zJ(n,await(IJ(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 UY({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 WY.create(this,this._def)}nullable(){return GY.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return wY.create(this)}promise(){return HY.create(this,this._def)}or(e){return DY.create([this,e],this._def)}and(e){return jY.create(this,e,this._def)}transform(e){return new UY({...BJ(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new KY({...BJ(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new YY({typeName:Z.ZodBranded,type:this,...BJ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new qY({...BJ(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 XY.create(this,e)}readonly(){return ZY.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const HJ=/^c[^\s-]{8,}$/i,UJ=/^[0-9a-z]+$/,WJ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GJ=/^[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,KJ=/^[a-z0-9_-]{21}$/i,qJ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,JJ=/^[-+]?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)?)??$/,YJ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let XJ;const ZJ=/^(?:(?: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])$/,QJ=/^(?:(?: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])$/,$J=/^(([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]))$/,eY=/^(([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])$/,tY=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nY=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rY=`((\\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])))`,iY=RegExp(`^${rY}$`);function aY(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 oY(e){return RegExp(`^${aY(e)}$`)}function sY(e){let t=`${rY}T${aY(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function cY(e,t){return!!((t===`v4`||!t)&&ZJ.test(e)||(t===`v6`||!t)&&$J.test(e))}function lY(e,t){if(!qJ.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 uY(e,t){return!!((t===`v4`||!t)&&QJ.test(e)||(t===`v6`||!t)&&eY.test(e))}var dY=class e extends VJ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==SJ.string){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.string,received:t.parsedType}),AJ}let t=new kJ,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`)YJ.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`)XJ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),XJ.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`)GJ.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`)KJ.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`)HJ.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`)UJ.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`)WJ.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`?sY(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`?iY.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:Y.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?oY(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`?JJ.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`duration`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?cY(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`?lY(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`?uY(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`?tY.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64`,code:Y.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?nY.test(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{validation:`base64url`,code:Y.invalid_string,message:r.message}),t.dirty()):bJ.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,...LJ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...LJ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...LJ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...LJ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...LJ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...LJ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...LJ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...LJ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...LJ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...LJ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...LJ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...LJ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...LJ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...LJ.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,...LJ.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,...LJ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...LJ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...LJ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...LJ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...LJ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...LJ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...LJ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...LJ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...LJ.errToObj(t)})}nonempty(e){return this.min(1,LJ.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}};dY.create=e=>new dY({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...BJ(e)});function fY(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 pY=class e extends VJ{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)!==SJ.number){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.number,received:t.parsedType}),AJ}let t,n=new kJ;for(let r of this._def.checks)r.kind===`int`?bJ.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`?fY(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()):bJ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,LJ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,LJ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,LJ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,LJ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:LJ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:LJ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:LJ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:LJ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:LJ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:LJ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:LJ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:LJ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:LJ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:LJ.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`&&bJ.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)}};pY.create=e=>new pY({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...BJ(e)});var mY=class e extends VJ{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)!==SJ.bigint)return this._getInvalidInput(e);let t,n=new kJ;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()):bJ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.bigint,received:t.parsedType}),AJ}gte(e,t){return this.setLimit(`min`,e,!0,LJ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,LJ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,LJ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,LJ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:LJ.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:LJ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:LJ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:LJ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:LJ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:LJ.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}};mY.create=e=>new mY({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...BJ(e)});var hY=class extends VJ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==SJ.boolean){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.boolean,received:t.parsedType}),AJ}return MJ(e.data)}};hY.create=e=>new hY({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...BJ(e)});var gY=class e extends VJ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==SJ.date){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.date,received:t.parsedType}),AJ}if(Number.isNaN(e.data.getTime()))return X(this._getOrReturnCtx(e),{code:Y.invalid_date}),AJ;let t=new kJ,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()):bJ.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:LJ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:LJ.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)}};gY.create=e=>new gY({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...BJ(e)});var _Y=class extends VJ{_parse(e){if(this._getType(e)!==SJ.symbol){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.symbol,received:t.parsedType}),AJ}return MJ(e.data)}};_Y.create=e=>new _Y({typeName:Z.ZodSymbol,...BJ(e)});var vY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.undefined,received:t.parsedType}),AJ}return MJ(e.data)}};vY.create=e=>new vY({typeName:Z.ZodUndefined,...BJ(e)});var yY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.null){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.null,received:t.parsedType}),AJ}return MJ(e.data)}};yY.create=e=>new yY({typeName:Z.ZodNull,...BJ(e)});var bY=class extends VJ{constructor(){super(...arguments),this._any=!0}_parse(e){return MJ(e.data)}};bY.create=e=>new bY({typeName:Z.ZodAny,...BJ(e)});var xY=class extends VJ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return MJ(e.data)}};xY.create=e=>new xY({typeName:Z.ZodUnknown,...BJ(e)});var SY=class extends VJ{_parse(e){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.never,received:t.parsedType}),AJ}};SY.create=e=>new SY({typeName:Z.ZodNever,...BJ(e)});var CY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.undefined){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.void,received:t.parsedType}),AJ}return MJ(e.data)}};CY.create=e=>new CY({typeName:Z.ZodVoid,...BJ(e)});var wY=class e extends VJ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==SJ.array)return X(t,{code:Y.invalid_type,expected:SJ.array,received:t.parsedType}),AJ;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 RJ(t,e,t.path,n)))).then(e=>kJ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new RJ(t,e,t.path,n)));return kJ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:LJ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:LJ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:LJ.toString(n)}})}nonempty(e){return this.min(1,e)}};wY.create=(e,t)=>new wY({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...BJ(t)});function TY(e){if(e instanceof EY){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=WY.create(TY(r))}return new EY({...e._def,shape:()=>t})}else if(e instanceof wY)return new wY({...e._def,type:TY(e.element)});else if(e instanceof WY)return WY.create(TY(e.unwrap()));else if(e instanceof GY)return GY.create(TY(e.unwrap()));else if(e instanceof MY)return MY.create(e.items.map(e=>TY(e)));else return e}var EY=class e extends VJ{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=bJ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==SJ.object){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.object,received:t.parsedType}),AJ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof SY&&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 RJ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof SY){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 RJ(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=>kJ.mergeObjectSync(t,e)):kJ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return LJ.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:LJ.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 bJ.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 bJ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return TY(this)}partial(t){let n={};for(let e of bJ.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 bJ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof WY;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return zY(bJ.objectKeys(this.shape))}};EY.create=(e,t)=>new EY({shape:()=>e,unknownKeys:`strip`,catchall:SY.create(),typeName:Z.ZodObject,...BJ(t)}),EY.strictCreate=(e,t)=>new EY({shape:()=>e,unknownKeys:`strict`,catchall:SY.create(),typeName:Z.ZodObject,...BJ(t)}),EY.lazycreate=(e,t)=>new EY({shape:e,unknownKeys:`strip`,catchall:SY.create(),typeName:Z.ZodObject,...BJ(t)});var DY=class extends VJ{_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 wJ(e.ctx.common.issues));return X(t,{code:Y.invalid_union,unionErrors:n}),AJ}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 wJ(e));return X(t,{code:Y.invalid_union,unionErrors:i}),AJ}}get options(){return this._def.options}};DY.create=(e,t)=>new DY({options:e,typeName:Z.ZodUnion,...BJ(t)});const OY=e=>e instanceof LY?OY(e.schema):e instanceof UY?OY(e.innerType()):e instanceof RY?[e.value]:e instanceof BY?e.options:e instanceof VY?bJ.objectValues(e.enum):e instanceof KY?OY(e._def.innerType):e instanceof vY?[void 0]:e instanceof yY?[null]:e instanceof WY?[void 0,...OY(e.unwrap())]:e instanceof GY?[null,...OY(e.unwrap())]:e instanceof YY||e instanceof ZY?OY(e.unwrap()):e instanceof qY?OY(e._def.innerType):[];var kY=class e extends VJ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==SJ.object)return X(t,{code:Y.invalid_type,expected:SJ.object,received:t.parsedType}),AJ;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]}),AJ)}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=OY(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,...BJ(r)})}};function AY(e,t){let n=CJ(e),r=CJ(t);if(e===t)return{valid:!0,data:e};if(n===SJ.object&&r===SJ.object){let n=bJ.objectKeys(t),r=bJ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=AY(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===SJ.array&&r===SJ.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=AY(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===SJ.date&&r===SJ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var jY=class extends VJ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(NJ(e)||NJ(r))return AJ;let i=AY(e.value,r.value);return i.valid?((PJ(e)||PJ(r))&&t.dirty(),{status:t.value,value:i.data}):(X(n,{code:Y.invalid_intersection_types}),AJ)};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}))}};jY.create=(e,t,n)=>new jY({left:e,right:t,typeName:Z.ZodIntersection,...BJ(n)});var MY=class e extends VJ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==SJ.array)return X(n,{code:Y.invalid_type,expected:SJ.array,received:n.parsedType}),AJ;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`}),AJ;!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 RJ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>kJ.mergeArray(t,e)):kJ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};MY.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new MY({items:e,typeName:Z.ZodTuple,rest:null,...BJ(t)})};var NY=class e extends VJ{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!==SJ.object)return X(n,{code:Y.invalid_type,expected:SJ.object,received:n.parsedType}),AJ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new RJ(n,e,n.path,e)),value:a._parse(new RJ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?kJ.mergeObjectAsync(t,r):kJ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof VJ?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...BJ(r)}):new e({keyType:dY.create(),valueType:t,typeName:Z.ZodRecord,...BJ(n)})}},PY=class extends VJ{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!==SJ.map)return X(n,{code:Y.invalid_type,expected:SJ.map,received:n.parsedType}),AJ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new RJ(n,e,n.path,[a,`key`])),value:i._parse(new RJ(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 AJ;(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 AJ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};PY.create=(e,t,n)=>new PY({valueType:t,keyType:e,typeName:Z.ZodMap,...BJ(n)});var FY=class e extends VJ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==SJ.set)return X(n,{code:Y.invalid_type,expected:SJ.set,received:n.parsedType}),AJ;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 AJ;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 RJ(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:LJ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:LJ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};FY.create=(e,t)=>new FY({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...BJ(t)});var IY=class e extends VJ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==SJ.function)return X(t,{code:Y.invalid_type,expected:SJ.function,received:t.parsedType}),AJ;function n(e,n){return OJ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,DJ(),TJ].filter(e=>!!e),issueData:{code:Y.invalid_arguments,argumentsError:n}})}function r(e,n){return OJ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,DJ(),TJ].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 HY){let e=this;return MJ(async function(...t){let o=new wJ([]),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 MJ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new wJ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new wJ([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:MY.create(t).rest(xY.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||MY.create([]).rest(xY.create()),returns:n||xY.create(),typeName:Z.ZodFunction,...BJ(r)})}},LY=class extends VJ{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})}};LY.create=(e,t)=>new LY({getter:e,typeName:Z.ZodLazy,...BJ(t)});var RY=class extends VJ{_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}),AJ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};RY.create=(e,t)=>new RY({value:e,typeName:Z.ZodLiteral,...BJ(t)});function zY(e,t){return new BY({values:e,typeName:Z.ZodEnum,...BJ(t)})}var BY=class e extends VJ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return X(t,{expected:bJ.joinValues(n),received:t.parsedType,code:Y.invalid_type}),AJ}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}),AJ}return MJ(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})}};BY.create=zY;var VY=class extends VJ{_parse(e){let t=bJ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==SJ.string&&n.parsedType!==SJ.number){let e=bJ.objectValues(t);return X(n,{expected:bJ.joinValues(e),received:n.parsedType,code:Y.invalid_type}),AJ}if(this._cache||=new Set(bJ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=bJ.objectValues(t);return X(n,{received:n.data,code:Y.invalid_enum_value,options:e}),AJ}return MJ(e.data)}get enum(){return this._def.values}};VY.create=(e,t)=>new VY({values:e,typeName:Z.ZodNativeEnum,...BJ(t)});var HY=class extends VJ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==SJ.promise&&t.common.async===!1?(X(t,{code:Y.invalid_type,expected:SJ.promise,received:t.parsedType}),AJ):MJ((t.parsedType===SJ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};HY.create=(e,t)=>new HY({type:e,typeName:Z.ZodPromise,...BJ(t)});var UY=class extends VJ{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 AJ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?AJ:r.status===`dirty`||t.value===`dirty`?jJ(r.value):r});{if(t.value===`aborted`)return AJ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?AJ:r.status===`dirty`||t.value===`dirty`?jJ(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`?AJ:(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`?AJ:(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(!FJ(e))return AJ;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=>FJ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):AJ);bJ.assertNever(r)}};UY.create=(e,t,n)=>new UY({schema:e,typeName:Z.ZodEffects,effect:t,...BJ(n)}),UY.createWithPreprocess=(e,t,n)=>new UY({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...BJ(n)});var WY=class extends VJ{_parse(e){return this._getType(e)===SJ.undefined?MJ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};WY.create=(e,t)=>new WY({innerType:e,typeName:Z.ZodOptional,...BJ(t)});var GY=class extends VJ{_parse(e){return this._getType(e)===SJ.null?MJ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};GY.create=(e,t)=>new GY({innerType:e,typeName:Z.ZodNullable,...BJ(t)});var KY=class extends VJ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===SJ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};KY.create=(e,t)=>new KY({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...BJ(t)});var qY=class extends VJ{_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 IJ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new wJ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new wJ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};qY.create=(e,t)=>new qY({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...BJ(t)});var JY=class extends VJ{_parse(e){if(this._getType(e)!==SJ.nan){let t=this._getOrReturnCtx(e);return X(t,{code:Y.invalid_type,expected:SJ.nan,received:t.parsedType}),AJ}return{status:`valid`,value:e.data}}};JY.create=e=>new JY({typeName:Z.ZodNaN,...BJ(e)});var YY=class extends VJ{_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}},XY=class e extends VJ{_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`?AJ:e.status===`dirty`?(t.dirty(),jJ(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`?AJ: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})}},ZY=class extends VJ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(FJ(e)&&(e.value=Object.freeze(e.value)),e);return IJ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};ZY.create=(e,t)=>new ZY({innerType:e,typeName:Z.ZodReadonly,...BJ(t)}),EY.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||={}),dY.create,pY.create,JY.create,mY.create,hY.create,gY.create,_Y.create,vY.create,yY.create,bY.create,xY.create,SY.create,CY.create,wY.create;const QY=EY.create;EY.strictCreate,DY.create,kY.create,jY.create,MY.create,NY.create,PY.create,FY.create,IY.create,LY.create,RY.create,BY.create,VY.create,HY.create,UY.create,WY.create,GY.create,UY.createWithPreprocess,XY.create;const $Y=Ui(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Da.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>ja(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Aa(e,t,n),e.parseAsync=async(t,n)=>la(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ta(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)=>ka(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),eX=Ui(`ZodMiniObject`,(e,t)=>{ca.init(e,t),$Y.init(e,t),ra(e,`shape`,()=>t.shape)});function tX(e,t){return new eX({type:`object`,shape:e??{},...Wi(t)})}function nX(e){return!!e._zod}function rX(e){let t=Object.values(e);if(t.length===0)return tX({});let n=t.every(nX),r=t.every(e=>!nX(e));if(n)return tX(e);if(r)return QY(e);throw Error(`Mixed Zod versions detected in object shape.`)}function iX(e,t){return nX(e)?Aa(e,t):e.safeParse(t)}async function aX(e,t){return nX(e)?await ta(e,t):await e.safeParseAsync(t)}function oX(e){if(!e)return;let t;if(t=nX(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function sX(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 rX(e)}}if(nX(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 cX(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 lX(e){return e.description}function uX(e){if(nX(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function dX(e){if(nX(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 fX=`2025-11-25`,pX=[fX,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],mX=`io.modelcontextprotocol/related-task`,hX=oa(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),gX=P([M(),j().int()]),_X=M();Ca({ttl:j().optional(),pollInterval:j().optional()});const vX=O({ttl:j().optional()}),yX=O({taskId:M()}),bX=Ca({progressToken:gX.optional(),[mX]:yX.optional()}),xX=O({_meta:bX.optional()}),SX=xX.extend({task:vX.optional()}),CX=e=>SX.safeParse(e).success,wX=O({method:M(),params:xX.loose().optional()}),TX=O({_meta:bX.optional()}),EX=O({method:M(),params:TX.loose().optional()}),DX=Ca({_meta:bX.optional()}),OX=P([M(),j().int()]),kX=O({jsonrpc:N(`2.0`),id:OX,...wX.shape}).strict(),AX=e=>kX.safeParse(e).success,jX=O({jsonrpc:N(`2.0`),...EX.shape}).strict(),MX=e=>jX.safeParse(e).success,NX=O({jsonrpc:N(`2.0`),id:OX,result:DX}).strict(),PX=e=>NX.safeParse(e).success;var FX;(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`})(FX||={});const IX=O({jsonrpc:N(`2.0`),id:OX.optional(),error:O({code:j().int(),message:M(),data:A().optional()})}).strict(),LX=e=>IX.safeParse(e).success,RX=P([kX,jX,NX,IX]);P([NX,IX]);const zX=DX.strict(),BX=TX.extend({requestId:OX.optional(),reason:M().optional()}),VX=EX.extend({method:N(`notifications/cancelled`),params:BX}),HX=O({icons:D(O({src:M(),mimeType:M().optional(),sizes:D(M()).optional(),theme:Ji([`light`,`dark`]).optional()})).optional()}),UX=O({name:M(),title:M().optional()}),WX=UX.extend({...UX.shape,...HX.shape,version:M(),websiteUrl:M().optional(),description:M().optional()}),GX=wa(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ua(O({form:ua(O({applyDefaults:E().optional()}),k(M(),A())).optional(),url:hX.optional()}),k(M(),A()).optional())),KX=Ca({list:hX.optional(),cancel:hX.optional(),requests:Ca({sampling:Ca({createMessage:hX.optional()}).optional(),elicitation:Ca({create:hX.optional()}).optional()}).optional()}),qX=Ca({list:hX.optional(),cancel:hX.optional(),requests:Ca({tools:Ca({call:hX.optional()}).optional()}).optional()}),JX=O({experimental:k(M(),hX).optional(),sampling:O({context:hX.optional(),tools:hX.optional()}).optional(),elicitation:GX.optional(),roots:O({listChanged:E().optional()}).optional(),tasks:KX.optional(),extensions:k(M(),hX).optional()}),YX=xX.extend({protocolVersion:M(),capabilities:JX,clientInfo:WX}),XX=wX.extend({method:N(`initialize`),params:YX}),ZX=e=>XX.safeParse(e).success,QX=O({experimental:k(M(),hX).optional(),logging:hX.optional(),completions:hX.optional(),prompts:O({listChanged:E().optional()}).optional(),resources:O({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:O({listChanged:E().optional()}).optional(),tasks:qX.optional(),extensions:k(M(),hX).optional()}),$X=DX.extend({protocolVersion:M(),capabilities:QX,serverInfo:WX,instructions:M().optional()}),eZ=EX.extend({method:N(`notifications/initialized`),params:TX.optional()}),tZ=e=>eZ.safeParse(e).success,nZ=wX.extend({method:N(`ping`),params:xX.optional()}),rZ=O({progress:j(),total:ya(j()),message:ya(M())}),iZ=O({...TX.shape,...rZ.shape,progressToken:gX}),aZ=EX.extend({method:N(`notifications/progress`),params:iZ}),oZ=xX.extend({cursor:_X.optional()}),sZ=wX.extend({params:oZ.optional()}),cZ=DX.extend({nextCursor:_X.optional()}),lZ=Ji([`working`,`input_required`,`completed`,`failed`,`cancelled`]),uZ=O({taskId:M(),status:lZ,ttl:P([j(),xa()]),createdAt:M(),lastUpdatedAt:M(),pollInterval:ya(j()),statusMessage:ya(M())}),dZ=DX.extend({task:uZ}),fZ=TX.merge(uZ),pZ=EX.extend({method:N(`notifications/tasks/status`),params:fZ}),mZ=wX.extend({method:N(`tasks/get`),params:xX.extend({taskId:M()})}),hZ=DX.merge(uZ),gZ=wX.extend({method:N(`tasks/result`),params:xX.extend({taskId:M()})});DX.loose();const _Z=sZ.extend({method:N(`tasks/list`)}),vZ=cZ.extend({tasks:D(uZ)}),yZ=wX.extend({method:N(`tasks/cancel`),params:xX.extend({taskId:M()})}),bZ=DX.merge(uZ),xZ=O({uri:M(),mimeType:ya(M()),_meta:k(M(),A()).optional()}),SZ=xZ.extend({text:M()}),CZ=M().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),wZ=xZ.extend({blob:CZ}),TZ=Ji([`user`,`assistant`]),EZ=O({audience:D(TZ).optional(),priority:j().min(0).max(1).optional(),lastModified:ba({offset:!0}).optional()}),DZ=O({...UX.shape,...HX.shape,uri:M(),description:ya(M()),mimeType:ya(M()),size:ya(j()),annotations:EZ.optional(),_meta:ya(Ca({}))}),OZ=O({...UX.shape,...HX.shape,uriTemplate:M(),description:ya(M()),mimeType:ya(M()),annotations:EZ.optional(),_meta:ya(Ca({}))}),kZ=sZ.extend({method:N(`resources/list`)}),AZ=cZ.extend({resources:D(DZ)}),jZ=sZ.extend({method:N(`resources/templates/list`)}),MZ=cZ.extend({resourceTemplates:D(OZ)}),NZ=xX.extend({uri:M()}),PZ=NZ,FZ=wX.extend({method:N(`resources/read`),params:PZ}),IZ=DX.extend({contents:D(P([SZ,wZ]))}),LZ=EX.extend({method:N(`notifications/resources/list_changed`),params:TX.optional()}),RZ=NZ,zZ=wX.extend({method:N(`resources/subscribe`),params:RZ}),BZ=NZ,VZ=wX.extend({method:N(`resources/unsubscribe`),params:BZ}),HZ=TX.extend({uri:M()}),UZ=EX.extend({method:N(`notifications/resources/updated`),params:HZ}),WZ=O({name:M(),description:ya(M()),required:ya(E())}),GZ=O({...UX.shape,...HX.shape,description:ya(M()),arguments:ya(D(WZ)),_meta:ya(Ca({}))}),KZ=sZ.extend({method:N(`prompts/list`)}),qZ=cZ.extend({prompts:D(GZ)}),JZ=xX.extend({name:M(),arguments:k(M(),M()).optional()}),YZ=wX.extend({method:N(`prompts/get`),params:JZ}),XZ=O({type:N(`text`),text:M(),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),ZZ=O({type:N(`image`),data:CZ,mimeType:M(),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),QZ=O({type:N(`audio`),data:CZ,mimeType:M(),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),$Z=O({type:N(`tool_use`),name:M(),id:M(),input:k(M(),A()),_meta:k(M(),A()).optional()}),eQ=O({type:N(`resource`),resource:P([SZ,wZ]),annotations:EZ.optional(),_meta:k(M(),A()).optional()}),tQ=P([XZ,ZZ,QZ,DZ.extend({type:N(`resource_link`)}),eQ]),nQ=O({role:TZ,content:tQ}),rQ=DX.extend({description:M().optional(),messages:D(nQ)}),iQ=EX.extend({method:N(`notifications/prompts/list_changed`),params:TX.optional()}),aQ=O({title:M().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),oQ=O({taskSupport:Ji([`required`,`optional`,`forbidden`]).optional()}),sQ=O({...UX.shape,...HX.shape,description:M().optional(),inputSchema:O({type:N(`object`),properties:k(M(),hX).optional(),required:D(M()).optional()}).catchall(A()),outputSchema:O({type:N(`object`),properties:k(M(),hX).optional(),required:D(M()).optional()}).catchall(A()).optional(),annotations:aQ.optional(),execution:oQ.optional(),_meta:k(M(),A()).optional()}),cQ=sZ.extend({method:N(`tools/list`)}),lQ=cZ.extend({tools:D(sQ)}),uQ=DX.extend({content:D(tQ).default([]),structuredContent:k(M(),A()).optional(),isError:E().optional()});uQ.or(DX.extend({toolResult:A()}));const dQ=SX.extend({name:M(),arguments:k(M(),A()).optional()}),fQ=wX.extend({method:N(`tools/call`),params:dQ}),pQ=EX.extend({method:N(`notifications/tools/list_changed`),params:TX.optional()});O({autoRefresh:E().default(!0),debounceMs:j().int().nonnegative().default(300)});const mQ=Ji([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),hQ=xX.extend({level:mQ}),gQ=wX.extend({method:N(`logging/setLevel`),params:hQ}),_Q=TX.extend({level:mQ,logger:M().optional(),data:A()}),vQ=EX.extend({method:N(`notifications/message`),params:_Q}),yQ=O({hints:D(O({name:M().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),bQ=O({mode:Ji([`auto`,`required`,`none`]).optional()}),xQ=O({type:N(`tool_result`),toolUseId:M().describe(`The unique identifier for the corresponding tool call.`),content:D(tQ).default([]),structuredContent:O({}).loose().optional(),isError:E().optional(),_meta:k(M(),A()).optional()}),SQ=Qi(`type`,[XZ,ZZ,QZ]),CQ=Qi(`type`,[XZ,ZZ,QZ,$Z,xQ]),wQ=O({role:TZ,content:P([CQ,D(CQ)]),_meta:k(M(),A()).optional()}),TQ=SX.extend({messages:D(wQ),modelPreferences:yQ.optional(),systemPrompt:M().optional(),includeContext:Ji([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:D(M()).optional(),metadata:hX.optional(),tools:D(sQ).optional(),toolChoice:bQ.optional()}),EQ=wX.extend({method:N(`sampling/createMessage`),params:TQ}),DQ=DX.extend({model:M(),stopReason:ya(Ji([`endTurn`,`stopSequence`,`maxTokens`]).or(M())),role:TZ,content:SQ}),OQ=DX.extend({model:M(),stopReason:ya(Ji([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(M())),role:TZ,content:P([CQ,D(CQ)])}),kQ=O({type:N(`boolean`),title:M().optional(),description:M().optional(),default:E().optional()}),AQ=O({type:N(`string`),title:M().optional(),description:M().optional(),minLength:j().optional(),maxLength:j().optional(),format:Ji([`email`,`uri`,`date`,`date-time`]).optional(),default:M().optional()}),jQ=O({type:Ji([`number`,`integer`]),title:M().optional(),description:M().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),MQ=O({type:N(`string`),title:M().optional(),description:M().optional(),enum:D(M()),default:M().optional()}),NQ=O({type:N(`string`),title:M().optional(),description:M().optional(),oneOf:D(O({const:M(),title:M()})),default:M().optional()}),PQ=P([P([O({type:N(`string`),title:M().optional(),description:M().optional(),enum:D(M()),enumNames:D(M()).optional(),default:M().optional()}),P([MQ,NQ]),P([O({type:N(`array`),title:M().optional(),description:M().optional(),minItems:j().optional(),maxItems:j().optional(),items:O({type:N(`string`),enum:D(M())}),default:D(M()).optional()}),O({type:N(`array`),title:M().optional(),description:M().optional(),minItems:j().optional(),maxItems:j().optional(),items:O({anyOf:D(O({const:M(),title:M()}))}),default:D(M()).optional()})])]),kQ,AQ,jQ]),FQ=P([SX.extend({mode:N(`form`).optional(),message:M(),requestedSchema:O({type:N(`object`),properties:k(M(),PQ),required:D(M()).optional()})}),SX.extend({mode:N(`url`),message:M(),elicitationId:M(),url:M().url()})]),IQ=wX.extend({method:N(`elicitation/create`),params:FQ}),LQ=TX.extend({elicitationId:M()}),RQ=EX.extend({method:N(`notifications/elicitation/complete`),params:LQ}),zQ=DX.extend({action:Ji([`accept`,`decline`,`cancel`]),content:wa(e=>e===null?void 0:e,k(M(),P([M(),j(),E(),D(M())])).optional())}),BQ=O({type:N(`ref/resource`),uri:M()}),VQ=O({type:N(`ref/prompt`),name:M()}),HQ=xX.extend({ref:P([VQ,BQ]),argument:O({name:M(),value:M()}),context:O({arguments:k(M(),M()).optional()}).optional()}),UQ=wX.extend({method:N(`completion/complete`),params:HQ});function WQ(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function GQ(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const KQ=DX.extend({completion:Ca({values:D(M()).max(100),total:ya(j().int()),hasMore:ya(E())})}),qQ=O({uri:M().startsWith(`file://`),name:M().optional(),_meta:k(M(),A()).optional()}),JQ=wX.extend({method:N(`roots/list`),params:xX.optional()}),YQ=DX.extend({roots:D(qQ)}),XQ=EX.extend({method:N(`notifications/roots/list_changed`),params:TX.optional()});P([nZ,XX,UQ,gQ,YZ,KZ,kZ,jZ,FZ,zZ,VZ,fQ,cQ,mZ,gZ,_Z,yZ]),P([VX,aZ,eZ,XQ,pZ]),P([zX,DQ,OQ,zQ,YQ,hZ,vZ,dZ]),P([nZ,EQ,IQ,JQ,mZ,gZ,_Z,yZ]),P([VX,aZ,vQ,UZ,LZ,pQ,iQ,pZ,RQ]),P([zX,$X,KQ,rQ,qZ,AZ,MZ,IZ,uQ,lQ,hZ,vZ,dZ]);var ZQ=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===FX.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new QQ(e.elicitations,n)}return new e(t,n,r)}},QQ=class extends ZQ{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(FX.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function $Q(e){return e===`completed`||e===`failed`||e===`cancelled`}const e$=Symbol(`Let zodToJsonSchema decide on which parser to use`),t$={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`},n$=e=>typeof e==`string`?{...t$,name:e}:{...t$,...e},r$=e=>{let t=n$(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 i$(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function a$(e,t,n,r,i){e[t]=n,i$(e,t,r,i)}const o$=(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 s$(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?o$(t,e.currentPath):t.join(`/`)}}function c$(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=Q$(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&a$(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&a$(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(a$(n,`minItems`,e.exactLength.value,e.exactLength.message,t),a$(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function l$(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?a$(n,`minimum`,r.value,r.message,t):a$(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),a$(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?a$(n,`maximum`,r.value,r.message,t):a$(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),a$(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:a$(n,`multipleOf`,r.value,r.message,t);break}return n}function u$(){return{type:`boolean`}}function d$(e,t){return Q$(e.type._def,t)}const f$=(e,t)=>Q$(e.innerType._def,t);function p$(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>p$(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 m$(e,t)}}const m$=(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`:a$(n,`minimum`,r.value,r.message,t);break;case`max`:a$(n,`maximum`,r.value,r.message,t);break}return n};function h$(e,t){return{...Q$(e.innerType._def,t),default:e.defaultValue()}}function g$(e,t){return t.effectStrategy===`input`?Q$(e.schema._def,t):s$(t)}function _$(e){return{type:`string`,enum:Array.from(e.values)}}const v$=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function y$(e,t){let n=[Q$(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Q$(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(v$(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 b$(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 x$;const S$={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:()=>(x$===void 0&&(x$=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),x$),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 C$(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:a$(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:a$(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`:D$(n,`email`,r.message,t);break;case`format:idn-email`:D$(n,`idn-email`,r.message,t);break;case`pattern:zod`:O$(n,S$.email,r.message,t);break}break;case`url`:D$(n,`uri`,r.message,t);break;case`uuid`:D$(n,`uuid`,r.message,t);break;case`regex`:O$(n,r.regex,r.message,t);break;case`cuid`:O$(n,S$.cuid,r.message,t);break;case`cuid2`:O$(n,S$.cuid2,r.message,t);break;case`startsWith`:O$(n,RegExp(`^${w$(r.value,t)}`),r.message,t);break;case`endsWith`:O$(n,RegExp(`${w$(r.value,t)}$`),r.message,t);break;case`datetime`:D$(n,`date-time`,r.message,t);break;case`date`:D$(n,`date`,r.message,t);break;case`time`:D$(n,`time`,r.message,t);break;case`duration`:D$(n,`duration`,r.message,t);break;case`length`:a$(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),a$(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:O$(n,RegExp(w$(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&D$(n,`ipv4`,r.message,t),r.version!==`v4`&&D$(n,`ipv6`,r.message,t);break;case`base64url`:O$(n,S$.base64url,r.message,t);break;case`jwt`:O$(n,S$.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&O$(n,S$.ipv4Cidr,r.message,t),r.version!==`v4`&&O$(n,S$.ipv6Cidr,r.message,t);break;case`emoji`:O$(n,S$.emoji(),r.message,t);break;case`ulid`:O$(n,S$.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:D$(n,`binary`,r.message,t);break;case`contentEncoding:base64`:a$(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:O$(n,S$.base64,r.message,t);break}break;case`nanoid`:O$(n,S$.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function w$(e,t){return t.patternStrategy===`escape`?E$(e):e}const T$=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function E$(e){let t=``;for(let n=0;n<e.length;n++)T$.has(e[n])||(t+=`\\`),t+=e[n];return t}function D$(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}}})):a$(e,`format`,t,n,r)}function O$(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:k$(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):a$(e,`pattern`,k$(t,r),n,r)}function k$(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
1227
1227
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1228
1228
  ]))`;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 A$(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]:Q$(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??s$(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Q$(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}=C$(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}=d$(e.keyType._def,t);return{...n,propertyNames:i}}return n}function j$(e,t){return t.mapStrategy===`record`?A$(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Q$(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||s$(t),Q$(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||s$(t)],minItems:2,maxItems:2}}}function M$(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 N$(e){return e.target===`openAi`?void 0:{not:s$({...e,currentPath:[...e.currentPath,`not`]})}}function P$(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const F$={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function I$(e,t){if(t.target===`openApi3`)return L$(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in F$&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=F$[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 L$(e,t)}const L$=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Q$(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 R$(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:F$[e.innerType._def.typeName],nullable:!0}:{type:[F$[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Q$(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Q$(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function z$(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`,i$(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?a$(n,`minimum`,r.value,r.message,t):a$(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),a$(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?a$(n,`maximum`,r.value,r.message,t):a$(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),a$(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:a$(n,`multipleOf`,r.value,r.message,t);break}return n}function B$(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=H$(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Q$(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=V$(e,t);return o!==void 0&&(r.additionalProperties=o),r}function V$(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Q$(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 H$(e){try{return e.isOptional()}catch{return!0}}const U$=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Q$(e.innerType._def,t);let n=Q$(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:s$(t)},n]}:s$(t)},W$=(e,t)=>{if(t.pipeStrategy===`input`)return Q$(e.in._def,t);if(t.pipeStrategy===`output`)return Q$(e.out._def,t);let n=Q$(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Q$(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function G$(e,t){return Q$(e.type._def,t)}function K$(e,t){let n={type:`array`,uniqueItems:!0,items:Q$(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&a$(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&a$(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function q$(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Q$(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Q$(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Q$(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function J$(e){return{not:s$(e)}}function Y$(e){return s$(e)}const X$=(e,t)=>Q$(e.innerType._def,t),Z$=(e,t,n)=>{switch(t){case Z.ZodString:return C$(e,n);case Z.ZodNumber:return z$(e,n);case Z.ZodObject:return B$(e,n);case Z.ZodBigInt:return l$(e,n);case Z.ZodBoolean:return u$();case Z.ZodDate:return p$(e,n);case Z.ZodUndefined:return J$(n);case Z.ZodNull:return P$(n);case Z.ZodArray:return c$(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return I$(e,n);case Z.ZodIntersection:return y$(e,n);case Z.ZodTuple:return q$(e,n);case Z.ZodRecord:return A$(e,n);case Z.ZodLiteral:return b$(e,n);case Z.ZodEnum:return _$(e);case Z.ZodNativeEnum:return M$(e);case Z.ZodNullable:return R$(e,n);case Z.ZodOptional:return U$(e,n);case Z.ZodMap:return j$(e,n);case Z.ZodSet:return K$(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return G$(e,n);case Z.ZodNaN:case Z.ZodNever:return N$(n);case Z.ZodEffects:return g$(e,n);case Z.ZodAny:return s$(n);case Z.ZodUnknown:return Y$(n);case Z.ZodDefault:return h$(e,n);case Z.ZodBranded:return d$(e,n);case Z.ZodReadonly:return X$(e,n);case Z.ZodCatch:return f$(e,n);case Z.ZodPipeline:return W$(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>void 0)(t)}};function Q$(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==e$)return i}if(r&&!n){let e=$$(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=Z$(e,e.typeName,t),o=typeof a==`function`?Q$(a(),t):a;if(o&&e1(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const $$=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:o$(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`),s$(t)):t.$refStrategy===`seen`?s$(t):void 0}},e1=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),t1=(e,t)=>{let n=r$(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Q$(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??s$(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Q$(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??s$(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 n1(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function r1(e,t){return nX(e)?_a(e,{target:n1(t?.target),io:t?.pipeStrategy??`input`}):t1(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function i1(e){let t=oX(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=dX(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function a1(e,t){let n=iX(e,t);if(!n.success)throw n.error;return n.data}var o1=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(VX,e=>{this._oncancel(e)}),this.setNotificationHandler(aZ,e=>{this._onprogress(e)}),this.setRequestHandler(nZ,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(mZ,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new ZQ(FX.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(gZ,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 ZQ(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 ZQ(FX.InvalidParams,`Task not found: ${r}`);if(!$Q(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if($Q(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[mX]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(_Z,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 ZQ(FX.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(yZ,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new ZQ(FX.InvalidParams,`Task not found: ${e.params.taskId}`);if($Q(n.status))throw new ZQ(FX.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 ZQ(FX.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof ZQ?e:new ZQ(FX.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),ZQ.fromError(FX.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),PX(e)||LX(e)?this._onresponse(e):AX(e)?this._onrequest(e,t):MX(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=ZQ.fromError(FX.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?.[mX]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:FX.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=CX(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 ZQ(FX.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:FX.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),PX(e)?n(e):n(new ZQ(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(PX(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),PX(e)?r(e):r(ZQ.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 ZQ?e:new ZQ(FX.InternalError,String(e))}}return}let i;try{let r=await this.request(e,dZ,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new ZQ(FX.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},$Q(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new ZQ(FX.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new ZQ(FX.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 ZQ?e:new ZQ(FX.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||{},[mX]: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 ZQ?e:new ZQ(FX.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=iX(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(ZQ.fromError(FX.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},hZ,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},vZ,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},bZ,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||{},[mX]: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||{},[mX]: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||{},[mX]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=i1(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=a1(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=i1(e);this._notificationHandlers.set(n,n=>{let r=a1(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`&&AX(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new ZQ(FX.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 ZQ(FX.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new ZQ(FX.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 ZQ(FX.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=pZ.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),$Q(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 ZQ(FX.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if($Q(a.status))throw new ZQ(FX.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=pZ.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),$Q(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function s1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c1(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];s1(a)&&s1(i)?n[r]={...a,...i}:n[r]=i}return n}var l1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),u1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=l1();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}}})),d1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=l1(),n=u1();var r=l1();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=u1();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&&=ae(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=ae(this.rhs,e,n),this}get names(){return ie(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=ae(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)||(w(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>re(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(oe(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=ae(this.condition,e,t),this}get names(){let e=super.names;return ie(e,this.condition),this.else&&re(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=ae(this.iteration,e,t),this}get names(){return re(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 ie(ie(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=ae(this.iterable,e,t),this}get names(){return re(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 ee=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&&re(e,this.catch.names),this.finally&&re(e,this.finally.names),e}},te=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};te.kind=`catch`;var ne=class extends m{render(e){return`finally`+super.render(e)}};ne.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
1229
1229
  `:``},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 ee;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new te(e),t(e)}return n&&(this._currNode=r.finally=new ne,this.code(n)),this._endBlockNode(te,ne)}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 re(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ie(e,n){return n instanceof t._CodeOrName?re(e,n.names):e}function ae(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 w(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function oe(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${fe(e)}`}e.not=oe;let se=de(e.operators.AND);function ce(...e){return e.reduce(se)}e.and=ce;let le=de(e.operators.OR);function ue(...e){return e.reduce(le)}e.or=ue;function de(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${fe(n)} ${e} ${fe(r)}`}function fe(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),f1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=d1(),n=l1();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})),p1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=d1();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`)}})),m1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=d1(),n=f1(),r=p1();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])}})),h1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=m1(),n=d1(),r=p1(),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)}})),g1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),_1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),v1=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=g1(),n=_1(),r=m1(),i=d1(),a=f1();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
@@ -3254,11 +3254,11 @@ Incremental by default — don't re-read the whole repo.
3254
3254
  `).filter(Boolean),c=Nhe(s),l=await Fhe(t),u=[];for(let e of c)e.startsWith(`detached-`)||(l.has(e)?i.retainedBranches.push(e):u.push(e));if(u.length!==0){let e=new Set;for(let t of l)c.has(t)||e.add(t);for(let n of u){let r=!1;if(e.size>0){let o=null;for(let e of s)if(e.startsWith(`refs/wip/${n}/`))try{o=(await a.raw(`rev-parse`,e)).trim();break}catch{}if(o){for(let c of e)if(await Phe(t,c)===o){let t=s.filter(e=>e.startsWith(`refs/wip/${n}/`));for(let e of t){let t=`refs/wip/${c}/${e.slice(`refs/wip/${n}/`.length)}`;try{let n=(await a.raw(`rev-parse`,e)).trim();await a.raw(`update-ref`,t,n),await a.raw(`update-ref`,`-d`,e)}catch(n){M7.error({err:n,oldRef:e,newRef:t},`[shadow-gc] failed to migrate WIP ref`)}}i.renamedBranches.push({from:n,to:c}),e.delete(c),r=!0;break}}}if(!r){let e=s.filter(e=>e.startsWith(`refs/wip/${n}/`));for(let t of e)try{let e=(await a.raw(`log`,`-1`,`--format=%ci`,t)).trim(),r=new Date(e).getTime();if(Date.now()-r<864e5){i.retainedBranches.push(n);break}await a.raw(`update-ref`,`-d`,t)}catch{}i.retainedBranches.includes(n)||i.deletedBranches.push(n)}}}let d=new Set([...l,...i.retainedBranches]);for(let t of d)try{let r=await XO(e,t,n);(r.scanned>0||r.deletedBridgeMergeLoss>0||r.deletedExternalChangeRescue>0||r.deletedAutoConsolidation>0)&&(i.checkpointGc[t]={scanned:r.scanned,deletedBridgeMergeLoss:r.deletedBridgeMergeLoss,deletedExternalChangeRescue:r.deletedExternalChangeRescue,deletedAutoConsolidation:r.deletedAutoConsolidation,retained:r.retained})}catch(e){M7.warn({err:e,branch:t},`[shadow-gc] checkpoint GC failed`)}try{await _j(e,$A(e.gitDir))}catch(e){M7.warn({err:e},`[shadow-gc] rename-log GC failed`)}let f=Date.now();for(let t of l){let n=await TO(e,t),a=[];for(let e of n)if(!(e.classification===`classified-file-system`||e.classification===`classified-git-upstream`||e.classification===`classified-git-author`||e.classification===`classified-openknowledge-service`)){if(e.classification===`unknown`){M7.warn({branch:t,writerId:e.writerId},`[shadow-gc] unknown writer id in active branch ref — preserved`);continue}if(e.classification===`agent`||e.classification===`principal`){if(e.isPark)continue;e.committedAtMs>0&&f-e.committedAtMs>=2592e6&&a.push({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})}}if(a.length>0)try{await tk(e,r,a,t,void 0,{checkpointKind:{foldedRefs:a.length,trigger:`ttl`},includeUpstream:!1,timeoutMs:SO}),i.deletedStaleSessionRefs+=a.length}catch(e){M7.warn({err:e,branch:t},`[shadow-gc] TTL consolidation failed`)}}return i}let N7=null,P7=null,F7=null;function Lhe(){return N7||=vo().createHistogram(`ok.shadow.maintenance.run_duration_ms`,{description:`Wall-clock duration of one maintenance op. Bounded labels: op ∈ {gc, consolidation, reap}, outcome ∈ {ok, skipped, error}.`,unit:`ms`}),N7}function Rhe(){return P7||=vo().createCounter(`ok.shadow.maintenance.gc_latch_total`,{description:`Distinct gc.log latch EPISODES (counted on the absent→present transition, not per observation, so one persistent ~1-day latch counts once). A latch means auto-gc is silently disabled until it self-expires; a nonzero rate means a repo is re-degrading invisibly.`}),P7}function zhe(){return F7||=vo().createCounter(`ok.shadow.maintenance.consolidation_total`,{description:`Auto-consolidation runs that folded ≥1 dead chain. Bounded label: trigger ∈ {dead-chain, session-close, boot, ttl}. Width before/after ride the structured log, not metric labels.`}),F7}function I7(e,t,n){Lhe().record(Math.max(0,n),{op:e,outcome:t})}function Bhe(){Rhe().add(1)}function Vhe(e){zhe().add(1,{trigger:e})}async function L7(e){let t=await CO(e).raw(`count-objects`,`-v`),n=new Map;for(let e of t.split(`
3255
3255
  `)){let t=e.indexOf(`:`);if(t<0)continue;let r=e.slice(0,t).trim(),i=Number.parseInt(e.slice(t+1).trim(),10);r&&n.set(r,Number.isFinite(i)?i:0)}return{looseObjects:n.get(`count`)??0,looseKiB:n.get(`size`)??0,packfiles:n.get(`packs`)??0,packedObjects:n.get(`in-pack`)??0}}function R7(e){return z(R(e.gitDir,`gc.log`))}async function z7(e,t){let n=CO(e),r=t?`refs/wip/${t}/`:`refs/wip/`;try{return(await n.raw(`for-each-ref`,`--format=%(refname)`,r)).trim().split(`
3256
3256
  `).filter(Boolean).length}catch{return 0}}async function Hhe(e,t){let n=CO(e),r;try{r=(await n.raw(`for-each-ref`,`--format=%(refname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/`)).trim().split(`
3257
- `).filter(Boolean)}catch{return 0}let i=0;for(let e of r){let[n=``,r=``,a=``]=e.split(`\0`);if(a.startsWith(`park:`))continue;let o=n.split(`/`).slice(3).join(`/`);if(!o||Su(o).classification!==`agent`)continue;let s=Number.parseInt(r,10);Number.isFinite(s)&&s*1e3<t&&(i+=1)}return i}const B7=F(`shadow-maintenance`),Uhe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),Whe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})();function V7(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function H7(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var Ghe=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){V7()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(e=1e3){if(V7()||this.destroyed)return;let t=this.runScheduledMaintenance(`boot`),n,r=new Promise(t=>{n=setTimeout(t,e)});await Promise.race([t.then(()=>void 0),r]),n&&clearTimeout(n),t.catch(e=>{B7.warn({err:e},`[shadow-maintenance] boot maintenance background continuation failed`)})}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(V7()||this.destroyed)&&!this.running){this.running=!0;try{await this.consolidateInner(e),await this.reapInner(e),await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(V7()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let n=performance.now();try{await Ihe(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),I7(`reap`,`ok`,performance.now()-n)}catch(t){I7(`reap`,`error`,performance.now()-n),B7.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(V7()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:n}=this.deps;if(!t||!n)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<Whe)return{consolidated:!1,skipped:`spacing`};let r=this.deps.getShadow();if(!r)return{consolidated:!1,skipped:`no-shadow`};try{let i=t()??`main`,a=await this.findDeadAgentChains(r,i,n);if(a.length<Uhe)return{consolidated:!1,skipped:`below-threshold`,deadChains:a.length};let o=await z7(r,i);await tk(r,this.deps.contentRoot??``,a,i,void 0,{checkpointKind:{foldedRefs:a.length,trigger:H7(e)},timeoutMs:SO}),this.lastConsolidationAt=Date.now();let s=await z7(r,i);return Vhe(H7(e)),B7.info({trigger:e,branch:i,foldedChains:a.length,widthBefore:o,widthAfter:s},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:a.length,widthBefore:o,widthAfter:s}}catch(t){return B7.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,n){return(await TO(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!n(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(V7())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return I7(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();return t?vO(t).withExclusive(()=>this.gcRun(e,t)):{ran:!1,skipped:`no-shadow`}}async gcRun(e,t){let n=performance.now();try{let r=await L7(t);await CO(t,{timeoutMs:SO}).raw(`gc`,`--auto`);let i=await L7(t),a=R7(t),o=performance.now()-n;return I7(`gc`,`ok`,o),a&&(this.lastGcLatch||Bhe(),B7.warn({trigger:e,looseObjects:i.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=a,B7.info({trigger:e,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfiles:i.packfiles,durationMs:Math.round(o)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfilesAfter:i.packfiles,latch:a,durationMs:o}}catch(t){return I7(`gc`,`error`,performance.now()-n),B7.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function Khe(e){return new Ghe(e)}const qhe={depth:1,acceptLeaf:e=>Ic(e)===`SKILL.md`},Jhe={depth:0,acceptLeaf:e=>Ic(e).endsWith(`.md`)};async function U7(e,t,n=qhe){let r=F(`managed-artifact-watcher`),{watch:i}=await import(`./chokidar-BCS--vwu.mjs`),a=Array.from(new Set(e));for(let e of a)try{ao(e,{recursive:!0})}catch(t){Xo(t)!==`EEXIST`&&r.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let o=i(a,{ignoreInitial:!0,depth:n.depth,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{o.once(`ready`,e)});let s=new Map,c=e=>{if(!n.acceptLeaf(e))return;let i;try{i=B(e,`utf-8`)}catch(t){if(Xo(t)===`ENOENT`){r.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}r.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(i!==s.get(e)){s.set(e,i);try{t(e,i)}catch(t){r.warn({err:t,path:e},`managed-artifact change handler threw`)}}},l=e=>c(e);o.on(`add`,l),o.on(`change`,l),o.on(`unlink`,e=>{n.acceptLeaf(e)&&(s.delete(e),r.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`))}),o.on(`error`,e=>{r.warn({err:e,watchRoots:a},`[managed-artifact-watcher] chokidar error`)});let u=!1;return async()=>{u||(u=!0,await o.close())}}const W7=F(`persistence-staleness`);var G7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function Yhe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,i=e.getBase??AM,a=e.isBatchActive??LM,o=e.peekInFlight??PM,s=e.msSinceLastUserTx??SD,c=new Map,l=!1,u=null;function d(e){return CM(e)}function f(e){return e===void 0?void 0:Wt(e)}function p(e,t){return t===void 0?e!==``:e!==t}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),sS(n)||OS(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S)){c.delete(n);continue}m++;let C=r(),ee=s(v,C);if(ee!==null&&ee<t)continue;let te=c.get(n);if(te&&te.fingerprint===x&&(te.declined||C-te.atMs<t))continue;let ne=te?.fingerprint!==x;ne&&Rne();let re=!ne&&te?te.firstDetectedAtMs:C,ie=C-re,ae=null,w=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(ae=`disk-file-never-loaded`):t===null?ae=`disk-file-missing`:Wt(t)!==S&&(ae=`disk-diverged-from-base`)}catch(e){e instanceof G7?(ae=`disk-read-refused`,W7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(ae=`disk-read-failed`,w=!0,W7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(ae!==null){g++,Bne(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:re,declined:!w}),W7.warn({docName:n,ageMs:ee,staleForMs:ie,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:ae},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}W7.warn({docName:n,ageMs:ee,staleForMs:ie,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:re,declined:!1}),zne(),h++;try{await e.forceStore(v,n)}catch(e){W7.error({err:e,docName:n,staleForMs:ie},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let oe=d(v.getText(`source`).toString());p(oe,f(i(n)))&&oe===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:re,declined:!0}),W7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?W7.info(v,`[persistence-staleness] sweep complete`):W7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{W7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function Xhe(e){try{let t=Ao({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function K7(e){let t=aN(e),n=R(t,`principal.json`),{name:r,email:i}=await Xhe(e);if(z(n)){let e;try{e=JSON.parse(B(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Il()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?rh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?rh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return fl(n,JSON.stringify(s,null,2),`utf-8`),s}$c(t,{recursive:!0});let a=`principal-${Il()}`,o=a.slice(10,18),s={id:a,display_name:r?rh(r):`Local User`,display_email:i?rh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return fl(n,JSON.stringify(s,null,2),`utf-8`),s}var Zhe=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};function q7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function Qhe(e,t){try{if(aS(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(q7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw Jx(),Va({"auth.reason":`doc-deleted`}),new _D(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){ore(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:i}));return}r.add(i);let n=t.recentlyRemovedDocs.get(i);if(n===void 0)throw qx(),Va({"auth.reason":`rename-redirect`}),new _D(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw q7(t,i)?(t.recentlyRemovedDocs.delete(i),qx(),Va({"auth.reason":`rename-redirect`}),new _D(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(Jx(),Va({"auth.reason":`doc-deleted`}),new _D(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof _D)throw t;are(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const J7=F(`removed-docs-journal`);function Y7(e){return I(aN(e),`removed-docs.json`)}function $he(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.docName!=`string`||t.docName.length===0||typeof t.addedAt!=`number`?!1:t.kind===`deleted`?!0:t.kind===`renamed`?typeof t.newDocName==`string`:!1}function ege(e){let t=Y7(e);if(!z(t))return[];try{let e=JSON.parse(B(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return J7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!$he(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return J7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function X7(e,t){let n=Y7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};ao(Rc(n),{recursive:!0});let i=`${n}.tmp`;ho(i,JSON.stringify(r),`utf-8`),Qa(i,n)}const Z7=F(`server-observers`);function Q7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(tS(r)||nS(r)||iS(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=gM({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(r,n),!0}catch(e){return Z7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),Wx(`a`),Wx(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(Z7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){Z7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const $7=`state.json`;function e9(e){return e.lockDir,z(e.shadowRepoDir)?`adopt`:`fresh`}function t9(e){return R(e,$7)}function tge(e,t){return e===t||e===0&&t===1}var n9=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function nge(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function r9(e){let t=t9(e);if(!z(t))return{status:`absent`};let n;try{n=B(t,`utf-8`)}catch(e){throw new n9({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new n9({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!nge(r))throw new n9({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function i9(e,t){let n=t9(e);$c(Rc(n),{recursive:!0}),fl(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function a9(e){let t=F(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Ho,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=t9(e.lockDir),s=r9(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!tge(c.stateSchemaVersion,n))throw new n9({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return i9(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(e9({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return i9(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return i9(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}function rge(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function ige(e){return e.git?.toString()??e.message??``}function o9(e,t){return t.some(t=>t.test(e))}const age={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},oge=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],s9=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],sge=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],cge=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],lge=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],uge=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],dge=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],fge=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],pge=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],mge=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],hge=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],gge=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],_ge=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function c9(e){let t=vge(e);return{...t,userFacingCode:rge(t.class,t.subclass)}}function vge(e){let t=e instanceof Error?e:Error(String(e)),n=ige(t),r=`${t.message}\n${n}`.toLowerCase();if(o9(r,fge))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(o9(r,pge))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(o9(r,mge))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=St(t);return i.kind===`auth`?i.subclass===`403`&&o9(r,s9)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:age[i.subclass],rawStderr:n}:o9(r,s9)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:o9(r,oge)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:o9(r,sge)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:o9(r,cge)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:o9(r,lge)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:o9(r,dge)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:o9(r,uge)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:o9(r,_ge)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:o9(r,gge)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:o9(r,hge)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function yge(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const l9=F(`github-permissions`);function bge(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function xge(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function Sge(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function Cge(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return l9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=Sge(t);return n===null?(l9.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return l9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function wge(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){l9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function Tge(e){let{owner:t,repo:n,host:r=`github.com`,detectGh:i=()=>({available:!1}),tokenStore:a,_fetchFn:o=fetch,_timeoutMs:s=5e3}=e,{token:c,source:l}=await wge(r,i,a);if(l===`anonymous`)return l9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`};let u=`${bge(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;l9.info({host:r,tokenSource:l,tokenLen:c===void 0?0:c.length},`[permissions] probe starting`);let d=new AbortController,f=setTimeout(()=>d.abort(),s);try{let e=await o(u,{signal:d.signal,headers:xge(c)}),t=await Cge(e,c!==void 0);return l9.info({host:r,tokenSource:l,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return d.signal.aborted?(l9.warn({host:r,timeoutMs:s},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(l9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(f)}}async function Ege(e){let t=performance.now(),n=await Tge(e);return Age(n,performance.now()-t),n}function Dge(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let u9=null;function Oge(){return u9||=vo().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,none}.`}),u9}let d9=null;function kge(){return d9||=vo().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),d9}function Age(e,t){let n=Dge(e);Oge().add(1,n),kge().record(t,{outcome:n.outcome})}function f9(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const p9=F(`sync-engine`),m9=/^[0-9a-f]{40}$/i;function jge(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function h9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function g9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function _9(e){let t=Yl(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`?t.repository.readRef(n.ref).kind===`absent`:!1}function Mge(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var Nge=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.ghTokenSource=yge(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??Ege,this.statePath=R(aN(this.projectDir),`sync-state.json`),this.conflictStore=new aJ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return hR(this.projectDir)}gitHandle(e){return No(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){p9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),p9.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){p9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=nu(this.projectDir),n=t?I(t,`MERGE_HEAD`):null,r=n!==null&&z(n);if(this.conflictCount>0&&!r)p9.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&r)try{let e=this.gitHandle(),t=new Set(await cO(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&p9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){p9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&this.conflictCount===0){p9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),p9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let i=f9(this.lastFetchUtc,this.pullIntervalSeconds),a=f9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(i>0?i:void 0),this.schedulePush(a>0?a:void 0),p9.info({branch:this.currentBranch,pullDelayMs:i,pushDelayMs:a},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){p9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await Gl(50)}this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async notifyCredentialsChanged(){if(this.syncEnabled&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?p9.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):p9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?gR(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await xH(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=mR(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,h9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,p9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){p9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=jge(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,p9.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),a=!0,p9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!h9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,p9.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!z(I(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return p9.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=nu(this.projectDir),n=t?I(t,`MERGE_HEAD`):null;if(!(n!==null&&z(n)))p9.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=this.gitHandle(),n=new Set(await cO(t.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let e of this.conflictStore.list())n.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&p9.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){p9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{p9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??g9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{p9.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=Mge(e);return t>0?t:g9(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(_9(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,p9.warn({},`[sync] detached HEAD — pausing sync`);return}t=n,this.currentBranch=t}catch(e){this.handleError(c9(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=c9(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=c9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(_9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=I(vl(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await jo(async()=>{let e=this.gitHandle(n);if(_9(this.projectDir)){p9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){p9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(c9(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i);if(t.length>0)for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));await this.removePathsFromIndex(e,s);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){p9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}p9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[],d=[];try{let n=await cO(e.git,[`diff-tree`,`--name-only`,`-r`,i,c]);if(n.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n){u.push(t);let n=e.get(t)??Sk(L(this.contentDir,I(this.projectDir,t)));n&&!n.startsWith(`..`)&&d.push(n)}}}catch{u=t.map(e=>e.projectRelPath).concat(s),d=t.map(e=>e.contentRelPath)}let f=this.buildCommitMessage(d),p=await xH(this.projectDir),m=p===null;this.identityUnresolved!==m&&(this.identityUnresolved=m,this.cc1Broadcaster?.signal(`sync-status`));let h=p?.name??`OpenKnowledge`,g=p?.email??`sync@open-knowledge.local`;Fo(e,{GIT_AUTHOR_NAME:h,GIT_AUTHOR_EMAIL:g,GIT_COMMITTER_NAME:h,GIT_COMMITTER_EMAIL:g});let _=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,f])).trim();if(!_||!m9.test(_)){p9.warn({raw:_},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,_,i]),await this.resetRealIndexForPaths(u);let v=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),v=!0}catch{}v?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=_}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=c9(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){p9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=c9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}p9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{dl(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=I(vl(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await a.git.raw([`add`,`--`,...t])}let i=new Set(n.map(e=>e.projectRelPath)),o=[...r].filter(e=>!i.has(e));await this.removePathsFromIndex(a,o);let s=(await a.git.raw([`write-tree`])).trim();if(s===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let c=[];try{c=await cO(a.git,[`diff-tree`,`--name-only`,`-r`,t,s])}catch{c=n.map(e=>e.projectRelPath).concat(o)}let l=await xH(this.projectDir),u=l?.name??`OpenKnowledge`,d=l?.email??`sync@open-knowledge.local`;Fo(a,{GIT_AUTHOR_NAME:u,GIT_AUTHOR_EMAIL:d,GIT_COMMITTER_NAME:u,GIT_COMMITTER_EMAIL:d});let f=(await a.git.raw([`commit-tree`,s,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!f||!m9.test(f)?(p9.warn({raw:f},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,f,t]),await this.resetRealIndexForPaths(c,e),f)}finally{try{dl(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await cO(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return p9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await cO(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return p9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),p9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return p9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){p9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=il(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=I(n,i.name);if(i.isDirectory()){let e=Sk(L(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=Sk(L(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Sk(L(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return z(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await cO(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=I(this.projectDir,e),r=Sk(L(this.contentDir,t));!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&n.add(e)}}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await cO(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){p9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=I(this.projectDir,e),i=Sk(L(this.contentDir,t));!i.startsWith(`..`)&&lS(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),p9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){p9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),p9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),p9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),p9.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){p9.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){p9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),p9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,p9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};fl(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){p9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(z(this.statePath))try{let e=B(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){p9.warn({err:e},`[sync] failed to load sync state`)}}};Ia();const Pge=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Fge(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(tS(e)||nS(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&Pge.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Ua(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),La.with(Pa.extract(La.active(),r),e)}else e()}catch(e){F(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}const v9=F(`tag-index`),y9=Yn();function Ige(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.version!==1)return!1;let{docs:n,files:r}=t;if(typeof n!=`object`||!n||Array.isArray(n)||typeof r!=`object`||!r||Array.isArray(r))return!1;for(let e of Object.values(n))if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e.length>0))return!1;for(let e of Object.values(r)){if(typeof e!=`object`||!e)return!1;let{mtimeMs:t,size:n}=e;if(typeof t!=`number`||typeof n!=`number`)return!1}return!0}function b9(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function Lge(e){return e.replace(/`[^`]*`/g,``)}function Rge(e){let t=e.replaceAll(`\r
3257
+ `).filter(Boolean)}catch{return 0}let i=0;for(let e of r){let[n=``,r=``,a=``]=e.split(`\0`);if(a.startsWith(`park:`))continue;let o=n.split(`/`).slice(3).join(`/`);if(!o||Su(o).classification!==`agent`)continue;let s=Number.parseInt(r,10);Number.isFinite(s)&&s*1e3<t&&(i+=1)}return i}const B7=F(`shadow-maintenance`),Uhe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),Whe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})();function V7(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function H7(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var Ghe=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){V7()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(e=1e3){if(V7()||this.destroyed)return;let t=this.runScheduledMaintenance(`boot`),n,r=new Promise(t=>{n=setTimeout(t,e)});await Promise.race([t.then(()=>void 0),r]),n&&clearTimeout(n),t.catch(e=>{B7.warn({err:e},`[shadow-maintenance] boot maintenance background continuation failed`)})}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(V7()||this.destroyed)&&!this.running){this.running=!0;try{await this.consolidateInner(e),await this.reapInner(e),await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(V7()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let n=performance.now();try{await Ihe(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),I7(`reap`,`ok`,performance.now()-n)}catch(t){I7(`reap`,`error`,performance.now()-n),B7.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(V7()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:n}=this.deps;if(!t||!n)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<Whe)return{consolidated:!1,skipped:`spacing`};let r=this.deps.getShadow();if(!r)return{consolidated:!1,skipped:`no-shadow`};try{let i=t()??`main`,a=await this.findDeadAgentChains(r,i,n);if(a.length<Uhe)return{consolidated:!1,skipped:`below-threshold`,deadChains:a.length};let o=await z7(r,i);await tk(r,this.deps.contentRoot??``,a,i,void 0,{checkpointKind:{foldedRefs:a.length,trigger:H7(e)},timeoutMs:SO}),this.lastConsolidationAt=Date.now();let s=await z7(r,i);return Vhe(H7(e)),B7.info({trigger:e,branch:i,foldedChains:a.length,widthBefore:o,widthAfter:s},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:a.length,widthBefore:o,widthAfter:s}}catch(t){return B7.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,n){return(await TO(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!n(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(V7())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return I7(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();return t?vO(t).withExclusive(()=>this.gcRun(e,t)):{ran:!1,skipped:`no-shadow`}}async gcRun(e,t){let n=performance.now();try{let r=await L7(t);await CO(t,{timeoutMs:SO}).raw(`gc`,`--auto`);let i=await L7(t),a=R7(t),o=performance.now()-n;return I7(`gc`,`ok`,o),a&&(this.lastGcLatch||Bhe(),B7.warn({trigger:e,looseObjects:i.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=a,B7.info({trigger:e,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfiles:i.packfiles,durationMs:Math.round(o)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfilesAfter:i.packfiles,latch:a,durationMs:o}}catch(t){return I7(`gc`,`error`,performance.now()-n),B7.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function Khe(e){return new Ghe(e)}const qhe={depth:1,acceptLeaf:e=>Ic(e)===`SKILL.md`},Jhe={depth:0,acceptLeaf:e=>Ic(e).endsWith(`.md`)};async function U7(e,t,n=qhe){let r=F(`managed-artifact-watcher`),{watch:i}=await import(`./chokidar-BCS--vwu.mjs`),a=Array.from(new Set(e));for(let e of a)try{ao(e,{recursive:!0})}catch(t){Xo(t)!==`EEXIST`&&r.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let o=i(a,{ignoreInitial:!0,depth:n.depth,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{o.once(`ready`,e)});let s=new Map,c=e=>{if(!n.acceptLeaf(e))return;let i;try{i=B(e,`utf-8`)}catch(t){if(Xo(t)===`ENOENT`){r.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}r.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(i!==s.get(e)){s.set(e,i);try{t(e,i)}catch(t){r.warn({err:t,path:e},`managed-artifact change handler threw`)}}},l=e=>c(e);o.on(`add`,l),o.on(`change`,l),o.on(`unlink`,e=>{n.acceptLeaf(e)&&(s.delete(e),r.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`))}),o.on(`error`,e=>{r.warn({err:e,watchRoots:a},`[managed-artifact-watcher] chokidar error`)});let u=!1;return async()=>{u||(u=!0,await o.close())}}const W7=F(`persistence-staleness`);var G7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function Yhe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,i=e.getBase??AM,a=e.isBatchActive??LM,o=e.peekInFlight??PM,s=e.msSinceLastUserTx??SD,c=new Map,l=!1,u=null;function d(e){return CM(e)}function f(e){return e===void 0?void 0:Wt(e)}function p(e,t){return t===void 0?e!==``:e!==t}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),sS(n)||OS(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S)){c.delete(n);continue}m++;let C=r(),ee=s(v,C);if(ee!==null&&ee<t)continue;let te=c.get(n);if(te&&te.fingerprint===x&&(te.declined||C-te.atMs<t))continue;let ne=te?.fingerprint!==x;ne&&Rne();let re=!ne&&te?te.firstDetectedAtMs:C,ie=C-re,ae=null,w=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(ae=`disk-file-never-loaded`):t===null?ae=`disk-file-missing`:Wt(t)!==S&&(ae=`disk-diverged-from-base`)}catch(e){e instanceof G7?(ae=`disk-read-refused`,W7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(ae=`disk-read-failed`,w=!0,W7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(ae!==null){g++,Bne(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:re,declined:!w}),W7.warn({docName:n,ageMs:ee,staleForMs:ie,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:ae},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}W7.warn({docName:n,ageMs:ee,staleForMs:ie,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:re,declined:!1}),zne(),h++;try{await e.forceStore(v,n)}catch(e){W7.error({err:e,docName:n,staleForMs:ie},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let oe=d(v.getText(`source`).toString());p(oe,f(i(n)))&&oe===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:re,declined:!0}),W7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?W7.info(v,`[persistence-staleness] sweep complete`):W7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{W7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function Xhe(e){try{let t=Ao({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function K7(e){let t=aN(e),n=R(t,`principal.json`),{name:r,email:i}=await Xhe(e);if(z(n)){let e;try{e=JSON.parse(B(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Il()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?rh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?rh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return fl(n,JSON.stringify(s,null,2),`utf-8`),s}$c(t,{recursive:!0});let a=`principal-${Il()}`,o=a.slice(10,18),s={id:a,display_name:r?rh(r):`Local User`,display_email:i?rh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return fl(n,JSON.stringify(s,null,2),`utf-8`),s}var Zhe=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};function q7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function Qhe(e,t){try{if(aS(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(q7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw Jx(),Va({"auth.reason":`doc-deleted`}),new _D(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){ore(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:i}));return}r.add(i);let n=t.recentlyRemovedDocs.get(i);if(n===void 0)throw qx(),Va({"auth.reason":`rename-redirect`}),new _D(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw q7(t,i)?(t.recentlyRemovedDocs.delete(i),qx(),Va({"auth.reason":`rename-redirect`}),new _D(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(Jx(),Va({"auth.reason":`doc-deleted`}),new _D(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof _D)throw t;are(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const J7=F(`removed-docs-journal`);function Y7(e){return I(aN(e),`removed-docs.json`)}function $he(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.docName!=`string`||t.docName.length===0||typeof t.addedAt!=`number`?!1:t.kind===`deleted`?!0:t.kind===`renamed`?typeof t.newDocName==`string`:!1}function ege(e){let t=Y7(e);if(!z(t))return[];try{let e=JSON.parse(B(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return J7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!$he(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return J7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function X7(e,t){let n=Y7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};ao(Rc(n),{recursive:!0});let i=`${n}.tmp`;ho(i,JSON.stringify(r),`utf-8`),Qa(i,n)}const Z7=F(`server-observers`);function Q7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(tS(r)||nS(r)||iS(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=gM({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(r,n),!0}catch(e){return Z7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),Wx(`a`),Wx(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(Z7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){Z7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const $7=`state.json`;function e9(e){return e.lockDir,z(e.shadowRepoDir)?`adopt`:`fresh`}function t9(e){return R(e,$7)}function tge(e,t){return e===t||e===0&&t===1}var n9=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function nge(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function r9(e){let t=t9(e);if(!z(t))return{status:`absent`};let n;try{n=B(t,`utf-8`)}catch(e){throw new n9({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new n9({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!nge(r))throw new n9({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function i9(e,t){let n=t9(e);$c(Rc(n),{recursive:!0}),fl(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function a9(e){let t=F(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Ho,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=t9(e.lockDir),s=r9(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!tge(c.stateSchemaVersion,n))throw new n9({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return i9(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(e9({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return i9(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return i9(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}function rge(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function ige(e){return e.git?.toString()??e.message??``}function o9(e,t){return t.some(t=>t.test(e))}const age={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},oge=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],s9=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],sge=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],cge=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],lge=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],uge=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],dge=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],fge=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],pge=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],mge=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],hge=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],gge=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],_ge=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function c9(e){let t=vge(e);return{...t,userFacingCode:rge(t.class,t.subclass)}}function vge(e){let t=e instanceof Error?e:Error(String(e)),n=ige(t),r=`${t.message}\n${n}`.toLowerCase();if(o9(r,fge))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(o9(r,pge))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(o9(r,mge))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=St(t);return i.kind===`auth`?i.subclass===`403`&&o9(r,s9)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:age[i.subclass],rawStderr:n}:o9(r,s9)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:o9(r,oge)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:o9(r,sge)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:o9(r,cge)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:o9(r,lge)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:o9(r,dge)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:o9(r,uge)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:o9(r,_ge)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:o9(r,gge)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:o9(r,hge)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function yge(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const l9=F(`github-permissions`);function bge(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function xge(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function Sge(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function Cge(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return l9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=Sge(t);return n===null?(l9.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return l9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function wge(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){l9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function Tge(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,detectGh:a=()=>({available:!1}),tokenStore:o,_fetchFn:s=fetch,_timeoutMs:c=5e3}=e,{token:l,source:u}=await wge(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(l9.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(l9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${bge(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;l9.info({host:r,tokenSource:u,tokenLen:l===void 0?0:l.length},`[permissions] probe starting`);let f=new AbortController,p=setTimeout(()=>f.abort(),c);try{let e=await s(d,{signal:f.signal,headers:xge(l)}),t=await Cge(e,l!==void 0);return l9.info({host:r,tokenSource:u,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return f.signal.aborted?(l9.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(l9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function Ege(e){let t=performance.now(),n=await Tge(e);return Age(n,performance.now()-t),n}function Dge(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let u9=null;function Oge(){return u9||=vo().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),u9}let d9=null;function kge(){return d9||=vo().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),d9}function Age(e,t){let n=Dge(e);Oge().add(1,n),kge().record(t,{outcome:n.outcome})}function f9(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const p9=F(`sync-engine`),m9=/^[0-9a-f]{40}$/i;function jge(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function h9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function g9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function _9(e){let t=Yl(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`?t.repository.readRef(n.ref).kind===`absent`:!1}function Mge(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var Nge=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;setBatchInProgress;onAutoDisable;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.detectGh=e.detectGh,this.ghTokenSource=yge(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??Ege,this.statePath=R(aN(this.projectDir),`sync-state.json`),this.conflictStore=new aJ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return hR(this.projectDir)}gitHandle(e){return No(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){p9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),p9.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){p9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=nu(this.projectDir),n=t?I(t,`MERGE_HEAD`):null,r=n!==null&&z(n);if(this.conflictCount>0&&!r)p9.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&r)try{let e=this.gitHandle(),t=new Set(await cO(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&p9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){p9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&this.conflictCount===0){p9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),p9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let i=f9(this.lastFetchUtc,this.pullIntervalSeconds),a=f9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(i>0?i:void 0),this.schedulePush(a>0?a:void 0),p9.info({branch:this.currentBranch,pullDelayMs:i,pushDelayMs:a},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){p9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await Gl(50)}this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async notifyCredentialsChanged(){if(this.syncEnabled&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?p9.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):p9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?gR(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await xH(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=mR(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,h9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,p9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){p9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=jge(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.syncEnabled===!0?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,p9.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.syncEnabled===!0&&this.transitionTo(`idle`),a=!0,p9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!h9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,p9.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!z(I(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return p9.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=nu(this.projectDir),n=t?I(t,`MERGE_HEAD`):null;if(!(n!==null&&z(n)))p9.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=this.gitHandle(),n=new Set(await cO(t.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let e of this.conflictStore.list())n.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&p9.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){p9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{p9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??g9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{p9.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=Mge(e);return t>0?t:g9(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(_9(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,p9.warn({},`[sync] detached HEAD — pausing sync`);return}t=n,this.currentBranch=t}catch(e){this.handleError(c9(e instanceof Error?e:Error(String(e))),`pull`);return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=c9(e instanceof Error?e:Error(String(e)));this.handleError(t,`pull`);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=c9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(_9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=I(vl(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await jo(async()=>{let e=this.gitHandle(n);if(_9(this.projectDir)){p9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){p9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(c9(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i);if(t.length>0)for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));await this.removePathsFromIndex(e,s);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){p9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}p9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[],d=[];try{let n=await cO(e.git,[`diff-tree`,`--name-only`,`-r`,i,c]);if(n.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n){u.push(t);let n=e.get(t)??Sk(L(this.contentDir,I(this.projectDir,t)));n&&!n.startsWith(`..`)&&d.push(n)}}}catch{u=t.map(e=>e.projectRelPath).concat(s),d=t.map(e=>e.contentRelPath)}let f=this.buildCommitMessage(d),p=await xH(this.projectDir),m=p===null;this.identityUnresolved!==m&&(this.identityUnresolved=m,this.cc1Broadcaster?.signal(`sync-status`));let h=p?.name??`OpenKnowledge`,g=p?.email??`sync@open-knowledge.local`;Fo(e,{GIT_AUTHOR_NAME:h,GIT_AUTHOR_EMAIL:g,GIT_COMMITTER_NAME:h,GIT_COMMITTER_EMAIL:g});let _=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,f])).trim();if(!_||!m9.test(_)){p9.warn({raw:_},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,_,i]),await this.resetRealIndexForPaths(u);let v=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),v=!0}catch{}v?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=_}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=c9(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){p9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=c9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}p9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{dl(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=I(vl(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await a.git.raw([`add`,`--`,...t])}let i=new Set(n.map(e=>e.projectRelPath)),o=[...r].filter(e=>!i.has(e));await this.removePathsFromIndex(a,o);let s=(await a.git.raw([`write-tree`])).trim();if(s===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let c=[];try{c=await cO(a.git,[`diff-tree`,`--name-only`,`-r`,t,s])}catch{c=n.map(e=>e.projectRelPath).concat(o)}let l=await xH(this.projectDir),u=l?.name??`OpenKnowledge`,d=l?.email??`sync@open-knowledge.local`;Fo(a,{GIT_AUTHOR_NAME:u,GIT_AUTHOR_EMAIL:d,GIT_COMMITTER_NAME:u,GIT_COMMITTER_EMAIL:d});let f=(await a.git.raw([`commit-tree`,s,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!f||!m9.test(f)?(p9.warn({raw:f},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,f,t]),await this.resetRealIndexForPaths(c,e),f)}finally{try{dl(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await cO(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return p9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await cO(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return p9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),p9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return p9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){p9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=il(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=I(n,i.name);if(i.isDirectory()){let e=Sk(L(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=Sk(L(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Sk(L(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return z(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await cO(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=I(this.projectDir,e),r=Sk(L(this.contentDir,t));!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&n.add(e)}}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await cO(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){p9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=I(this.projectDir,e),i=Sk(L(this.contentDir,t));!i.startsWith(`..`)&&lS(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),p9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){p9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),p9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),p9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),p9.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){p9.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){p9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){p9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),p9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,p9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};fl(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){p9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(z(this.statePath))try{let e=B(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){p9.warn({err:e},`[sync] failed to load sync state`)}}};Ia();const Pge=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Fge(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(tS(e)||nS(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&Pge.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Ua(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),La.with(Pa.extract(La.active(),r),e)}else e()}catch(e){F(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}const v9=F(`tag-index`),y9=Yn();function Ige(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.version!==1)return!1;let{docs:n,files:r}=t;if(typeof n!=`object`||!n||Array.isArray(n)||typeof r!=`object`||!r||Array.isArray(r))return!1;for(let e of Object.values(n))if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e.length>0))return!1;for(let e of Object.values(r)){if(typeof e!=`object`||!e)return!1;let{mtimeMs:t,size:n}=e;if(typeof t!=`number`||typeof n!=`number`)return!1}return!0}function b9(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function Lge(e){return e.replace(/`[^`]*`/g,``)}function Rge(e){let t=e.replaceAll(`\r
3258
3258
  `,`
3259
3259
  `).split(`
3260
3260
  `),n=[],r=!1,i=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){r?RegExp(`^\\s{0,3}${i[0]==="`"?"`":`~`}{${i.length},}\\s*$`).test(e)&&(r=!1,i=``):(r=!0,i=t[1]);continue}if(r)continue;let a=Lge(e);for(y9.lastIndex=0;;){let e=y9.exec(a);if(e===null)break;let t=e[2];t&&n.push(t)}}return n}var x9=class{contentDir;contentFilter;projectDir;state=b9();fileMeta=new Map;initChain=Promise.resolve();closed=!1;constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.projectDir=e.projectDir}snapshotPath(){return this.projectDir?R(aN(this.projectDir),`cache`,`tags.json`):null}enqueue(e){let t=this.initChain.then(e);return this.initChain=t.then(()=>void 0,e=>{v9.warn({err:e},`queued tag-index task failed (chain cleared for next task)`)}),t}close(){return this.closed=!0,this.initChain}updateDocumentFromMarkdown(e,t){if(!oS(e))try{let{frontmatter:n,body:r}=en(t),i=Ke(n?Yt(n):``),a=Rge(r),o=new Set([...i,...a]),s=new Set;for(let e of o)for(let t of ai(e))s.add(t);this.applyDocSnapshot(e,o,s)}catch(t){v9.warn({docName:e,err:t},`Failed to scan ${e} for tag extraction`),this.deleteDocument(e)}}deleteDocument(e){if(oS(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=Dr(t,e);n.push({docName:r,matchingTags:[...i].sort((e,t)=>e.localeCompare(t))})}return n.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),n=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&n.add(e.slice(0,t));let r=t;for(;r>0;)n.add(e.slice(0,r)),r=e.indexOf(`/`,r+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!n.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){return this.enqueue(()=>xV(`tag`,`full`,()=>this.initOnce()))}async initOnce(){if(this.closed||(this.state=b9(),this.fileMeta=new Map,!z(this.contentDir)))return;let e=await this.listDocsWithPaths();for(let t=0;t<e.length;t+=50){let n=e.slice(t,t+50),r=await Promise.all(n.map(async({docName:e,filePath:t})=>{try{let[n,r]=await Promise.all([El(t),Cl(t,`utf-8`)]);return{docName:e,markdown:r,mtimeMs:n.mtimeMs,size:n.size}}catch(t){return v9.warn({docName:e,err:t},`Failed to read ${e} during init`),null}}));for(let e of r)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown),this.fileMeta.set(e.docName,{mtimeMs:e.mtimeMs,size:e.size})}catch(t){v9.warn({docName:e.docName,err:t},`Failed to index ${e.docName} during init`)}}}loadFromDisk(){return this.enqueue(()=>this.loadOnce())}async loadOnce(){if(this.closed)return!1;let e=this.snapshotPath();if(!e||!z(e))return!1;let t;try{t=JSON.parse(await Cl(e,`utf-8`))}catch(e){return v9.warn({err:e},`Failed to load tag snapshot; falling back to full rebuild`),!1}if(!Ige(t))return v9.warn({},`Tag snapshot failed validation; falling back to full rebuild`),!1;this.state=b9(),this.fileMeta=new Map(Object.entries(t.files));for(let[e,n]of Object.entries(t.docs)){if(oS(e))continue;let t=new Set(n),r=new Set;for(let e of t)for(let t of ai(e))r.add(t);this.applyDocSnapshot(e,t,r)}return!0}saveToDisk(){return this.enqueue(()=>this.saveOnce())}async saveOnce(){if(this.closed)return;let e=this.snapshotPath();if(!e)return;let t={version:1,docs:Object.fromEntries([...this.state.byDocLiteral.entries()].map(([e,t])=>[e,[...t].sort((e,t)=>e.localeCompare(t))])),files:Object.fromEntries(this.fileMeta)};await Za(Rc(e),{recursive:!0}),await Ja(e,JSON.stringify(t,null,2),`utf-8`)}reconcileWithDisk(){return this.enqueue(()=>xV(`tag`,`reconcile`,()=>this.reconcileOnce(),e=>({"index.added":e.added,"index.updated":e.updated,"index.deleted":e.deleted})))}async reconcileOnce(){if(this.closed||!z(this.contentDir))return{added:0,updated:0,deleted:0};let e=await this.listDocsWithPaths(),t=new Set(e.map(e=>e.docName)),n=new Map,r=0,i=0,a=[],o=await Promise.allSettled(e.map(async({docName:e,filePath:t})=>{let n=await El(t);return{docName:e,filePath:t,meta:{mtimeMs:n.mtimeMs,size:n.size}}}));for(let e of o){if(e.status===`rejected`)continue;let{docName:t,filePath:r,meta:i}=e.value,o=this.fileMeta.get(t);if(o!==void 0&&o.mtimeMs===i.mtimeMs&&o.size===i.size){n.set(t,i);continue}a.push({docName:t,filePath:r,meta:i,isNew:o===void 0})}for(let e=0;e<a.length;e+=50){let t=a.slice(e,e+50),o=await Promise.allSettled(t.map(async({docName:e,meta:t,isNew:n,filePath:r})=>({docName:e,meta:t,isNew:n,markdown:await Cl(r,`utf-8`)})));for(let e of o){if(e.status===`rejected`){v9.warn({err:e.reason},`Failed to reconcile file`);continue}let{docName:t,meta:a,isNew:o,markdown:s}=e.value;this.updateDocumentFromMarkdown(t,s),n.set(t,a),o?r++:i++}}let s=0,c=new Set([...this.fileMeta.keys(),...this.state.byDoc.keys()]);for(let e of c)t.has(e)||(this.deleteDocument(e),s++);return this.fileMeta=n,{added:r,updated:i,deleted:s}}applyDocSnapshot(e,t,n){let r=this.state.byDoc.get(e)??new Set;for(let t of r){if(n.has(t))continue;let r=this.state.byTag.get(t);r&&(r.delete(e),r.size===0&&this.state.byTag.delete(t))}for(let t of n){let n=this.state.byTag.get(t);n||(n=new Set,this.state.byTag.set(t,n)),n.add(e)}n.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,n),this.state.byDocLiteral.set(e,t))}async listDocsWithPaths(){let e=[];await this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}async walkContentDir(e,t){let n;try{n=await wl(e,{withFileTypes:!0})}catch(t){v9.warn({dir:e,err:t},`Failed to read directory ${e}`);return}for(let r of n){let n=I(e,r.name);if(r.isDirectory()){let e=Sk(L(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!lS(r.name))continue;let i=Sk(L(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:dS(i),filePath:n})}}};let S9=!1;function C9(){if(S9)return;let e=Oee;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){S9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),S9=!0}catch(e){F(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const zge=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function Bge(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(Y8).join(` `)} auth git-credential`]}function Vge(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Pc(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],NA({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return F(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return F(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
3261
3261
  `)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=R(e,r);if(!TM(a,t))continue;let s=Uk(a,t);i.has(s)||z(a)&&i.set(s,o)}return i}function w9(e){C9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,skipStateManifestCheck:h=!1,singleDocRelPath:g,ephemeral:_=!1}=e,v=F(`server`);function b(){let e=Ha({absPath:Ga(`project`,n),sideline:!1,warn:e=>v.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=Ea(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}`)}v.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function x(){let e=Ha({absPath:Ga(`project-local`,n),sideline:!1,warn:e=>v.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;if(t!=null)return t===!0;e.valid||v.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let r=Ha({absPath:Ga(`project`,n),sideline:!1,warn:e=>v.warn({message:e},`[config] could not read project config`)});return r.valid||v.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),r.value.autoSync?.default===!0}function S(){let e=Ha({absPath:Ga(`project`,n),sideline:!1,warn:e=>v.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?fi(e):Mn}function C(){return xF(n,{configHomedirOverride:l,onWarn:e=>v.warn({message:e},`[config] could not read project-local config`)})}function ee(){let e=Ha({absPath:Ga(`project-local`,n,l),sideline:!1,warn:e=>v.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function ne(e){return`${hF(e.baseUrl)}|${e.model}|${e.dimensions??1536}`}function re(e){let t;(e===`__config__/project`||e===`__local__/project`)&&(t=x(),ct?.setEnabled(t).catch(n=>{v.warn({err:n,enabled:t,docName:e},`[sync] failed to apply autoSync.enabled from config`)}));let n=C();Te.applyConfig({enabled:n.enabled,providerFingerprint:ne(n)}),v.info({docName:e,autoSyncEnabled:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}_o();let ie=Il(),ae=aN(n),w=new Au({localDir:ae,log:F(`acp-registry`)}),se=new wu(ae,F(`acp-permissions`));if(qo(ae,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!h)try{a9({lockDir:ae,shadowRepoDir:ru(n)})}catch(e){throw Ro(ae),e}let ce=Jr(),le=(e,t)=>ce.resolveEmbed(e,t),ue=(e,n)=>{let r=ce.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=R(t,r);if(!Ck(i,R(t)))return null;try{let e=ul(i);return e.isFile()?e.size:null}catch{return null}},de,pe,me,he,ge,_e,T,ve,ye=null,be=null,xe=null,Se=null,Ce=null,we=C(),Te=new Bae({loadEmbedder:e.embedderLoader??(()=>{let t=C();return jae({keyStore:e.embeddingsKeyStore??null,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:I(aN(n),`embeddings`),enabled:we.enabled,providerFingerprint:ne(we)}),Ee=null,De=new Set,Oe=!1,ke=[],Ae,je,Me,Ne=new Promise((e,t)=>{je=e,Me=t});function Pe(e){ye?.signal(e)}let Fe=null;function Ie(){Fe!==null&&clearTimeout(Fe),Fe=setTimeout(()=>{Fe=null,pe.saveToDisk().catch(e=>{F(`backlinks`).warn({err:e},`Failed to persist debounced cache`)}),me.saveToDisk().catch(e=>{F(`tag-index`).warn({err:e},`Failed to persist debounced tag snapshot`)})},2e3)}let Le=null,Re=!1,ze=()=>{try{X7(n,Be.entries())}catch(e){v.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Be=new Zhe(void 0,{onEviction:()=>rre(),onSizeChange:e=>ire(e),onMutate:()=>{!Re||Le!==null||(Le=setTimeout(()=>{Le=null,ze()},2e3))}});for(let[e,r]of ege(n))aS(e)||Zq(e)&&([`.md`,`.mdx`].some(n=>{let r=R(t,`${e}${n}`);return Ck(r,R(t))&&z(r)})||Be.restore(e,r));Re=!0;let Ve=(e,t)=>{aS(e)||Be.setRenamed(e,t)},He=e=>{if(!aS(e)){if(Be.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Be.setDeleted(e)}},Ue=e=>{aS(e)||Be.delete(e)};try{de=WI({projectDir:n,contentDir:t,singleDocRelPath:g,onAfterRebuild:()=>{pe.rebuildFromDisk(kM()).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),me.init().catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),dA(ot).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?F(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):F(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),pe=new YV({projectDir:n,contentDir:t,contentFilter:de}),me=new x9({projectDir:n,contentDir:t,contentFilter:de}),(async()=>{await me.loadFromDisk()?await me.reconcileWithDisk():await me.init()})().catch(e=>{F(`server-factory`).warn({err:e},`[server-factory] tag-index warm boot failed; continuing with empty index`)}),he={current:d},ge=o?Khe({getShadow:()=>he.current??null,getCurrentBranch:()=>st?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:nu(n)??void 0,isWriterLive:e=>{if(!xe&&!ve)return F(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(xe?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of ve?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,_e=zM({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:he,ephemeral:_,contentRoot:f,backlinkIndex:pe,configHomedirOverride:l,getCurrentBranch:()=>st?.getLastKnownBranch()??null,resolveEmbed:le,resolveSize:ue,getPrincipal:()=>Ee,onAgentCommit:()=>ye?.signal(`session-activity`),onFlushCommit:()=>ge?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{ye?.emitDiskAck(e,t),!aS(e)&&KM(r,n)&&(Se?.(),Pe(`files`))},onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),onConfigPersisted:re,isRecentlyRemoved:e=>Be.has(e),mdManager:e.mdManager}),T=new mhe({quiet:r,debounce:i,maxDebounce:a,extensions:[_e.extension]});let p=T;ke.push(Uj(()=>p.documents.size),Wj(()=>_e.getQueueDepths()),Kj(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),Jj(),_||(Ce=Yhe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>_e.forceStore(e,t),readDiskBytes:e=>{let n=wM(e,t),r,i;try{r=ol(n),i=ul(r).size}catch(t){let n=Xo(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new G7(`symlink cycle at content path: ${e}`):t}if(!TM(r,t))throw new G7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new G7(`document exceeds the open byte limit: ${e}`);try{return B(r,`utf-8`)}catch(e){if(Xo(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let h=T.shouldUnloadDocument.bind(T);T.shouldUnloadDocument=e=>{if(De.has(e)||Oe&&h(e))return!0;let t=e.name;return aS(t)||AM(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:h(e)},Ae=async e=>{De.add(e);try{await T.unloadDocument(e)}finally{De.delete(e)}},ye=new cS(T),be=new Bw(T),xe=new Vw(T),ve=new _C(T);let v=ve;ke.push(qj(()=>({active:v.liveSessionCount,limit:v.sessionLimit})));let y=j7({backlinkIndex:pe,tagIndex:me,signalChannel:Pe});T.configuration.extensions.push(y),T.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=vD(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==ie)throw new _D(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${ie}`);let i=n?.expectedBranch,a=kM();if(typeof i==`string`&&i.length>0&&i!==a)throw new _D(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(Ee&&n.principalId===Ee.id?o.principalId=Ee.id:Ee?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Ee.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),T.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!nS(e.documentName)&&!rS(e.documentName))return;let t=e.request,n=t.socket?.remoteAddress;if(n!==void 0&&!yW(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(!bW(i))throw Error(`config-doc admission requires loopback Host header (host=${i??`<absent>`}, doc=${e.documentName})`)}});let x=R(t);function te(e){if(!Zq(e))return null;let t=R(x,_S(e));return Ck(t,x)?t:null}T.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await Qhe(e.documentName,{recentlyRemovedDocs:Be,resolveFilePath:te,fileExists:z})}}),T.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=vD(e.token);whe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>T.documents.get(e)})}}),T.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new i7(e.update);if(t.readVarString(),t.readVarUint()===h7.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${qe} rejected — server-only channel`)}});let ne=$q({hocuspocus:T,sessionManager:ve,contentDir:t,contentFilter:de,serverInstanceId:ie,getFileIndex:()=>ot?ot.getFileIndex():new Map,getAttachmentFolderPath:b,getAllFilesIndex:()=>ot?ot.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ot?.getFileIndexGeneration()??0,mutateFileIndex:e=>ot?.mutateFileIndex(e),getFolderIndex:()=>ot?ot.getFolderIndex():new Map,getAliasMap:()=>ot?ot.getAliasMap():new Map,getFolderAliasIndex:()=>ot?ot.getFolderAliasIndex():new Map,rescanFiles:()=>ot?.rescanFromDisk(),enableTestRoutes:u,shadowRef:he,flushGitCommit:()=>_e.flushPendingGitCommit(),flushContributors:()=>_e.flushContributors(),takeStoreFailure:e=>_e.takeStoreFailure(e),takeStoreDivergence:e=>_e.takeStoreDivergence(e),markAgentWriteStore:e=>_e.markAgentWriteStore(e),getCurrentBranch:()=>st?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,backlinkIndex:pe,tagIndex:me,signalChannel:Pe,agentFocusBroadcaster:be,agentPresenceBroadcaster:xe,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ct,localOpCliArgs:m,projectDir:n,resolveEmbed:le,getPrincipal:()=>Ee,acpRegistry:w,loadAcpCustomAgents:()=>ju(ae,F(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Ae,ready:Ne,recentlyRemovedDocs:Be,serializeDoc:Ye,evictManagedArtifactLkg:e=>{_e.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Te,getSemanticSimilarityFloor:()=>C().similarityFloor,getLinterBaseConfig:()=>S(),getLinkPreviewsEnabled:ee,embeddingsSecretsFile:vF(l),ephemeral:_,onReferencedAssetsCacheInvalidator:e=>{Se=e}});T.configuration.extensions.push(ne),T.configuration.extensions.push(Q7({mdManager:za,schema:Ra,shadowRef:he,contentRoot:f,getCurrentBranch:()=>st?.getLastKnownBranch()??null,resolveEmbed:le,resolveSize:ue})),T.configuration.extensions.push(Fge()),T.configuration.extensions.push(Che({getSyncEngine:()=>ct,projectDir:n,contentDir:t}))}catch(e){for(let e of ke.splice(0))e();throw Ce?.dispose(),Ce=null,Ro(ae),e}let We=null,Ge=new Map,Ke=[];function Je(e,t){let n=R(e,`rescue`),r=R(n,_S(t));return Ck(r,n)?r:null}function Ye(e){let t=T.documents.get(e);return t?lk(t):null}let Xe=(e,t)=>ok(T,e,t,le,ue);function Ze(e){if(!DS(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Qe=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of T.documents){if(aS(n))continue;let r=T.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{ak(r,i,le,n)},ik)}catch(t){v.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},$e=null,et=e=>{e&&($e===null&&($e=new Set,setImmediate(()=>{let e=$e;if($e=null,e)try{for(let t of e)Qe(t)}catch(t){v.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),$e.add(e))};function tt(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 Tk(e)}}async function nt(e){try{switch(e.kind){case`create`:v.info({docName:e.docName},`[reconcile] create: ${e.docName}`),pe.updateDocumentFromMarkdown(e.docName,e.content),Ie(),me.updateDocumentFromMarkdown(e.docName,e.content),Pe(`files`),Pe(`backlinks`),Pe(`graph`),Pe(`tags`),Ue(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=T.documents.get(t);if(!r){pe.updateDocumentFromMarkdown(t,n),Ie(),me.updateDocumentFromMarkdown(t,n),Pe(`backlinks`),Pe(`graph`),Pe(`tags`);return}let i=AM(t)??``,a=Ye(t)??i,o=$D({docName:t,base:i,ours:a,theirs:n}),s=Mk(i).slice(0,6),c=Mk(a).slice(0,6),l=Mk(n).slice(0,6);switch(v.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`:Ze(r),pe.updateDocumentFromMarkdown(t,n),Ie(),me.updateDocumentFromMarkdown(t,n),Pe(`backlinks`),Pe(`graph`),Pe(`tags`);break;case`clean`:try{Xe(t,o.newContent),jM(t,o.newContent),Ix(),Ze(r),pe.updateDocumentFromMarkdown(t,n),Ie(),me.updateDocumentFromMarkdown(t,n),Pe(`backlinks`),Pe(`graph`),Pe(`tags`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),jM(t,n),Ze(r)}break;case`merged`:try{Xe(t,o.newContent),jM(t,n),Ix(),Ze(r),pe.updateDocumentFromMarkdown(t,n),Ie(),me.updateDocumentFromMarkdown(t,n),Pe(`backlinks`),Pe(`graph`),Pe(`tags`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),jM(t,n),Ze(r)}break;case`conflicts`:try{Xe(t,o.newContent),jM(t,o.newContent),Ix(),Lx(),pe.updateDocumentFromMarkdown(t,n),Ie(),me.updateDocumentFromMarkdown(t,n),Pe(`backlinks`),Pe(`graph`),Pe(`tags`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),jM(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{Lx();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=T.documents.get(t);if(!n){pe.deleteDocument(t),Ie(),me.deleteDocument(t),Pe(`files`),Pe(`backlinks`),Pe(`graph`),Pe(`tags`),He(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=AM(t)??``,i=Ye(t)??``,a=i!==r;if(a&&he.current){let e=he.current,n=st?.getLastKnownBranch()??`main`;queueMicrotask(()=>{KO(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{zx(),v.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{v.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),MM(t),pe.deleteDocument(t),Ie(),me.deleteDocument(t),v.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),T.closeConnections(t),await Ae(n),Pe(`files`),Pe(`backlinks`),Pe(`graph`),Pe(`tags`),He(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=T.documents.get(t);if(MM(t),jM(n,r),pe.renameDocument(t,n,r),Ie(),me.renameDocument(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}v.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),Pe(`files`),Pe(`backlinks`),Pe(`graph`),Pe(`tags`),Ve(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=T.documents.get(t);if(!n)return;let r=Ye(t);r===null?v.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):jM(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),v.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ce.add(e.relativePath),Pe(`files`),et(Ic(e.relativePath));break;case`asset-delete`:ce.remove(e.relativePath),Pe(`files`),et(Ic(e.relativePath));break;case`folder-create`:case`folder-delete`:Pe(`files`);break;case`file-create`:case`file-update`:case`file-delete`:Pe(`files`);break;default:Tk(e)}}catch(t){let n=tt(e);v.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let rt=[];async function it(e){if(LM()){rt.push(e);return}await nt(e)}async function at(){let e=rt.splice(0,rt.length);for(let t of e)await nt(t)}let ot=null,st=null,ct=null,lt=null;async function ut(e){if(T.documents.size===0)return;let t=!1,n=new Promise(e=>{T.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(T.documents.keys());T.closeConnections(),T.flushPendingStores();for(let e of T.documents.values())e.getConnectionsCount()===0&&T.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(T.documents.keys()),i=[],o=[];if(he.current){for(let e of n)if(!aS(e))try{let t=Ye(e);if(t===null){v.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Je(he.current.gitDir,e);if(!n){v.warn({docName:e,gitDir:he.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}$c(Rc(n),{recursive:!0}),fl(n,t,`utf-8`),zx(),i.push(e),v.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),v.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else v.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 dt(){return lt||(lt=(async()=>{let e=Date.now(),t=[];Oe=!0;for(let e of ke.splice(0))e();try{await Ce?.dispose()}catch(e){v.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Ce=null;try{Jo(ae)}catch(e){v.warn({err:e},`[server] failed to mark server.lock draining`)}if(Fe!==null&&(clearTimeout(Fe),Fe=null),me.close(),Le!==null&&(clearTimeout(Le),Le=null),Re)try{X7(n,Be.entries())}catch(e){v.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([Ne.then(()=>`completed`,e=>(v.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&v.warn({},`[server] init did not complete within 5s during shutdown`);let a=T.documents.size;ge?.destroy();try{try{try{st&&=(await st.unsubscribe(),null),ot&&=(await ot.unsubscribe(),null);for(let{docName:e,cleanup:t}of Ke)try{await t()}catch(t){v.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Ke.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),xe?.destroy(),We&&=(await We.disconnect(),null);for(let[e,t]of Ge)try{await t.disconnect()}catch(t){v.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ge.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await wre()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await ut(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await _e.flushPendingGitCommit(),await _e.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ct&&=(await ct.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(he.current){try{let e=(await Ao({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&fl(R(he.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{DO(he.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?v.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):v.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Ro(ae,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await go()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),lt)}let ft=[];async function pt(){try{Ee=await K7(n),v.info({principalId:Ee.id},`[server] principal loaded`)}catch(e){v.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!he.current)try{he.current=await EO(n),v.info({gitDir:he.current.gitDir},`[server] history repo initialized at ${he.current.gitDir}`)}catch(e){v.error({err:e},`[server] history repo init failed`),ft.push(`shadow-repo`)}if(he.current){let e=null;try{e=qA(he.current.gitDir),gj(he.current.gitDir,e),QA(he.current.gitDir,e),v.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){v.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([_j(he.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){v.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ge?.runBootMaintenance()}catch(e){v.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(he.current)try{await CO(he.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`)){v.warn({},`[server] history repo appears corrupted — reinitializing`);try{he.current=await EO(n)}catch(e){v.error({err:e},`[server] history repo reinit failed`),he.current=void 0,ft.includes(`shadow-repo`)||ft.push(`shadow-repo`)}}else v.error({err:e},`[server] history repo check failed (transient?)`)}if(he.current)try{let e=R(he.current.gitDir,`last-known-head`),t=null;try{t=B(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Ao({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Ao({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}v.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await HO(he.current,f??``,t,r,e),Rx()}catch(e){v.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else v.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{fl(e,r,`utf-8`)}catch(e){v.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){v.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=BW(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;v.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){v.error({err:e},`[server] managed rename recovery failed`),ft.push(`managed-rename-recovery`)}try{let e=gV(n);(e.deleted>0||e.errors>0)&&v.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){v.error({err:e},`[server] upload-tempfile sweep failed`),ft.push(`upload-tempfile-sweep`)}try{We=await T.openDirectConnection(qe),ye?.emitServerInfo(ie,kM())}catch(e){v.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),ft.push(`cc1-push`)}let r=_?[]:y;for(let e of r)try{let t=await T.openDirectConnection(e);Ge.set(e,t)}catch(t){v.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),ft.push(`config-doc:${e}`)}let i=new Map([[At,Ga(`project`,n)],[oe,Ga(`project-local`,n)],[te,Ga(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{v.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await bhe(t,t=>{let n=T.documents.get(e);v.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=UD(n??null,e,t,_e.configPersistenceCtx);v.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),re(e)});Ke.push({docName:e,cleanup:n}),v.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){v.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),ft.push(`config-file-watcher:${e}`)}}if(!_){let e=(e,t)=>{let n=bA(e,_e.managedArtifactCtx);if(!n)return;let r=CA(T.documents.get(n)??null,n,t,_e.managedArtifactCtx);v.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),fe(n)&&pe.ingestGlobalSkillBundles(gA(_e.managedArtifactCtx),kM()).then(()=>{Pe(`backlinks`),Pe(`graph`)}).catch(e=>{v.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=gA(_e.managedArtifactCtx),n=await U7(t,e);Ke.push({docName:`__skill-files__`,cleanup:n}),v.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){v.warn({err:e},`[managed-artifact-watcher] skills failed to start`),ft.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of cP(n).templates)t.add(e.source_folder)}catch(e){v.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?R(n,e,`.ok`,`templates`):R(n,`.ok`,`templates`)),i=await U7(r,e,Jhe);Ke.push({docName:`__template-files__`,cleanup:i}),v.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){v.warn({err:e},`[managed-artifact-watcher] templates failed to start`),ft.push(`managed-artifact-watcher:templates`)}}try{let e=R(t,`.okignore`),r=R(n,`.gitignore`),i=null;try{let e=Pc(`git`,[`rev-parse`,`--git-common-dir`],NA({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=I(R(n,e.stdout.trim()),`info`,`exclude`);z(Rc(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=v;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:_},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=_?null:await xhe(a,(t,r)=>{(async()=>{if(t===e)try{let e=UD(T.documents.get(`__config__/okignore`)??null,bi,r,_e.configPersistenceCtx);o.info({docName:bi,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:L(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await de.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:L(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=L(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:L(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Ke.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){v.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),ft.push(`ignore-files-watcher`)}let a=A7(n).branch??`main`;OM(a),pe.switchBranch(a);let o=performance.now();try{await qa(`ok.boot.indexes`,void 0,async()=>{let e=kM();try{if(await pe.loadFromDisk(e)){let t=await pe.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&v.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)aS(e)||Be.peek(e)?.kind!==`renamed`&&(Be.setDeleted(e),n++);n>0&&v.info({count:n},`[removal-guard] tombstoned docs deleted while the server was down`)}else await pe.rebuildFromDisk(e);try{await pe.ingestGlobalSkillBundles(gA(_e.managedArtifactCtx),e)}catch(t){v.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}pe.saveToDisk().catch(t=>{F(`backlinks`).warn({branch:e,err:t},`Failed to persist startup cache for ${e}`)})}catch(t){v.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let n=performance.now();ot=await qa(`ok.boot.seed-walk`,void 0,async()=>uA(t,it,de)),eH(`seedWalkMs`,Math.round(performance.now()-n));{let e=R(t),n=0;for(let[t]of Be.entries()){if(!Zq(t))continue;let r=R(e,`${t}${gS(t)}`);Ck(r,e)&&z(r)&&(Be.delete(t),n++)}n>0&&v.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{let e=await me.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&v.info(e,`[tag-index] startup reconcile: offline changes applied`),me.saveToDisk().catch(e=>{F(`tag-index`).warn({err:e},`Failed to persist startup tag snapshot`)})}catch(e){v.error({err:e},`[tag-index] startup reconcile failed; tag index updates incrementally via watcher events`),ft.push(`tag-index`)}let r=0;try{g===void 0?await nJ({contentDir:t,contentFilter:de,basenameIndex:ce,onSkip:(e,t,n)=>{r++,v.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):tJ({contentDir:t,basenameIndex:ce,onSkip:(e,t,n)=>{r++,v.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),r>0&&(v.warn({count:r},`[basename-index] startup seed completed with ${r} skipped entries — embeds under inaccessible subtrees will not resolve`),ft.push(`basename-index-partial`))}catch(e){v.error({err:e},`[basename-index] startup seed failed`),ft.push(`basename-index`)}})}catch(e){v.error({err:e},`[server] disk bridge watcher failed to start`),ft.push(`file-watcher`)}finally{eH(`indexesMs`,Math.round(performance.now()-o)),ot&&tH(`fileCount`,ot.getFileIndex().size)}try{st=await khe(n,async({trigger:e})=>{if(v.info({trigger:e},`[batch] begin trigger=${e}`),vne(),T.flushPendingStores(),await _e.flushPendingGitCommit(),IM(!0),he.current){let e=kM(),t=A7(n).branch??e,r=[];for(let[e,t]of T.documents){if(aS(e))continue;let n=null;if(t.transact(()=>{n=Ye(e)},zge),n===null)continue;let i=AM(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await QO(he.current,e,BO.id,r,t);n&&(xne(),v.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){v.error({err:e},`[shadow] park failed`)}}},async e=>{let r=rt.length,i=e.newBranch??`main`;if(v.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(IM(!1),await at(),e.headMoved&&e.newHead){let r=Vge(n,R(t),e.oldHead,e.newHead);if(r.size>0){Hie(r.keys());for(let[e,t]of r)GD(e,Nee(t.email),t.name,t.email,_u(e));await _e.flushContributors()}}if(await _e.flushDeferredStores(`within-branch`),ct!==null)try{await ct.reconcileConflictsFromGit()}catch(e){v.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{bne(),rt.splice(0,rt.length),OM(i),Fe!==null&&(clearTimeout(Fe),Fe=null),pe.switchBranch(i),de.rebuildDirCount();try{let e=0;ce.clear(),await nJ({contentDir:t,contentFilter:de,basenameIndex:ce,onSkip:(t,n,r)=>{e++,v.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(v.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`),ft.includes(`basename-index-partial`)||ft.push(`basename-index-partial`))}catch(e){v.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of T.documents)if(!aS(e))try{let r=wM(e,t);if(!z(r)){let t=AM(e)??``,r=Ye(e)??``;if(r!==t&&he.current){let t=he.current;queueMicrotask(()=>{KO(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{zx(),v.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{v.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),v.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=B(r,`utf-8`);Xe(e,a),jM(e,a),v.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){v.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}v.info({branch:i,docCount:T.documents.size},`[branch-switch] loaded branch ${i} (${T.documents.size} docs)`);try{if(await pe.loadFromDisk(i)){let e=await pe.reconcileWithDisk(i);(e.added>0||e.updated>0||e.deleted>0)&&v.info(e,`[backlinks] branch-switch reconcile for ${i}`)}else await pe.rebuildFromDisk(i);try{await pe.ingestGlobalSkillBundles(gA(_e.managedArtifactCtx),i)}catch(e){v.warn({err:e,branch:i},`[backlinks] branch-switch global skill bundle ingest failed`)}pe.saveToDisk(i).catch(e=>{F(`backlinks`).warn({branch:i,err:e},`Failed to persist branch cache for ${i}`)})}catch(e){v.error({err:e,branch:i},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}try{let e=await me.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&v.info(e,`[tag-index] branch-switch reconcile for ${i}`)}catch(e){v.warn({err:e,branch:i},`[tag-index] branch-switch reconcile failed; falling back to full rebuild`),await me.init()}if(me.saveToDisk().catch(e=>{F(`tag-index`).warn({branch:i,err:e},`Failed to persist tag snapshot after branch switch`)}),he.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of T.documents)if(!aS(t))try{let n=await ek(he.current,i,BO.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=AM(t);if(!r)continue;let a=$D({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:Xe(t,a.newContent),jM(t,a.newContent),e++;break;case`conflicts`:Xe(t,a.newContent),jM(t,a.newContent),Lx(),e++;{let e=T.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){v.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&v.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&he.current)try{let t=CO(he.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await vO(he.current).withMutator(async()=>{for(let e of n.split(`
3262
- `))e&&await t.raw(`update-ref`,`-d`,e)}),v.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){v.error({err:e},`[branch-switch] detached cleanup failed`)}IM(!1),await _e.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&he.current&&r>0){let t=f??`.`;try{let n=await HO(he.current,t,e.oldHead,e.newHead,i);Rx(),v.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){v.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){v.error({err:e},`[server] HEAD watcher failed to start`),ft.push(`head-watcher`)}function s(e){for(let r of e)try{let e=Sk(L(t,I(n,r)));if(e.startsWith(`..`))continue;let i=dS(e),a=T.documents.get(i);if(!a)continue;let o=Ye(i);o===null?v.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):jM(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),v.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){v.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}let c=Bge(m);try{ct=new Nge({projectDir:n,contentDir:t,contentFilter:de,contentRoot:f,syncEnabled:x(),credentialArgs:c,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{IM(e),e||_e.flushDeferredStores(`within-branch`).catch(e=>{v.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{v.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:s,onAutoDisable:async e=>{v.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await io({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||v.error({result:t,reason:e,humanError:ha(t.error),configPath:Ga(`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 ct.start()}catch(e){v.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ct=null}Pe(`files`),Pe(`backlinks`),Pe(`graph`),Pe(`tags`);let u=$V();u!==void 0&&eH(`readyMs`,u)}return pt().then(je,Me),{hocuspocus:T,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:be,agentPresenceBroadcaster:xe,maintenanceCoordinator:ge,contentFilter:de,basenameIndex:ce,serverInstanceId:ie,destroy:dt,ready:Ne,degraded:ft,lockDir:ae,get syncEngine(){return ct},resolveEmbed:le,acpRegistry:w,acpPermissions:se}}function T9(e){return e/1048576}function Hge(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:T9(e.rss),heapTotalMb:T9(e.heapTotal),heapUsedMb:T9(e.heapUsed),externalMb:T9(e.external),arrayBuffersMb:T9(e.arrayBuffers)}}}let E9=null,D9=null,O9=null;const k9=1e6;let A9=null,j9=null;Ka(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function Uge(){if(E9)return;let e=vo().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=Hge();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),E9=e}function Wge(){if(!D9){let e=vo().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!A9){A9=Vl({resolution:20}),A9.enable();return}e.observe(A9.percentile(50)/k9,{stat:`p50`}),e.observe(A9.percentile(99)/k9,{stat:`p99`}),A9.reset()}),D9=e}if(!O9){let e=vo().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=j9;if(j9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),O9=e}}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=aN(e);M9=new Do({currentPath:R(t,`tolerance-telemetry.jsonl`),previousPath:R(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Ii(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){Ii(null),await M9?.drain(),M9=null,N9=!1}Ia();const Gge=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],Kge=[`cache`,`tmp`];function qge(e){let t=R(e,va);if(!(()=>{if(!z(t))return!0;try{return il(t).length===0}catch{return!0}})())return[];let n=[];for(let t of Gge)z(R(e,t))&&n.push(t);for(let t of Kge){let r=R(e,t);try{z(r)&&ul(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function Jge(e){let t=tu(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const L9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function Yge(e){QV();let t=e.projectDir??e.contentDir,n=yJ({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}Co.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}_o({localSink:n?.telemetry}),F9(t),Uge(),Wge();let{kind:r,gitdir:i}=Jge(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=so(i));let o=dJ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>qa(`ok.boot`,{attributes:a},async()=>Xge(e)),l=()=>{if(s)try{let e=Pa.extract(La.active(),{traceparent:s});return La.with(e,c)}catch(e){F(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function Xge(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??F(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=e.lockKind??a??`interactive`,{createServer:s}=await import(`node:http`),{markServerLockDraining:c,releaseServerLock:l,updateServerLockPort:u}=await import(`./server-lock-DTx_Ih9P.mjs`),d=!1;if(!t&&e.autoInitFn)try{d=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let f=e.projectDir??e.contentDir,p=R(f,`.ok`);if(!z(R(p,`config.yml`)))throw new D5(z(p)?`config`:`okdir`,f);let m=R(p,`.gitignore`);z(m)||F(`boot`).warn({path:m},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let h=e.gitPreflight??Uz;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof Bz||e instanceof Vz){let t=e instanceof Vz?e.detected:``,n=e instanceof Vz?`too_old`:`not_available`;rW(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 go(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let g=qge(p);g.length>0&&F(`boot`).warn({files:g},`Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${va}/.`);let _=w9({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:o,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:v,destroy:y,ready:b,degraded:x,lockDir:S,sessionManager:C,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne}=_,re=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ie=e.port??0,ae=e.ephemeral?void 0:x5({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${re}:${ie}`,log:i}),w=s();w.headersTimeout=3e4,w.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:rN({contentFilter:_.contentFilter,contentSirv:Qo(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:qi,assetExtensions:Bi,blocklistExtensions:Xi}),se=!1;if(e.reactShellDistDir)try{nV(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof tV)i.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:S},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await y().catch(()=>{}),l(S),e}let ce=e.reactShellDistDir?Qo(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,le=e.ephemeral?null:new Iw({contentDir:e.contentDir,localDir:S,registry:_.acpRegistry,permissions:_.acpPermissions,sessionManager:C,agentPresenceBroadcaster:te,resolveEmbed:_.resolveEmbed,isExcludedPath:e=>_.contentFilter.isExcluded(e),isIgnoredPath:e=>_.contentFilter.isPathIgnored(e),getLoadedDocText:e=>v.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${re}:${ie}`,getMcpStdioCommand:()=>Fw(e.localOpCliArgs,ie),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:i});le!==null&&await le.init();let ue=C5({httpServer:w,hocuspocus:v,mcpHttpHandler:ae,log:i,sessionManager:C,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:ce,ephemeral:e.ephemeral,acpThreadManager:le}),de=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},fe=null;r!==null&&(fe=fJ({httpServer:w,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await de()})})),await R9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);w.once(`error`,r),w.listen(e.port,e.host,()=>{w.removeListener(`error`,r),t()})})}catch(e){if(se)try{aV(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),l(S),e}let pe=$V();pe!==void 0&&eH(`httpListenMs`,pe);let me=w.address(),he=typeof me==`object`&&me?me.port:e.port??0;if(ie=he,u(S,he),se&&rV(S,he),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let ge=!1,_e=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};de=async()=>{if(ge)return;ge=!0;let e=[],t=async(t,n)=>{try{await _e(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{c(S),se&&oV(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{fe?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(le!==null&&await t(`acpThreads.destroy`,()=>le.destroy()),await t(`mount.shutdown`,()=>ue.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ue.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{w.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{w.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),se&&await t(`releaseUiLock`,async()=>aV(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>go()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Co.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await qB({projectDir:f,skillsRoot:R(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&i.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){i.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:w,destroy:de,lockDir:S,contentDir:e.contentDir,port:he,ready:b,degraded:x,didAutoInit:d,serverInstance:_,acpThreadManager:le}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new aJ(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=nu(n),t=e?I(e,`MERGE_HEAD`):null;if(!t||!z(t)){i.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:a.length}));return}let r=Mo({baseDir:n,timeout:{block:5e3}});o=new Set(await cO(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=dS(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const Zge=sa;function Qge(e={}){let t=e.home??hl(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?z(I(t,`Library`,`Application Support`,`Claude`)):n===`win32`?z(I(r.APPDATA??I(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(Eo(),1);const B9=I(hl(),`.ok`,`logs`),$ge=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function e_e(){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 t_e(e){$c(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function n_e(e){try{if(ul(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{sl(n,r)}catch{}}try{dl(`${e}.3`)}catch{}}function r_e(e){try{let t=Date.now(),n=10080*60*1e3,r=il(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ul(I(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{dl(I(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{dl(I(e,t.name)),a-=t.size}catch{}}}catch{}}function i_e(e){t_e(B9);let t=V9(),n=e.filePath??I(B9,`${e.name}.${t}.log`);n_e(n),(e._setTimeout??setTimeout)(()=>r_e(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:e_e(),name:e.name,redact:{paths:$ge,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function a_e(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function o_e(e){return I(B9,`${e}.${V9()}.log`)}function s_e(){return B9}function c_e(e){let t=R(e),n=0;for(;n<30;){let e=!1;try{e=z(R(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=Rc(t);if(r===t)return null;t=r,n+=1}return null}const H9=Kl(Mc),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function l_e(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],NA({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function u_e(e){let t=R(e),n=R(t,`.git`),r=R(n,`HEAD`),i=!1;if(z(n)){if(!ul(n).isDirectory()||z(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=Uz()}catch(e){throw e instanceof Bz||e instanceof Vz?(rW(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof Vz?`too_old`:`not_available`,detectedVersion:e instanceof Vz?e.detected:``},e instanceof Vz?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await l_e(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],NA({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(!z(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,d_e=cn.map(e=>e.replace(/\/$/,``));async function f_e(e){let t=nu(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(g_e(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=No(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await jo(async()=>{let t=await p_e(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await m_e(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=No(e,{gitIndexFile:I(vl(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await h_e(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await xH(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Fo(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${_i}\` 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 d_e){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function p_e(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function m_e(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function h_e(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function g_e(e){return z(I(e,`MERGE_HEAD`))||z(I(e,`rebase-merge`))||z(I(e,`rebase-apply`))||z(I(e,`CHERRY_PICK_HEAD`))||z(I(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function __e(e,t){let n;try{n=jc(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=Rc(n),r=0;r<32;r+=1){let n=I(t,`package.json`);if(z(n))try{let t=JSON.parse(await Cl(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=Rc(t);if(r===t)return;t=r}}const v_e=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of v_e)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function y_e(e){if(!lS(e))throw new $9(e);let t;try{t=ol(R(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ul(t).isFile())throw new Q9(e);let n=Rc(t),r=aH(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:dS(L(b_e(e),t).split(Uc).join(`/`)),canonicalFilePath:t}}let i=Ic(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:dS(i)}}function b_e(e){return R(e,Ha({absPath:Ga(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function x_e(e){let t=el(R(vl(),`ok-ephemeral-`)),n=R(t,`.ok`);return $c(n,{recursive:!0}),fl(R(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),fl(R(n,`.gitignore`),`local/
3262
+ `))e&&await t.raw(`update-ref`,`-d`,e)}),v.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){v.error({err:e},`[branch-switch] detached cleanup failed`)}IM(!1),await _e.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&he.current&&r>0){let t=f??`.`;try{let n=await HO(he.current,t,e.oldHead,e.newHead,i);Rx(),v.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){v.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){v.error({err:e},`[server] HEAD watcher failed to start`),ft.push(`head-watcher`)}function s(e){for(let r of e)try{let e=Sk(L(t,I(n,r)));if(e.startsWith(`..`))continue;let i=dS(e),a=T.documents.get(i);if(!a)continue;let o=Ye(i);o===null?v.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):jM(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),v.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){v.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}let c=Bge(m);try{ct=new Nge({projectDir:n,contentDir:t,contentFilter:de,contentRoot:f,syncEnabled:x(),credentialArgs:c,cc1Broadcaster:ye,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{IM(e),e||_e.flushDeferredStores(`within-branch`).catch(e=>{v.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{v.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:s,onAutoDisable:async e=>{v.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await io({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||v.error({result:t,reason:e,humanError:ha(t.error),configPath:Ga(`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 ct.start()}catch(e){v.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ct=null}Pe(`files`),Pe(`backlinks`),Pe(`graph`),Pe(`tags`);let u=$V();u!==void 0&&eH(`readyMs`,u)}return pt().then(je,Me),{hocuspocus:T,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:be,agentPresenceBroadcaster:xe,maintenanceCoordinator:ge,contentFilter:de,basenameIndex:ce,serverInstanceId:ie,destroy:dt,ready:Ne,degraded:ft,lockDir:ae,get syncEngine(){return ct},resolveEmbed:le,acpRegistry:w,acpPermissions:se}}function T9(e){return e/1048576}function Hge(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:T9(e.rss),heapTotalMb:T9(e.heapTotal),heapUsedMb:T9(e.heapUsed),externalMb:T9(e.external),arrayBuffersMb:T9(e.arrayBuffers)}}}let E9=null,D9=null,O9=null;const k9=1e6;let A9=null,j9=null;Ka(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function Uge(){if(E9)return;let e=vo().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=Hge();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),E9=e}function Wge(){if(!D9){let e=vo().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!A9){A9=Vl({resolution:20}),A9.enable();return}e.observe(A9.percentile(50)/k9,{stat:`p50`}),e.observe(A9.percentile(99)/k9,{stat:`p99`}),A9.reset()}),D9=e}if(!O9){let e=vo().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=j9;if(j9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),O9=e}}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=aN(e);M9=new Do({currentPath:R(t,`tolerance-telemetry.jsonl`),previousPath:R(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Ii(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){Ii(null),await M9?.drain(),M9=null,N9=!1}Ia();const Gge=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],Kge=[`cache`,`tmp`];function qge(e){let t=R(e,va);if(!(()=>{if(!z(t))return!0;try{return il(t).length===0}catch{return!0}})())return[];let n=[];for(let t of Gge)z(R(e,t))&&n.push(t);for(let t of Kge){let r=R(e,t);try{z(r)&&ul(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function Jge(e){let t=tu(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const L9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function Yge(e){QV();let t=e.projectDir??e.contentDir,n=yJ({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}Co.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}_o({localSink:n?.telemetry}),F9(t),Uge(),Wge();let{kind:r,gitdir:i}=Jge(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=so(i));let o=dJ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>qa(`ok.boot`,{attributes:a},async()=>Xge(e)),l=()=>{if(s)try{let e=Pa.extract(La.active(),{traceparent:s});return La.with(e,c)}catch(e){F(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function Xge(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??F(`boot`),a=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,o=e.lockKind??a??`interactive`,{createServer:s}=await import(`node:http`),{markServerLockDraining:c,releaseServerLock:l,updateServerLockPort:u}=await import(`./server-lock-DZZ64TDY.mjs`),d=!1;if(!t&&e.autoInitFn)try{d=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let f=e.projectDir??e.contentDir,p=R(f,`.ok`);if(!z(R(p,`config.yml`)))throw new D5(z(p)?`config`:`okdir`,f);let m=R(p,`.gitignore`);z(m)||F(`boot`).warn({path:m},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let h=e.gitPreflight??Uz;try{e.gitEnabled!==!1&&h()}catch(e){if(e instanceof Bz||e instanceof Vz){let t=e instanceof Vz?e.detected:``,n=e instanceof Vz?`too_old`:`not_available`;rW(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 go(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let g=qge(p);g.length>0&&F(`boot`).warn({files:g},`Found legacy runtime files at .ok/${g.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${va}/.`);let _=w9({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:o,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:v,destroy:y,ready:b,degraded:x,lockDir:S,sessionManager:C,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne}=_,re=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ie=e.port??0,ae=e.ephemeral?void 0:x5({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${re}:${ie}`,log:i}),w=s();w.headersTimeout=3e4,w.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:rN({contentFilter:_.contentFilter,contentSirv:Qo(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:qi,assetExtensions:Bi,blocklistExtensions:Xi}),se=!1;if(e.reactShellDistDir)try{nV(S,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof tV)i.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:S},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await y().catch(()=>{}),l(S),e}let ce=e.reactShellDistDir?Qo(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,le=e.ephemeral?null:new Iw({contentDir:e.contentDir,localDir:S,registry:_.acpRegistry,permissions:_.acpPermissions,sessionManager:C,agentPresenceBroadcaster:te,resolveEmbed:_.resolveEmbed,isExcludedPath:e=>_.contentFilter.isExcluded(e),isIgnoredPath:e=>_.contentFilter.isPathIgnored(e),getLoadedDocText:e=>v.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${re}:${ie}`,getMcpStdioCommand:()=>Fw(e.localOpCliArgs,ie),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:i});le!==null&&await le.init();let ue=C5({httpServer:w,hocuspocus:v,mcpHttpHandler:ae,log:i,sessionManager:C,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:ce,ephemeral:e.ephemeral,acpThreadManager:le}),de=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},fe=null;r!==null&&(fe=fJ({httpServer:w,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await de()})})),await R9({hocuspocus:v,projectDir:e.projectDir??e.contentDir,log:i});try{await new Promise((t,n)=>{let r=e=>n(e);w.once(`error`,r),w.listen(e.port,e.host,()=>{w.removeListener(`error`,r),t()})})}catch(e){if(se)try{aV(S)}catch(e){i.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await y().catch(()=>{}),l(S),e}let pe=$V();pe!==void 0&&eH(`httpListenMs`,pe);let me=w.address(),he=typeof me==`object`&&me?me.port:e.port??0;if(ie=he,u(S,he),se&&rV(S,he),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:S,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let ge=!1,_e=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};de=async()=>{if(ge)return;ge=!0;let e=[],t=async(t,n)=>{try{await _e(t,n)}catch(n){e.push(n),i.warn({err:n,step:t},`bootServer destroy step failed`)}};try{c(S),se&&oV(S)}catch(e){i.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{fe?.detach()}catch(t){e.push(t),i.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(le!==null&&await t(`acpThreads.destroy`,()=>le.destroy()),await t(`mount.shutdown`,()=>ue.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ue.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{w.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{w.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>y()),se&&await t(`releaseUiLock`,async()=>aV(S,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>go()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>Co.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await qB({projectDir:f,skillsRoot:R(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&i.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){i.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:w,destroy:de,lockDir:S,contentDir:e.contentDir,port:he,ready:b,degraded:x,didAutoInit:d,serverInstance:_,acpThreadManager:le}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new aJ(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=nu(n),t=e?I(e,`MERGE_HEAD`):null;if(!t||!z(t)){i.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:a.length}));return}let r=Mo({baseDir:n,timeout:{block:5e3}});o=new Set(await cO(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=dS(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const Zge=sa;function Qge(e={}){let t=e.home??hl(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?z(I(t,`Library`,`Application Support`,`Claude`)):n===`win32`?z(I(r.APPDATA??I(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(Eo(),1);const B9=I(hl(),`.ok`,`logs`),$ge=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function e_e(){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 t_e(e){$c(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function n_e(e){try{if(ul(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{sl(n,r)}catch{}}try{dl(`${e}.3`)}catch{}}function r_e(e){try{let t=Date.now(),n=10080*60*1e3,r=il(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ul(I(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{dl(I(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{dl(I(e,t.name)),a-=t.size}catch{}}}catch{}}function i_e(e){t_e(B9);let t=V9(),n=e.filePath??I(B9,`${e.name}.${t}.log`);n_e(n),(e._setTimeout??setTimeout)(()=>r_e(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:e_e(),name:e.name,redact:{paths:$ge,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function a_e(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function o_e(e){return I(B9,`${e}.${V9()}.log`)}function s_e(){return B9}function c_e(e){let t=R(e),n=0;for(;n<30;){let e=!1;try{e=z(R(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=Rc(t);if(r===t)return null;t=r,n+=1}return null}const H9=Kl(Mc),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function l_e(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],NA({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function u_e(e){let t=R(e),n=R(t,`.git`),r=R(n,`HEAD`),i=!1;if(z(n)){if(!ul(n).isDirectory()||z(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=Uz()}catch(e){throw e instanceof Bz||e instanceof Vz?(rW(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof Vz?`too_old`:`not_available`,detectedVersion:e instanceof Vz?e.detected:``},e instanceof Vz?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await l_e(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],NA({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(!z(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,d_e=cn.map(e=>e.replace(/\/$/,``));async function f_e(e){let t=nu(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(g_e(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=No(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await jo(async()=>{let t=await p_e(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await m_e(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=No(e,{gitIndexFile:I(vl(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await h_e(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await xH(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Fo(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${_i}\` 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 d_e){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function p_e(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function m_e(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function h_e(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function g_e(e){return z(I(e,`MERGE_HEAD`))||z(I(e,`rebase-merge`))||z(I(e,`rebase-apply`))||z(I(e,`CHERRY_PICK_HEAD`))||z(I(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function __e(e,t){let n;try{n=jc(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=Rc(n),r=0;r<32;r+=1){let n=I(t,`package.json`);if(z(n))try{let t=JSON.parse(await Cl(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=Rc(t);if(r===t)return;t=r}}const v_e=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of v_e)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function y_e(e){if(!lS(e))throw new $9(e);let t;try{t=ol(R(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ul(t).isFile())throw new Q9(e);let n=Rc(t),r=aH(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:dS(L(b_e(e),t).split(Uc).join(`/`)),canonicalFilePath:t}}let i=Ic(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:dS(i)}}function b_e(e){return R(e,Ha({absPath:Ga(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function x_e(e){let t=el(R(vl(),`ok-ephemeral-`)),n=R(t,`.ok`);return $c(n,{recursive:!0}),fl(R(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),fl(R(n,`.gitignore`),`local/
3263
3263
  `,`utf-8`),t}export{m4 as $,Ux as $i,xL as $n,NO as $r,RH as $t,r9 as A,Bw as Ai,fz as An,Zj as Ar,$W as At,A7 as B,uC as Bi,HR as Bn,Uk as Br,bW as Bt,w9 as C,pD as Ci,Iz as Cn,Tae as Cr,SG as Ct,n9 as D,vD as Di,mz as Dn,rN as Dr,lG as Dt,$7 as E,yie as Ei,vz as En,oN as Er,YW as Et,Hhe as F,Ere as Fi,iz as Fn,Zk as Fr,nG as Ft,x5 as G,nS as Gi,qL as Gn,Ok as Gr,rW as Gt,D5 as H,W as Hi,UR as Hn,Xk as Hr,sW as Ht,z7 as I,mC as Ii,nz as In,Mk as Ir,aG as It,b4 as J,aS as Ji,jL as Jn,sk as Jr,YU as Jt,v5 as K,oS as Ki,ML as Kn,ik as Kr,$U as Kt,R7 as L,_C as Li,JR as Ln,jk as Lr,tG as Lt,Q7 as M,Iw as Mi,hz as Mn,gM as Mr,cG as Mt,K7 as N,jw as Ni,pz as Nn,NA as Nr,dG as Nt,a9 as O,nD as Oi,gz as On,zM as Or,sG as Ot,L7 as P,Fw as Pi,rz as Pn,Tk as Pr,rG as Pt,Qoe as Q,Xx as Qi,TL as Qn,BO as Qr,kH as Qt,Ahe as R,pC as Ri,tz as Rn,Qk as Rr,GW as Rt,I9 as S,_D as Si,Pz as Sn,wae as Sr,iq as St,x9 as T,hD as Ti,Oz as Tn,iN as Tr,mG as Tt,C5 as U,TS as Ui,WR as Un,uA as Ur,aW as Ut,E5 as V,ES as Vi,RR as Vn,Ak as Vr,yW as Vt,w5 as W,cS as Wi,hR as Wn,Yk as Wr,nW as Wt,S4 as X,eS as Xi,CL as Xn,RO as Xr,NH as Xt,x4 as Y,tS as Yi,wL as Yn,YO as Yr,TH as Yt,D4 as Z,Qx as Zi,EL as Zn,zO as Zr,PH as Zt,Zge as _,JD as _i,Hz as _n,yF as _r,GK as _t,y_e as a,Au as aa,JO as ai,YV as an,Roe as ar,V2 as at,F9 as b,KD as bi,Lz as bn,Pae as br,pq as bt,f_e as c,wu as ca,tk as ci,nV as cn,RF as cr,U0 as ct,c_e as d,lu as da,ZD as di,rV as dn,zF as dr,tZ as dt,dre as ea,HO as ei,FH as en,gL as er,p4 as et,i_e as f,ru as fa,$D as fi,Bz as fn,BF as fr,AX as ft,Qge as g,Uie as gi,oB as gn,xF as gr,nJ as gt,s_e as h,YD as hi,Uz as hn,kF as hr,rJ as ht,x_e as i,oh as ia,EO as ii,iH as in,WI as ir,e4 as it,i9 as j,zw as ji,dz as jn,Qj as jr,eG as jt,e9 as k,Vw as ki,_z as kn,wM as kr,uG as kt,W9 as l,ou as la,CO as li,iV as ln,LF as lr,RX as lt,o_e as m,Yl as ma,Gie as mi,Rz as mn,EF as mr,fJ as mt,Z9 as n,ih as na,IO as ni,IH as nn,mL as nr,Q2 as nt,X9 as o,Tu as oa,GO as oi,HV as on,gI as or,z2 as ot,a_e as p,Xl as pa,QD as pi,Vz as pn,FF as pr,PX as pt,o5 as q,rS as qi,NL as qn,ok as qr,QU as qt,$9 as r,sh as ra,XO as ri,aH as rn,hL as rr,$2 as rt,__e as s,ju as sa,KO as si,tV as sn,hI as sr,B2 as st,Q9 as t,ah as ta,kO as ti,DH as tn,bL as tr,o4 as tt,u_e as u,au as ua,XD as ui,aV as un,VF as ur,fX as ut,Yge as v,GD as vi,Yz as vn,bF as vr,WK as vt,C9 as w,gD as wi,jz as wn,aN as wr,yG as wt,P9 as x,mD as xi,Fz as xn,Nae as xr,$q as xt,R9 as y,qD as yi,Gz as yn,Mae as yr,fq as yt,j7 as z,Nre as zi,VR as zn,Jk as zr,KW as zt};
3264
- //# sourceMappingURL=src-BEaiZuXz.mjs.map
3264
+ //# sourceMappingURL=src-DxAg43k_.mjs.map