@inkeep/open-knowledge 0.46.0-beta.22 → 0.46.0-beta.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.md +0 -10
- package/dist/{acp-harness-probe-CRn8eK5E.mjs → acp-harness-probe-CNr_uL76.mjs} +2 -2
- package/dist/cli.mjs +7 -7
- package/dist/config-schema.json +108 -13
- package/dist/config.user.schema.json +108 -13
- package/dist/constants-Bi35H8-Y.mjs +2 -0
- package/dist/fs-traced-CbQ-GS7x.mjs +1 -0
- package/dist/{fs-traced-S0kTDDbJ.mjs → fs-traced-OS6B1cZZ.mjs} +2 -2
- package/dist/git-handle-BHI57rg_.mjs +1 -0
- package/dist/{git-handle-B4sZCaOF.mjs → git-handle-BX4T8btU.mjs} +2 -2
- package/dist/index.d.mts +10 -10
- package/dist/index.mjs +1 -1
- package/dist/init-BHEUjCX8.mjs +1 -0
- package/dist/{init-DB7V_L0g.mjs → init-BJIgDJa3.mjs} +3 -3
- package/dist/{launch-json-removal-D3Fmd63b.mjs → launch-json-removal-CJgXyPl3.mjs} +2 -2
- package/dist/{loader-C3960z78.mjs → loader-BVADW1fG.mjs} +2 -2
- package/dist/loader-DIKghq91.mjs +1 -0
- package/dist/md-manager-oHSV8G_7.mjs +2 -0
- package/dist/{open-browser-C7gapRCk.mjs → open-browser-DlO-Gsw_.mjs} +2 -2
- package/dist/parse-worker.mjs +1 -1
- package/dist/{preview-BptdoKu1.mjs → preview-BwdVoUBB.mjs} +2 -2
- package/dist/preview-CRUQ2pHj.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-DSMkdCKH.js → ActivityModeContent-DQJfhFeQ.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-C4Ff6cFp.js → AgentDiffPane-D9VDqMCh.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-BGP2cYbn.js → AgentThreadClientBinder-D_oR-NzN.js} +1 -1
- package/dist/public/assets/{ChangedOutsideBadge-5cWobd6L.js → ChangedOutsideBadge-bIQSwxNT.js} +1 -1
- package/dist/public/assets/CodeMirrorPropInput-C21yk3-k.js +3 -0
- package/dist/public/assets/DiffView-DuPfWTAC.js +3 -0
- package/dist/public/assets/DocumentContext-Bhb-Rllg.js +38 -0
- package/dist/public/assets/EditorModeToggle-DYt4xV0B.js +1 -0
- package/dist/public/assets/EnableSyncConfirmDialog-D7Jzb7yA.js +1 -0
- package/dist/public/assets/FeedbackForm-D46RvfHP.js +1 -0
- package/dist/public/assets/{GraphPanel-BHhs9d_j.js → GraphPanel-BK4oU7K8.js} +1 -1
- package/dist/public/assets/{ImportSkillDialog-BBOb5ucQ.js → ImportSkillDialog-DT373DMA.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-BQrh8rjg.js → LintConfigEditor-CKLpAwfC.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-BijATHK9.js +1 -0
- package/dist/public/assets/{ManagedArtifactProperties-C2RUr9ul.js → ManagedArtifactProperties-CTw29aB4.js} +1 -1
- package/dist/public/assets/{McpConsentDialogBody-CnzWhv5d.js → McpConsentDialogBody-BICQmO-R.js} +1 -1
- package/dist/public/assets/MermaidDocEditor-CwRVCqx7.js +1 -0
- package/dist/public/assets/{ReportBugDialogBody-cxc30WKp.js → ReportBugDialogBody-COTMJPnc.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-BpQBtTyY.js → SchemaConfigEditor-bkLxSHte.js} +1 -1
- package/dist/public/assets/{SessionsHost-CbagO4xN.js → SessionsHost-Bw4MKgvL.js} +2 -2
- package/dist/public/assets/SettingsDialogBody-DYh6a8hI.js +12 -0
- package/dist/public/assets/{ShareBranchSwitchDialog-ChLbTjJf.js → ShareBranchSwitchDialog-BrnApKc6.js} +1 -1
- package/dist/public/assets/{ShareReceiveDialog-BV36sHT2.js → ShareReceiveDialog-iTAeKpJM.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-BuwUGCen.js → ShareReceiveMissDialog-D4JlxFnU.js} +1 -1
- package/dist/public/assets/{SkillEditBanner-CTLg7M8S.js → SkillEditBanner-B4YWkWzW.js} +1 -1
- package/dist/public/assets/{SkillOriginInline-BC5LfTxy.js → SkillOriginInline-Uo33TCpC.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-B2lqqSNx.js → SkillToolbarControls-DjI3RNFS.js} +1 -1
- package/dist/public/assets/SourceEditor-BZSPCXoy.js +1 -0
- package/dist/public/assets/{TerminalPanel-BPqwq8Q7.js → TerminalPanel-CVHJq4Iu.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-DXkoU-Wq.js → TerminalWindowApp-BITwxu5N.js} +1 -1
- package/dist/public/assets/TextDocEditor-7FzBwfzQ.js +1 -0
- package/dist/public/assets/{ThreadView-De8W8Sau.js → ThreadView-1kpA4rse.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-BgqJsURk.js → TimelineDiffPane-Cvmtozih.js} +1 -1
- package/dist/public/assets/{agent-diff-store-D3wCGBNo.js → agent-diff-store-CC8aPVHS.js} +1 -1
- package/dist/public/assets/{agent-visibility-jMXG7qfn.js → agent-visibility-XcypjuYX.js} +1 -1
- package/dist/public/assets/{auth-state-cache-cFen_h-t.js → auth-state-cache-DZEPs4Pt.js} +5 -5
- package/dist/public/assets/client-version-DL1elh-R.js +1 -0
- package/dist/public/assets/{esm-Dn0h--OG.js → cm-theme-BIKMj2KE.js} +1 -1
- package/dist/public/assets/{comment-chips-Dyvy03mN.js → comment-chips-tOHcZ7p1.js} +1 -1
- package/dist/public/assets/config-context-CVWonKyE.js +1 -0
- package/dist/public/assets/config-provider-COjQaZZa.js +4 -0
- package/dist/public/assets/{dist-BawYG08a.js → dist-B42mX0YC.js} +1 -1
- package/dist/public/assets/{dist-BhBnufkS.js → dist-B4xkxNpz.js} +1 -1
- package/dist/public/assets/dist-BOFmnwXG.js +1 -0
- package/dist/public/assets/{dist-B_pBFyj72.js → dist-ChpE673Q.js} +1 -1
- package/dist/public/assets/{dist-1bY-7L2j.js → dist-Cka1ipRf.js} +1 -1
- package/dist/public/assets/{dist-Dsr-OKxp2.js → dist-D14X-mK2.js} +1 -1
- package/dist/public/assets/{dist-4KAJEfHq.js → dist-DZQQflzj.js} +1 -1
- package/dist/public/assets/{dist-2t_r6dn4.js → dist-DjACJACU.js} +1 -1
- package/dist/public/assets/dist-Dp7TiZ5u2.js +1 -0
- package/dist/public/assets/{dist-DhrsAcRJ.js → dist-DsE9X3Yz.js} +1 -1
- package/dist/public/assets/{dist-CVBOvb5_.js → dist-cmNR9Bbs.js} +1 -1
- package/dist/public/assets/{dist-B5YN73un.js → dist-gVPIADKn2.js} +1 -1
- package/dist/public/assets/{dist-Bs8DNjRh2.js → dist-lf4nG52q2.js} +181 -179
- package/dist/public/assets/{doc-paths-BbWRFVgi.js → doc-paths-CQTfUOZw.js} +1 -1
- package/dist/public/assets/{documents-events-BajItHup.js → documents-events-BwmrmAGX.js} +1 -1
- package/dist/public/assets/{file-tree-adapter-J6QKEfhJ.js → file-tree-adapter-DESJhWoq.js} +1 -1
- package/dist/public/assets/{file-tree-utils-BbhSDaTW.js → file-tree-utils-BG34yBvw.js} +1 -1
- package/dist/public/assets/{folder-config-api-4IXvDZej.js → folder-config-api-DNrN753j.js} +1 -1
- package/dist/public/assets/{globals-DZAq1BKn.js → globals-BGbHjQJ2.js} +1 -1
- package/dist/public/assets/globals-BmAazS49.css +1 -0
- package/dist/public/assets/{index-HKhe_5r9.js → index-DEksXdTO.js} +14 -14
- package/dist/public/assets/{lint-config-client-DxXOFrgQ.js → lint-config-client-Bg_dSPOM.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-C30SWnqC.js → markdownlint-rule-browser-DrFQPMJg.js} +1 -1
- package/dist/public/assets/navigation-targets-0wZAeKrc.js +1 -0
- package/dist/public/assets/{open-managed-artifact-tab-JgSQJhTn.js → open-managed-artifact-tab-BVeI_6BU.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-DsrtuI8M.js → pending-receive-nav-store-iHnQtDVG.js} +1 -1
- package/dist/public/assets/{prop-types-CiBsNxle.js → prop-types-CHOFqrri.js} +1 -1
- package/dist/public/assets/{receive-store-CV99IXkf.js → receive-store-YZh_VQ02.js} +1 -1
- package/dist/public/assets/{selection-context-DEAlV4hy.js → selection-context-CtO8dzXv.js} +1 -1
- package/dist/public/assets/{skill-actions-Du0nfl4o.js → skill-actions-CKsFVZ7s.js} +1 -1
- package/dist/public/assets/{skill-scope-p6Dsw7Bl.js → skill-scope-DNo7_4lO.js} +1 -1
- package/dist/public/assets/{skills-api-ctJhutDo.js → skills-api-YMCgcUab.js} +1 -1
- package/dist/public/assets/{src-DvGM96LY.js → src-DKNcDpsX.js} +1 -1
- package/dist/public/assets/{tag-pill-input-BR6KfEym.js → tag-pill-input-BR-zZRy9.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-CbnILhIU.js → target-navigation-intent-CTSKR5SK.js} +1 -1
- package/dist/public/assets/{telemetry-impl-DWXkoD72.js → telemetry-impl-BJK36lQF.js} +1 -1
- package/dist/public/assets/{telemetry-startup-3Sng8oEw.js → telemetry-startup-D8rFEM2d.js} +1 -1
- package/dist/public/assets/{terminal-launch-events-BO-PD_eo.js → terminal-launch-events-D7klM-xS.js} +1 -1
- package/dist/public/assets/{terminal-telemetry-D8M0Ozm1.js → terminal-telemetry-JwJxpal6.js} +1 -1
- package/dist/public/assets/{text-viewer-languages-DFJQsbAG.js → text-viewer-languages-BLSME92j.js} +2 -2
- package/dist/public/assets/{typing-burst-detector-J49yrfso.js → typing-burst-detector-X0S33jis.js} +1 -1
- package/dist/public/assets/{uninstall-CFuBiQfI.js → uninstall-CgrheMqc.js} +1 -1
- package/dist/public/assets/{use-activity-panel-BkkZ0ANm.js → use-activity-panel-BZ9nGQPH.js} +1 -1
- package/dist/public/assets/{use-collab-url-DZPhaKCl.js → use-collab-url-D8N5M2pl.js} +1 -1
- package/dist/public/assets/use-live-xterm-theme-on3ebtaK.js +1 -0
- package/dist/public/assets/{use-open-skill-DLwXz8W_.js → use-open-skill-CI0ilwyX.js} +1 -1
- package/dist/public/assets/{use-settings-route-CS1B3HfO.js → use-settings-route-BiaOx7d8.js} +1 -1
- package/dist/public/assets/{use-skill-directory-jOoyjAPU.js → use-skill-directory-BVbrNJTi.js} +1 -1
- package/dist/public/assets/{use-skill-origin-DDWTwjBX.js → use-skill-origin-CEQwPxVb.js} +1 -1
- package/dist/public/assets/{use-skills-udAv99z6.js → use-skills-DdHlTORK.js} +1 -1
- package/dist/public/assets/use-terminal-enabled-DVN1muEr.js +1 -0
- package/dist/public/assets/{use-timeline-entry-diff-BN4My22X.js → use-timeline-entry-diff-Be73Nm0G.js} +1 -1
- package/dist/public/assets/{use-workspace-DGXA9Dn3.js → use-workspace--dJVq1a4.js} +1 -1
- package/dist/public/index.html +59 -59
- package/dist/public/uninstall.html +4 -4
- package/dist/{repair-launch-json-KmYO_2FG.mjs → repair-launch-json-kJ-N16X6.mjs} +2 -2
- package/dist/{repair-mcp-configs-CsIGV5-7.mjs → repair-mcp-configs-cRf1KHN2.mjs} +2 -2
- package/dist/{repair-skills-Cie1nS2r.mjs → repair-skills-CAgJh50Q.mjs} +2 -2
- package/dist/repair-skills-CXwfQm8m.mjs +1 -0
- package/dist/schemas/v0/config.user.schema.json +108 -13
- package/dist/{server-lock-DW5T6J_m.mjs → server-lock-BcVRTi0F.mjs} +2 -2
- package/dist/server-lock-CCA69O0D.mjs +1 -0
- package/dist/{sleep-CJdjw5UD.mjs → sleep-C5OfWWWx.mjs} +5 -5
- package/dist/{src-D0P0SFti.mjs → src-6SIlUA0g.mjs} +1 -1
- package/dist/{src-0sJ50HI5.mjs → src-CA2-5ky_.mjs} +2 -2
- package/dist/{src-BKLIxQOr.mjs → src-DlAv53T2.mjs} +6 -6
- package/dist/{src-CpgLre_H.mjs → src-K60Nfy_1.mjs} +2 -2
- package/dist/start-ak4kOBNH.mjs +1 -0
- package/dist/{start-DhBxzdcm.mjs → start-fAsaQwEs.mjs} +3 -3
- package/dist/{write-project-skill-CKuq5itB.mjs → write-project-skill-Bn1Fo5lw.mjs} +2 -2
- package/package.json +4 -4
- package/dist/constants-BtN4Fp1d.mjs +0 -2
- package/dist/fs-traced-DbSNN5G0.mjs +0 -1
- package/dist/git-handle-uBCwtyAf.mjs +0 -1
- package/dist/init-Cx94zXdb.mjs +0 -1
- package/dist/loader-CRQzxtMB.mjs +0 -1
- package/dist/md-manager-DZuZjzrd.mjs +0 -2
- package/dist/preview-CLNTLfvK.mjs +0 -1
- package/dist/public/assets/CodeMirrorPropInput-BFenJemA.js +0 -3
- package/dist/public/assets/DiffView-DBpBW2MH.js +0 -3
- package/dist/public/assets/DocumentContext-CKMhLy2N.js +0 -38
- package/dist/public/assets/EditorModeToggle-BYt93vnW.js +0 -1
- package/dist/public/assets/EnableSyncConfirmDialog-V141T2QR.js +0 -1
- package/dist/public/assets/FeedbackForm-BFPoJkdK.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-C4CnV_IS.js +0 -1
- package/dist/public/assets/MermaidDocEditor-CNK3K4lC.js +0 -1
- package/dist/public/assets/SettingsDialogBody-hWpwDgnT.js +0 -7
- package/dist/public/assets/SourceEditor-hADslP9Q.js +0 -1
- package/dist/public/assets/TextDocEditor-D07aFI4B.js +0 -1
- package/dist/public/assets/client-version-BBVOjYrp.js +0 -1
- package/dist/public/assets/config-provider-D2FBTvIx.js +0 -4
- package/dist/public/assets/dist-ZmxLttHl.js +0 -1
- package/dist/public/assets/dist-zNz6UTbN.js +0 -1
- package/dist/public/assets/globals-Cd1sgqvz.css +0 -1
- package/dist/public/assets/navigation-targets-CnIm35UZ.js +0 -1
- package/dist/public/assets/use-apply-config-color-theme-C7h1V38B.js +0 -2
- package/dist/public/assets/use-live-xterm-theme-CbDRpOKw.js +0 -1
- package/dist/public/assets/use-terminal-enabled-87atXgw4.js +0 -1
- package/dist/repair-skills-C0rCwW3E.mjs +0 -1
- package/dist/server-lock-GGE1_Y5o.mjs +0 -1
- package/dist/start-DdGn_P_U.mjs +0 -1
- /package/dist/public/assets/{dist-pl6OT5yc.js → dist-CJ0cwmiC.js} +0 -0
- /package/dist/public/assets/{stex-WCjgSIWy.js → stex-7gT25hE_.js} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D as a,Dt as o,E as s,F as c,Ft as l,H as u,It as d,J as f,K as p,Lt as m,Mt as h,Nt as g,O as _,Ot as v,Pt as y,Q as b,R as x,Rt as S,St as C,T as w,U as T,V as ee,W as te,Y as ne,Z as re,_ as ie,_t as E,at as D,b as ae,bt as O,ct as oe,d as se,dt as k,et as ce,f as le,ft as ue,g as de,gt as fe,ht as A,i as pe,it as j,jt as me,kt as he,l as ge,lt as _e,mt as M,n as ve,nt as ye,ot as be,pt as N,q as P,r as xe,st as Se,t as Ce,tt as we,v as Te,vt as F,w as Ee,wt as De,xt as Oe,y as ke,yt as I}from"./sleep-CJdjw5UD.mjs";import{$ as Ae,$a as je,$i as Me,$n as Ne,$o as Pe,$r as Fe,$t as Ie,A as Le,Aa as Re,Ai as ze,An as Be,Ao as Ve,Ar as He,At as Ue,B as We,Ba as Ge,Bi as Ke,Bn as qe,Br as Je,Bt as Ye,C as Xe,Ca as Ze,Ci as Qe,Cn as $e,Cr as et,Ct as tt,D as nt,Da as rt,Di as it,Dn as at,Do as ot,Dr as st,Dt as ct,E as lt,Ea as ut,Ei as dt,En as ft,Eo as pt,Er as mt,Et as ht,F as gt,Fa as _t,Fi as vt,Fn as yt,Fr as bt,Ft as xt,G as St,Ga as Ct,Gi as wt,Gn as Tt,Go as Et,Gr as Dt,Gt as Ot,H as kt,Ha as At,Hi as jt,Hn as eee,Ho as Mt,Hr as tee,Ht as Nt,I as Pt,Ia as Ft,Ii as nee,In as ree,Io as It,Ir as Lt,J as Rt,Ja as iee,Ji as zt,Jn as Bt,Jo as Vt,Jr as Ht,Jt as Ut,K as Wt,Ka as Gt,Ki as Kt,Kn as qt,Ko as Jt,Kr as Yt,Kt as Xt,L as Zt,La as aee,Li as oee,Ln as Qt,Lr as see,M as $t,Ma as en,Mi as cee,Mn as lee,Mo as tn,Mr as nn,Mt as rn,N as an,Na as on,Ni as uee,Nn as sn,No as cn,Nr as ln,Nt as dee,O as fee,Oa as un,Oi as dn,On as pee,Or as fn,Ot as mee,P as pn,Pi as mn,Pn as hn,Po as gn,Pr as _n,Pt as vn,Qa as yn,Qi as bn,Qn as xn,Qo as Sn,Qr as Cn,Qt as wn,Ra as Tn,Ri as En,Rn as Dn,Ro as On,Rr as kn,Rt as An,S as jn,Sa as Mn,Si as Nn,Sn as Pn,So as Fn,Sr as In,Ss as Ln,St as Rn,T as hee,Ta as zn,Ti as Bn,Tn as gee,To as Vn,Tr as _ee,Tt as Hn,U as Un,Ua as vee,Ui as yee,Un as Wn,Uo as Gn,Ur as bee,Ut as Kn,V as xee,Va as See,Vi as Cee,Vn as wee,Vo as qn,Vr as Jn,Vt as Yn,W as Xn,Wa as Zn,Wi as Tee,Wn as Eee,Wo as Qn,Wr as Dee,Wt as $n,X as er,Xa as Oee,Xi as tr,Xn as kee,Xo as nr,Xr as Aee,Xt as jee,Ya as rr,Yi as ir,Yn as Mee,Yo as ar,Yr as or,Yt as sr,Za as cr,Zi as lr,Zn as ur,Zr as dr,Zt as fr,_ as pr,_a as mr,_i as hr,_n as gr,_o as _r,_r as Nee,_s as vr,_t as yr,a as br,aa as xr,ai as Sr,an as Cr,ao as wr,ar as Tr,as as Er,at as Dr,b as Or,ba as kr,bi as Ar,bn as jr,br as Pee,bt as Mr,c as Nr,ca as Pr,ci as Fr,cn as Ir,cr as Lr,cs as Rr,ct as zr,d as Br,da as Vr,di as Hr,dn as Ur,do as Wr,dr as Gr,ds as Kr,dt as qr,ea as Jr,ei as Yr,en as Xr,eo as Zr,er as Qr,es as $r,et as ei,f as ti,fa as ni,fi as ri,fn as ii,fr as ai,fs as oi,ft as si,g as ci,ga as li,gi as ui,gn as di,go as fi,gr as pi,gs as mi,gt as hi,h as gi,ha as _i,hi as vi,hn as yi,hr as bi,hs as xi,ht as Si,i as Ci,ia as wi,ii as Ti,in as Ei,io as Di,ir as Oi,is as ki,it as Ai,j as ji,ja as Mi,ji as Ni,jn as Pi,jo as Fi,jr as Ii,jt as Li,k as Ri,ka as zi,ki as Bi,kn as Vi,ko as Hi,kr as Ui,kt as Wi,l as Gi,la as Ki,li as qi,ln as Ji,lo as Yi,lr as Xi,ls as Zi,lt as Qi,ma as $i,mi as ea,mn as ta,mr as na,ms as ra,mt as ia,n as aa,na as oa,ni as sa,nn as ca,no as la,nr as ua,ns as da,nt as fa,o as pa,oa as ma,oi as ha,on as Fee,oo as ga,or as Iee,os as _a,ot as va,p as ya,pa as Lee,pi as ba,pn as Ree,po as xa,pr as Sa,ps as Ca,pt as wa,q as Ta,qa as Ea,qi as zee,qn as Bee,qo as Da,qr as Oa,qt as ka,r as Aa,ra as ja,ri as Ma,rn as Vee,ro as Na,rr as Hee,rs as Pa,rt as Fa,s as Ia,sa as La,si as Uee,sn as Wee,so as Ra,sr as Gee,ss as za,st as Ba,t as Va,ta as Ha,ti as Kee,tn as Ua,to as qee,tr as Wa,ts as Ga,tt as Ka,u as qa,ua as Ja,ui as Ya,un as Jee,uo as Xa,ur as Yee,us as Za,ut as Qa,v as $a,va as Xee,vi as Zee,vn as Qee,vo as eo,vr as $ee,vs as to,vt as no,w as ro,wa as io,wi as ete,wn as tte,wo as ao,wr as oo,wt as so,x as nte,xa as rte,xi as co,xn as lo,xo as uo,xr as ite,xt as fo,y as po,ya as ate,yi as ote,yn as ste,yo as mo,yr as ho,ys as go,yt as _o,z as cte,za as lte,zi as vo,zn as yo,zo as bo,zr as xo,zt as So}from"./src-0sJ50HI5.mjs";import{c as Co,i as wo,l as ute,n as To,s as Eo}from"./esm-DxvI2ZVA.mjs";import{n as Do,t as Oo}from"./md-manager-DZuZjzrd.mjs";import{A as ko,C as Ao,D as jo,E as Mo,F as No,N as Po,O as Fo,S as Io,T as Lo,_ as Ro,a as zo,b as dte,c as Bo,d as Vo,f as Ho,g as Uo,h as Wo,i as Go,j as Ko,k as qo,l as Jo,m as Yo,n as Xo,o as Zo,p as Qo,r as $o,s as es,t as ts,u as ns,v as rs,w as is,x as as,y as os}from"./fs-traced-S0kTDDbJ.mjs";import{D as fte,E as pte,S as ss,T as cs,a as ls,b as us,l as ds,p as fs,r as L,s as ps,x as ms,y as hs}from"./logger-5LePyO3n.mjs";import{a as gs,i as _s,o as vs,r as ys,s as bs,t as xs}from"./git-handle-B4sZCaOF.mjs";import{S as Ss,a as Cs,b as ws,c as Ts,d as Es,f as Ds,g as Os,h as ks,i as As,l as js,m as Ms,n as Ns,r as Ps,x as Fs,y as Is}from"./server-lock-DW5T6J_m.mjs";import{t as Ls}from"./libesm-DzwC_yFw.mjs";import{n as Rs,t as zs}from"./build-DYQrG4v7.mjs";import{t as Bs}from"./yazl-BafwB467.mjs";import{t as Vs}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Hs,c as Us,d as Ws,f as Gs,h as Ks,i as qs,l as Js,m as Ys,n as Xs,o as Zs,p as Qs,r as $s,s as ec,t as tc,u as nc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as rc,B as ic,C as ac,D as oc,E as sc,F as cc,H as lc,I as uc,L as dc,M as fc,N as pc,O as mc,P as hc,S as gc,T as _c,V as vc,_ as yc,a as bc,b as xc,c as Sc,d as Cc,f as wc,g as Tc,h as Ec,i as Dc,j as Oc,k as kc,l as Ac,m as jc,n as Mc,o as Nc,p as Pc,r as Fc,s as Ic,t as Lc,u as Rc,v as zc,w as Bc,x as Vc,y as Hc,z as Uc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Wc,c as Gc,d as Kc,i as qc,l as Jc,n as Yc,o as Xc,r as Zc,s as Qc,t as $c,u as el}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as tl,r as nl,t as rl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as il}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as al}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as ol,t as sl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as cl,t as ll}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as ul,r as dl,t as fl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as pl,t as ml}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as hl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as gl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as _l}from"./wrapper-BcpqREsI.mjs";import{createRequire as vl}from"node:module";import{execFile as yl,execFileSync as bl,spawn as xl,spawnSync as Sl}from"node:child_process";import*as Cl from"node:path";import{basename as wl,delimiter as Tl,dirname as R,extname as El,isAbsolute as Dl,join as z,normalize as Ol,posix as kl,relative as B,resolve as V,sep as Al,win32 as jl}from"node:path";import{URLSearchParams as Ml,fileURLToPath as Nl,pathToFileURL as Pl}from"node:url";import*as Fl from"node:fs";import{appendFileSync as Il,chmodSync as Ll,closeSync as Rl,constants as zl,createReadStream as Bl,createWriteStream as Vl,existsSync as H,lstatSync as Hl,mkdirSync as Ul,mkdtempSync as Wl,openSync as Gl,readFile as Kl,readFileSync as U,readSync as ql,readdirSync as Jl,readlinkSync as Yl,realpathSync as W,renameSync as Xl,rmSync as Zl,rmdirSync as Ql,statSync as $l,unlinkSync as eu,writeFileSync as tu,writeSync as nu}from"node:fs";import{arch as ru,availableParallelism as iu,homedir as au,hostname as ou,platform as su,tmpdir as cu}from"node:os";import{access as lu,chmod as uu,constants as du,lstat as fu,readFile as pu,readdir as mu,realpath as hu,stat as gu,writeFile as _u}from"node:fs/promises";import{Readable as vu,Transform as yu,Writable as bu}from"node:stream";import xu,{createHash as Su,randomUUID as Cu,webcrypto as wu}from"node:crypto";import Tu from"crypto";import{Readable as Eu}from"stream";import{Worker as Du}from"node:worker_threads";import{monitorEventLoopDelay as Ou,performance as ku}from"node:perf_hooks";import{createInterface as Au}from"node:readline";import{pipeline as ju}from"node:stream/promises";import{setImmediate as Mu,setTimeout as Nu}from"node:timers/promises";import{promisify as Pu}from"node:util";import{lookup as Fu}from"node:dns/promises";import{request as Iu}from"node:http";import{request as Lu}from"node:https";import{createBrotliDecompress as Ru,createGunzip as zu,createInflate as mte}from"node:zlib";import{Http2ServerRequest as Bu,constants as hte}from"http2";import{AsyncLocalStorage as gte}from"node:async_hooks";import{lookup as _te}from"node:dns";import vte from"node:tls";function Vu(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Hu(n)}function Hu(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Uu=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=U(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Dl(t)?t:V(this.gitDir,t))}catch(e){if(!Xu(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=U(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return Xu(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]}:$u(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=U(z(t.path,`config`),`utf-8`)}catch(e){return Xu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=qu(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Zu(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=V(t.path,e),r=B(t.path,n);if(r.startsWith(`..`)||Dl(r))return{kind:`invalid`};try{let e=U(n,`utf-8`).trim(),t=Qu(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Xu(e))return{kind:`unreadable`,cause:e}}let i;try{i=U(z(t.path,`packed-refs`),`utf-8`)}catch(e){return Xu(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 $u(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Wu(e){return Ku(V(e),``)}function Gu(e){let t=V(e),n=V(au());if(t===n)return{kind:`absent`};let r=Ku(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=R(i);if(e===i||e===n)return{kind:`absent`};let r=Ku(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Ku(e,t){let n=z(e,`.git`),r;try{r=$l(n)}catch(e){return Xu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Uu(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=U(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=Dl(o)?o:V(e,o);try{if(!$l(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 Uu(`linked`,e,t,n,s)}}function qu(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Ju(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=Yu(i[1]);if(a.length>0)return a}return null}function Ju(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Yu(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Xu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Zu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Qu(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Zu(t[1])?{kind:`symbolic`,target:t[1]}:null:$u(e)?{kind:`oid`,oid:e}:null}function $u(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function yte(e){return`git-author-${Hn(e.trim().toLowerCase())}`}const bte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function ed(e){let t=Gu(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 td(e){let t=ed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function nd(e){let t=ed(e);switch(t.kind){case`directory`:return V(t.path,rd(t.projectSubPath));case`linked`:if(!H(t.path))throw new id(t.gitPath,t.path);return V(t.path,rd(t.projectSubPath));case`malformed-pointer`:throw new id(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new ad(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function rd(e){return e===``?`ok`:`ok-${xte(e)}`}function xte(e){let t=e.split(Al).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Ste(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Ste(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var id=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}},ad=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 od(e){let t;try{t=nd(e)}catch(e){if(e instanceof id||e instanceof ad)return null;throw e}return H(V(t,`HEAD`))?t:null}function sd(e){return`refs/wip/${e}/`}function cd(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{At as r,Ct as i,D as a,Dt as o,E as s,F as c,Ft as l,H as u,It as d,J as f,K as p,Lt as m,Mt as h,Nt as g,O as _,Ot as v,Pt as y,Q as b,R as x,Rt as S,St as C,T as w,U as T,V as ee,W as te,Y as ne,Z as re,_ as ie,_t as E,at as D,b as ae,bt as O,ct as oe,d as se,dt as k,et as ce,f as le,ft as ue,g as de,gt as fe,ht as A,i as pe,it as j,jt as me,kt as he,l as ge,lt as _e,mt as M,n as ve,nt as ye,ot as be,pt as N,q as P,r as xe,st as Se,t as Ce,tt as we,v as Te,vt as F,w as Ee,wt as De,xt as Oe,y as ke,yt as I}from"./sleep-C5OfWWWx.mjs";import{$ as Ae,$a as je,$i as Me,$n as Ne,$o as Pe,$r as Fe,$t as Ie,A as Le,Aa as Re,Ai as ze,An as Be,Ao as Ve,Ar as He,At as Ue,B as We,Ba as Ge,Bi as Ke,Bn as qe,Br as Je,Bt as Ye,C as Xe,Ca as Ze,Ci as Qe,Cn as $e,Cr as et,Ct as tt,D as nt,Da as rt,Di as it,Dn as at,Do as ot,Dr as st,Dt as ct,E as lt,Ea as ut,Ei as dt,En as ft,Eo as pt,Er as mt,Et as ht,F as gt,Fa as _t,Fi as vt,Fn as yt,Fr as bt,Ft as xt,G as St,Ga as Ct,Gi as wt,Gn as Tt,Go as Et,Gr as Dt,Gt as Ot,H as kt,Ha as At,Hi as jt,Hn as eee,Ho as Mt,Hr as tee,Ht as Nt,I as Pt,Ia as Ft,Ii as nee,In as ree,Io as It,Ir as Lt,J as Rt,Ja as iee,Ji as zt,Jn as Bt,Jo as Vt,Jr as Ht,Jt as Ut,K as Wt,Ka as Gt,Ki as Kt,Kn as qt,Ko as Jt,Kr as Yt,Kt as Xt,L as Zt,La as aee,Li as oee,Ln as Qt,Lr as see,M as $t,Ma as en,Mi as cee,Mn as lee,Mo as tn,Mr as nn,Mt as rn,N as an,Na as on,Ni as uee,Nn as sn,No as cn,Nr as ln,Nt as dee,O as fee,Oa as un,Oi as dn,On as pee,Or as fn,Ot as mee,P as pn,Pi as mn,Pn as hn,Po as gn,Pr as _n,Pt as vn,Qa as yn,Qi as bn,Qn as xn,Qo as Sn,Qr as Cn,Qt as wn,Ra as Tn,Ri as En,Rn as Dn,Ro as On,Rr as kn,Rt as An,S as jn,Sa as Mn,Si as Nn,Sn as Pn,So as Fn,Sr as In,Ss as Ln,St as Rn,T as hee,Ta as zn,Ti as Bn,Tn as gee,To as Vn,Tr as _ee,Tt as Hn,U as Un,Ua as vee,Ui as yee,Un as Wn,Uo as Gn,Ur as bee,Ut as Kn,V as xee,Va as See,Vi as Cee,Vn as wee,Vo as qn,Vr as Jn,Vt as Yn,W as Xn,Wa as Zn,Wi as Tee,Wn as Eee,Wo as Qn,Wr as Dee,Wt as $n,X as er,Xa as Oee,Xi as tr,Xn as kee,Xo as nr,Xr as Aee,Xt as jee,Ya as rr,Yi as ir,Yn as Mee,Yo as ar,Yr as or,Yt as sr,Za as cr,Zi as lr,Zn as ur,Zr as dr,Zt as fr,_ as pr,_a as mr,_i as hr,_n as gr,_o as _r,_r as Nee,_s as vr,_t as yr,a as br,aa as xr,ai as Sr,an as Cr,ao as wr,ar as Tr,as as Er,at as Dr,b as Or,ba as kr,bi as Ar,bn as jr,br as Pee,bt as Mr,c as Nr,ca as Pr,ci as Fr,cn as Ir,cr as Lr,cs as Rr,ct as zr,d as Br,da as Vr,di as Hr,dn as Ur,do as Wr,dr as Gr,ds as Kr,dt as qr,ea as Jr,ei as Yr,en as Xr,eo as Zr,er as Qr,es as $r,et as ei,f as ti,fa as ni,fi as ri,fn as ii,fr as ai,fs as oi,ft as si,g as ci,ga as li,gi as ui,gn as di,go as fi,gr as pi,gs as mi,gt as hi,h as gi,ha as _i,hi as vi,hn as yi,hr as bi,hs as xi,ht as Si,i as Ci,ia as wi,ii as Ti,in as Ei,io as Di,ir as Oi,is as ki,it as Ai,j as ji,ja as Mi,ji as Ni,jn as Pi,jo as Fi,jr as Ii,jt as Li,k as Ri,ka as zi,ki as Bi,kn as Vi,ko as Hi,kr as Ui,kt as Wi,l as Gi,la as Ki,li as qi,ln as Ji,lo as Yi,lr as Xi,ls as Zi,lt as Qi,ma as $i,mi as ea,mn as ta,mr as na,ms as ra,mt as ia,n as aa,na as oa,ni as sa,nn as ca,no as la,nr as ua,ns as da,nt as fa,o as pa,oa as ma,oi as ha,on as Fee,oo as ga,or as Iee,os as _a,ot as va,p as ya,pa as Lee,pi as ba,pn as Ree,po as xa,pr as Sa,ps as Ca,pt as wa,q as Ta,qa as Ea,qi as zee,qn as Bee,qo as Da,qr as Oa,qt as ka,r as Aa,ra as ja,ri as Ma,rn as Vee,ro as Na,rr as Hee,rs as Pa,rt as Fa,s as Ia,sa as La,si as Uee,sn as Wee,so as Ra,sr as Gee,ss as za,st as Ba,t as Va,ta as Ha,ti as Kee,tn as Ua,to as qee,tr as Wa,ts as Ga,tt as Ka,u as qa,ua as Ja,ui as Ya,un as Jee,uo as Xa,ur as Yee,us as Za,ut as Qa,v as $a,va as Xee,vi as Zee,vn as Qee,vo as eo,vr as $ee,vs as to,vt as no,w as ro,wa as io,wi as ete,wn as tte,wo as ao,wr as oo,wt as so,x as nte,xa as rte,xi as co,xn as lo,xo as uo,xr as ite,xt as fo,y as po,ya as ate,yi as ote,yn as ste,yo as mo,yr as ho,ys as go,yt as _o,z as cte,za as lte,zi as vo,zn as yo,zo as bo,zr as xo,zt as So}from"./src-CA2-5ky_.mjs";import{c as Co,i as wo,l as ute,n as To,s as Eo}from"./esm-DxvI2ZVA.mjs";import{n as Do,t as Oo}from"./md-manager-oHSV8G_7.mjs";import{A as ko,C as Ao,D as jo,E as Mo,F as No,N as Po,O as Fo,S as Io,T as Lo,_ as Ro,a as zo,b as dte,c as Bo,d as Vo,f as Ho,g as Uo,h as Wo,i as Go,j as Ko,k as qo,l as Jo,m as Yo,n as Xo,o as Zo,p as Qo,r as $o,s as es,t as ts,u as ns,v as rs,w as is,x as as,y as os}from"./fs-traced-OS6B1cZZ.mjs";import{D as fte,E as pte,S as ss,T as cs,a as ls,b as us,l as ds,p as fs,r as L,s as ps,x as ms,y as hs}from"./logger-5LePyO3n.mjs";import{a as gs,i as _s,o as vs,r as ys,s as bs,t as xs}from"./git-handle-BX4T8btU.mjs";import{S as Ss,a as Cs,b as ws,c as Ts,d as Es,f as Ds,g as Os,h as ks,i as As,l as js,m as Ms,n as Ns,r as Ps,x as Fs,y as Is}from"./server-lock-BcVRTi0F.mjs";import{t as Ls}from"./libesm-DzwC_yFw.mjs";import{n as Rs,t as zs}from"./build-DYQrG4v7.mjs";import{t as Bs}from"./yazl-BafwB467.mjs";import{t as Vs}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Hs,c as Us,d as Ws,f as Gs,h as Ks,i as qs,l as Js,m as Ys,n as Xs,o as Zs,p as Qs,r as $s,s as ec,t as tc,u as nc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as rc,B as ic,C as ac,D as oc,E as sc,F as cc,H as lc,I as uc,L as dc,M as fc,N as pc,O as mc,P as hc,S as gc,T as _c,V as vc,_ as yc,a as bc,b as xc,c as Sc,d as Cc,f as wc,g as Tc,h as Ec,i as Dc,j as Oc,k as kc,l as Ac,m as jc,n as Mc,o as Nc,p as Pc,r as Fc,s as Ic,t as Lc,u as Rc,v as zc,w as Bc,x as Vc,y as Hc,z as Uc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Wc,c as Gc,d as Kc,i as qc,l as Jc,n as Yc,o as Xc,r as Zc,s as Qc,t as $c,u as el}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as tl,r as nl,t as rl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as il}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as al}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as ol,t as sl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as cl,t as ll}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as ul,r as dl,t as fl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as pl,t as ml}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as hl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as gl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as _l}from"./wrapper-BcpqREsI.mjs";import{createRequire as vl}from"node:module";import{execFile as yl,execFileSync as bl,spawn as xl,spawnSync as Sl}from"node:child_process";import*as Cl from"node:path";import{basename as wl,delimiter as Tl,dirname as R,extname as El,isAbsolute as Dl,join as z,normalize as Ol,posix as kl,relative as B,resolve as V,sep as Al,win32 as jl}from"node:path";import{URLSearchParams as Ml,fileURLToPath as Nl,pathToFileURL as Pl}from"node:url";import*as Fl from"node:fs";import{appendFileSync as Il,chmodSync as Ll,closeSync as Rl,constants as zl,createReadStream as Bl,createWriteStream as Vl,existsSync as H,lstatSync as Hl,mkdirSync as Ul,mkdtempSync as Wl,openSync as Gl,readFile as Kl,readFileSync as U,readSync as ql,readdirSync as Jl,readlinkSync as Yl,realpathSync as W,renameSync as Xl,rmSync as Zl,rmdirSync as Ql,statSync as $l,unlinkSync as eu,writeFileSync as tu,writeSync as nu}from"node:fs";import{arch as ru,availableParallelism as iu,homedir as au,hostname as ou,platform as su,tmpdir as cu}from"node:os";import{access as lu,chmod as uu,constants as du,lstat as fu,readFile as pu,readdir as mu,realpath as hu,stat as gu,writeFile as _u}from"node:fs/promises";import{Readable as vu,Transform as yu,Writable as bu}from"node:stream";import xu,{createHash as Su,randomUUID as Cu,webcrypto as wu}from"node:crypto";import Tu from"crypto";import{Readable as Eu}from"stream";import{Worker as Du}from"node:worker_threads";import{monitorEventLoopDelay as Ou,performance as ku}from"node:perf_hooks";import{createInterface as Au}from"node:readline";import{pipeline as ju}from"node:stream/promises";import{setImmediate as Mu,setTimeout as Nu}from"node:timers/promises";import{promisify as Pu}from"node:util";import{lookup as Fu}from"node:dns/promises";import{request as Iu}from"node:http";import{request as Lu}from"node:https";import{createBrotliDecompress as Ru,createGunzip as zu,createInflate as mte}from"node:zlib";import{Http2ServerRequest as Bu,constants as hte}from"http2";import{AsyncLocalStorage as gte}from"node:async_hooks";import{lookup as _te}from"node:dns";import vte from"node:tls";function Vu(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Hu(n)}function Hu(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Uu=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=U(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Dl(t)?t:V(this.gitDir,t))}catch(e){if(!Xu(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=U(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return Xu(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]}:$u(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=U(z(t.path,`config`),`utf-8`)}catch(e){return Xu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=qu(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Zu(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=V(t.path,e),r=B(t.path,n);if(r.startsWith(`..`)||Dl(r))return{kind:`invalid`};try{let e=U(n,`utf-8`).trim(),t=Qu(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!Xu(e))return{kind:`unreadable`,cause:e}}let i;try{i=U(z(t.path,`packed-refs`),`utf-8`)}catch(e){return Xu(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 $u(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Wu(e){return Ku(V(e),``)}function Gu(e){let t=V(e),n=V(au());if(t===n)return{kind:`absent`};let r=Ku(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=R(i);if(e===i||e===n)return{kind:`absent`};let r=Ku(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Ku(e,t){let n=z(e,`.git`),r;try{r=$l(n)}catch(e){return Xu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Uu(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=U(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=Dl(o)?o:V(e,o);try{if(!$l(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 Uu(`linked`,e,t,n,s)}}function qu(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Ju(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=Yu(i[1]);if(a.length>0)return a}return null}function Ju(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Yu(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function Xu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Zu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Qu(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Zu(t[1])?{kind:`symbolic`,target:t[1]}:null:$u(e)?{kind:`oid`,oid:e}:null}function $u(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function yte(e){return`git-author-${Hn(e.trim().toLowerCase())}`}const bte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function ed(e){let t=Gu(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 td(e){let t=ed(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function nd(e){let t=ed(e);switch(t.kind){case`directory`:return V(t.path,rd(t.projectSubPath));case`linked`:if(!H(t.path))throw new id(t.gitPath,t.path);return V(t.path,rd(t.projectSubPath));case`malformed-pointer`:throw new id(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new ad(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function rd(e){return e===``?`ok`:`ok-${xte(e)}`}function xte(e){let t=e.split(Al).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Ste(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Ste(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var id=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}},ad=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 od(e){let t;try{t=nd(e)}catch(e){if(e instanceof id||e instanceof ad)return null;throw e}return H(V(t,`HEAD`))?t:null}function sd(e){return`refs/wip/${e}/`}function cd(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 ld=`ok-actor: `;function ud(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),`${ld}${JSON.stringify(i)}`}function dd(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=fd(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 fd(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 pd(e){if(!e)return null;for(let t of e.split(`
|
|
3
3
|
`)){let e=t.trim();if(!e.startsWith(ld))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:dd(n)}return null}function md(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
4
|
-
`)){let e=n.trim();if(!e.startsWith(ld))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=dd(r);i&&t.push(i)}return t}function Cte(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function hd(e){let t=md(e);return t.length>0?t.map(Cte):cd(e)}function gd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function _d(e){return`reconcile: ${e}`}function vd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function wte(e,t){return`park: ${e} -> ${t}`}function yd(e,t){return`rename: ${e} -> ${t}`}function bd(e){return`checkpoint: ${e}`}function Tte(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Ete=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function xd(e){return e.replace(Ete,` `)}function Dte(e,t){let n=xd(e);if(t.length===0)return n;if(t.length>=2)return`${n} (${t.length} edits)`;let[r]=t;if(r===void 0)return n;let i=xd(r),a=`${n} — ${i}`;if(a.length<=72)return a;let o=`${n} — `,s=72-o.length-1;return s<=0?a.slice(0,72):`${o}${i.slice(0,s)}…`}function Sd(e){return bte.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function Cd(e){let t=ed(e);if(t.kind!==`linked`)return V(e);try{let n=U(z(t.path,`commondir`),`utf-8`).trim();return n===``?V(e):V(R(V(t.path,n)),t.projectSubPath)}catch{return V(e)}}function wd(e){return e.kind??`other`}function Ote(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Td=class{filePath;log;grants=null;constructor(e,t){this.filePath=z(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=wd(t),i=Ote(n,[`allow_once`,`allow_always`]);return i===void 0?{auto:null}:r===`read`||this.hasAllowAlways(e,r)?{auto:{optionId:i.optionId}}:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n){if(n.kind!==`allow_always`)return;let r=wd(t);if(this.hasAllowAlways(e,r))return;let i=[...this.loadGrants(),{agentId:e,toolKind:r}];this.grants=i;try{let{tracedMkdir:e,tracedWriteFile:t}=await import(`./fs-traced-DbSNN5G0.mjs`);await e(z(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(U(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const Ed=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],kte={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Dd=`acp-agents.json`,Od=`acp-registry-cache.json`;function kd(){let e=su(),t=ru(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`windows`:null,r=t===`arm64`?`aarch64`:t===`x64`?`x86_64`:null;return n===null||r===null?null:`${n}-${r}`}function Ad(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.name==`string`&&typeof t.version==`string`&&typeof t.distribution==`object`&&t.distribution!==null}function jd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Ad):null}var Md=class{localDir;log;ttlMs;fetchImpl;memory=null;inflight=null;constructor(e){this.localDir=e.localDir,this.log=e.log,this.ttlMs=e.ttlMs??36e5,this.fetchImpl=e.fetchImpl??fetch}async getCatalog(){return this.memory!==null&&Date.now()-this.memory.fetchedAt<this.ttlMs&&!this.memory.stale?this.memory:(this.inflight===null&&(this.inflight=this.refresh().finally(()=>{this.inflight=null})),this.inflight)}async getAgent(e){let{agents:t}=await this.getCatalog();return t.find(t=>t.id===e)}async refresh(){try{let e=await this.fetchImpl(`https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json`,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw Error(`registry fetch failed: HTTP ${e.status}`);let t=await e.text(),n=jd(t);if(n===null)throw Error(`registry payload did not parse as a catalog`);this.memory={agents:n,fetchedAt:Date.now(),stale:!1};try{let{tracedMkdir:e,tracedWriteFile:n}=await import(`./fs-traced-DbSNN5G0.mjs`);await e(this.localDir,{recursive:!0}),await n(z(this.localDir,Od),t)}catch(e){this.log.warn({err:e},`[acp-registry] disk cache write failed`)}return this.memory}catch(e){let t=await this.readDiskCache();if(t!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving disk cache`),this.memory=t,t;if(this.memory!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving stale memory copy`),this.memory={...this.memory,stale:!0},this.memory;throw e instanceof Error?e:Error(String(e))}}async readDiskCache(){try{let e=jd(await pu(z(this.localDir,Od),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Nd(e,t){let n;try{n=await pu(z(e,Dd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Dd} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return[];let i=[];for(let e of r){let n=e;typeof n?.id==`string`&&/^[a-zA-Z0-9_-]+$/.test(n.id)&&typeof n.name==`string`&&typeof n.command==`string`&&n.command.length>0&&(n.args===void 0||Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))&&(n.env===void 0||typeof n.env==`object`&&n.env!==null&&!Array.isArray(n.env)&&Object.values(n.env).every(e=>typeof e==`string`))?i.push({id:n.id,name:n.name,command:n.command,args:n.args,env:n.env??void 0}):t.warn({entry:e},`[acp-registry] dropping malformed ${Dd} entry`)}return i}const Pd={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,nes_accept:`nes/accept`,nes_reject:`nes/reject`,nes_close:`nes/close`,document_did_open:`document/didOpen`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_save:`document/didSave`,document_did_focus:`document/didFocus`},Fd={session_request_permission:`session/request_permission`,session_update:`session/update`,fs_write_text_file:`fs/write_text_file`,fs_read_text_file:`fs/read_text_file`,terminal_create:`terminal/create`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`,terminal_kill:`terminal/kill`,mcp_connect:`mcp/connect`,mcp_message:`mcp/message`,mcp_disconnect:`mcp/disconnect`,elicitation_create:`elicitation/create`,elicitation_complete:`elicitation/complete`},Id={cancel_request:`$/cancel_request`},Ld=Symbol(`skippedItem`);function G(e,t){return e.catch(t)}function Rd(e,t){let n=e.catch(t);return O().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),S):n.parse(e))}function zd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Bd(e,t,n){return e.superRefine((e,r)=>{let i=zd(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Vd(e,t,n){return O().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return S}let o=a.data,s=zd(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function Hd(e){return j(e.catch(Ld)).transform(e=>e.filter(e=>e!==Ld))}const Ud=I([N(),F()]).nullable(),Wd=F(),Gd=M({sessionId:Wd,path:F(),content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kd=M({sessionId:Wd,path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qd=F(),Jd=I([k(`read`),k(`edit`),k(`delete`),k(`move`),k(`search`),k(`execute`),k(`think`),k(`fetch`),k(`switch_mode`),k(`other`)]),Yd=I([k(`pending`),k(`in_progress`),k(`completed`),k(`failed`)]),Xd=M({audience:G(Hd(I([k(`assistant`),k(`user`)])).nullish(),()=>void 0),lastModified:G(F().nullish(),()=>void 0),priority:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zd=M({annotations:G(Xd.nullish(),()=>void 0),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qd=M({annotations:G(Xd.nullish(),()=>void 0),data:F(),mimeType:F(),uri:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ate=M({annotations:G(Xd.nullish(),()=>void 0),data:F(),mimeType:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),jte=M({annotations:G(Xd.nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),mimeType:G(F().nullish(),()=>void 0),name:F(),size:G(N().nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mte=I([M({mimeType:G(F().nullish(),()=>void 0),text:F(),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({blob:F(),mimeType:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})]),Nte=M({annotations:G(Xd.nullish(),()=>void 0),resource:Mte,_meta:G(E(F(),O()).nullish(),()=>void 0)}),$d=I([Zd.and(M({type:k(`text`)})),Qd.and(M({type:k(`image`)})),Ate.and(M({type:k(`audio`)})),jte.and(M({type:k(`resource_link`)})),Nte.and(M({type:k(`resource`)}))]),Pte=M({content:$d,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fte=M({path:F(),oldText:G(F().nullish(),()=>void 0),newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ef=F(),Ite=M({terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),tf=I([Pte.and(M({type:k(`content`)})),Fte.and(M({type:k(`diff`)})),Ite.and(M({type:k(`terminal`)}))]),nf=M({path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rf=M({toolCallId:qd,kind:G(Jd.nullish(),()=>void 0),status:G(Yd.nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),content:G(Hd(tf).nullish(),()=>void 0),locations:G(Hd(nf).nullish(),()=>void 0),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),af=F(),Lte=I([k(`allow_once`),k(`allow_always`),k(`reject_once`),k(`reject_always`)]),of=M({sessionId:Wd,toolCall:rf,options:j(M({optionId:af,name:F(),kind:Lte,_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sf=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cf=M({sessionId:Wd,command:F(),args:G(Hd(F()).optional(),()=>[]),env:G(Hd(sf).optional(),()=>[]),cwd:G(F().nullish(),()=>void 0),outputByteLimit:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),lf=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),uf=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),df=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),ff=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),pf=M({sessionId:Wd,toolCallId:G(qd.nullish(),()=>void 0)}),mf=M({requestId:Ud}),Rte=k(`object`),zte=I([k(`email`),k(`uri`),k(`date`),k(`date-time`)]),hf=M({const:F(),title:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:F().nullish(),format:zte.nullish(),default:G(F().nullish(),()=>void 0),enum:j(F()).nullish(),oneOf:j(hf).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_f=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),yf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),default:G(D().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bf=M({enum:j(F()),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xf=M({anyOf:j(hf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sf=Vd(I([bf.and(M({type:k(`string`)})),Bd(M({type:F()}),`type`,[`string`]),xf]),`type`,[`string`]),Cf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minItems:N().nullish(),maxItems:N().nullish(),items:Sf,default:G(Hd(F()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wf=Vd(I([gf.and(M({type:k(`string`)})),_f.and(M({type:k(`number`)})),vf.and(M({type:k(`integer`)})),yf.and(M({type:k(`boolean`)})),Cf.and(M({type:k(`array`)})),Bd(M({type:F()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Tf=M({type:G(Rte.optional().default(`object`),()=>`object`),title:G(F().nullish(),()=>void 0),properties:E(F(),wf).optional().default({}),required:j(F()).nullish(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ef=_e(I([pf,mf]),M({requestedSchema:Tf})),Df=F(),Of=_e(I([pf,mf]),M({elicitationId:Df,url:Oe()})),kf=Vd(_e(I([Ef.and(M({mode:k(`form`)})),Of.and(M({mode:k(`url`)})),Bd(_e(I([pf,mf]),M({mode:F()})),`mode`,[`form`,`url`])]),M({message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Af=F(),jf=M({serverId:Af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mf=F(),Nf=M({connectionId:Mf,method:F(),params:E(F(),O()).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Pf=M({connectionId:Mf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ff=O();M({id:Ud,method:F(),params:I([Gd,Kd,of,cf,lf,uf,df,ff,kf,jf,Nf,Pf,Ff]).nullish()});const If=oe().gte(0).lte(65535),Lf=M({image:G(D().optional().default(!1),()=>!1),audio:G(D().optional().default(!1),()=>!1),embeddedContext:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rf=M({http:G(D().optional().default(!1),()=>!1),sse:G(D().optional().default(!1),()=>!1),acp:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),zf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Uf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gf=M({list:G(zf.nullish(),()=>void 0),delete:G(Bf.nullish(),()=>void 0),additionalDirectories:G(Vf.nullish(),()=>void 0),fork:G(Hf.nullish(),()=>void 0),resume:G(Uf.nullish(),()=>void 0),close:G(Wf.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kf=M({logout:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yf=M({syncKind:I([k(`full`),k(`incremental`)]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),$f=M({document:G(M({didOpen:G(Jf.nullish(),()=>void 0),didChange:G(Yf.nullish(),()=>void 0),didClose:G(Xf.nullish(),()=>void 0),didSave:G(Zf.nullish(),()=>void 0),didFocus:G(Qf.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ep=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),tp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),np=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rp=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ip=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ap=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),op=M({recentFiles:G(ep.nullish(),()=>void 0),relatedSnippets:G(tp.nullish(),()=>void 0),editHistory:G(np.nullish(),()=>void 0),userActions:G(rp.nullish(),()=>void 0),openFiles:G(ip.nullish(),()=>void 0),diagnostics:G(ap.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sp=M({events:G($f.nullish(),()=>void 0),context:G(op.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cp=I([k(`utf-16`),k(`utf-32`),k(`utf-8`)]),lp=M({loadSession:G(D().optional().default(!1),()=>!1),promptCapabilities:G(Lf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:G(Rf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:G(Gf.optional().default({}),()=>({})),auth:G(Kf.optional().default({}),()=>({})),providers:G(qf.nullish(),()=>void 0),nes:G(sp.nullish(),()=>void 0),positionEncoding:G(cp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),up=F(),dp=M({name:F(),label:G(F().nullish(),()=>void 0),secret:G(D().optional().default(!0),()=>!0),optional:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fp=M({id:up,name:F(),description:G(F().nullish(),()=>void 0),vars:Rd(Hd(dp),()=>[]),link:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pp=M({id:up,name:F(),description:G(F().nullish(),()=>void 0),args:G(Hd(F()).optional(),()=>[]),env:G(E(F(),F()).optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mp=M({id:up,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hp=I([fp.and(M({type:k(`env_var`)})),pp.and(M({type:k(`terminal`)})),mp]),gp=M({name:F(),title:G(F().nullish(),()=>void 0),version:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_p=M({protocolVersion:If,agentCapabilities:G(lp.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:G(Hd(hp).optional().default([]),()=>[]),agentInfo:G(gp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),yp=F(),bp=I([k(`anthropic`),k(`openai`),k(`azure`),k(`vertex`),k(`bedrock`),F()]),xp=M({apiType:bp,baseUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sp=M({providers:j(M({providerId:yp,supported:Rd(Hd(bp),()=>[]),required:D(),current:xp.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),wp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ep=F(),Dp=M({currentModeId:Ep,availableModes:Rd(Hd(M({id:Ep,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Op=F(),kp=I([k(`mode`),k(`model`),k(`model_config`),k(`thought_level`),F()]),Ap=F(),jp=M({value:Ap,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mp=M({group:F(),name:F(),options:Rd(Hd(jp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Np=M({currentValue:Ap,options:I([j(jp),j(Mp)])}),Pp=M({currentValue:D()}),Fp=_e(I([Np.and(M({type:k(`select`)})),Pp.and(M({type:k(`boolean`)}))]),M({id:Op,name:F(),description:G(F().nullish(),()=>void 0),category:G(kp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),Ip=M({sessionId:Wd,modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lp=M({modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rp=M({sessions:Rd(Hd(M({sessionId:Wd,cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),nextCursor:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),zp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bp=M({sessionId:Wd,modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vp=M({modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Up=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wp=M({configOptions:Rd(Hd(Fp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gp=M({stopReason:I([k(`end_turn`),k(`max_tokens`),k(`max_turn_requests`),k(`refusal`),k(`cancelled`)]),usage:G(M({totalTokens:N(),inputTokens:N(),outputTokens:N(),thoughtTokens:G(N().nullish(),()=>void 0),cachedReadTokens:G(N().nullish(),()=>void 0),cachedWriteTokens:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kp=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),qp=F(),Jp=M({line:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yp=M({start:Jp,end:Jp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xp=M({range:Yp,newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zp=M({id:qp,uri:F(),edits:j(Xp),cursorPosition:G(Jp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qp=M({id:qp,uri:F(),position:Jp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),$p=M({id:qp,uri:F(),position:Jp,newName:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),em=M({id:qp,uri:F(),search:F(),replace:F(),isRegex:D().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),tm=M({suggestions:j(I([Zp.and(M({kind:k(`edit`)})),Qp.and(M({kind:k(`jump`)})),$p.and(M({kind:k(`rename`)})),em.and(M({kind:k(`searchAndReplace`)}))])),_meta:G(E(F(),O()).nullish(),()=>void 0)}),nm=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),rm=O(),im=O(),am=M({code:I([k(-32700),k(-32600),k(-32601),k(-32602),k(-32603),k(-32800),k(-32e3),k(-32002),oe().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:F(),data:G(O().optional(),()=>void 0)});I([M({id:Ud,result:I([_p,vp,Sp,Cp,wp,Tp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,tm,nm,rm,im])}),M({id:Ud,error:am})]);const om=M({content:$d,messageId:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sm=M({toolCallId:qd,title:F(),kind:G(Jd.optional(),()=>void 0),status:G(Yd.optional(),()=>void 0),content:G(Hd(tf).optional(),()=>[]),locations:G(Hd(nf).optional(),()=>[]),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cm=I([k(`high`),k(`medium`),k(`low`)]),lm=I([k(`pending`),k(`in_progress`),k(`completed`)]),um=M({content:F(),priority:cm,status:lm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),dm=M({entries:Rd(Hd(um),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fm=F(),pm=M({planId:fm,entries:Rd(Hd(um),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mm=M({planId:fm,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hm=M({planId:fm,content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gm=M({plan:I([pm.and(M({type:k(`items`)})),mm.and(M({type:k(`file`)})),hm.and(M({type:k(`markdown`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_m=M({planId:fm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),vm=M({hint:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bte=M({availableCommands:Rd(Hd(M({name:F(),description:F(),input:G(vm.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vte=M({currentModeId:Ep,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hte=M({configOptions:Rd(Hd(Fp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ute=M({title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wte=M({amount:N(),currency:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gte=M({used:N(),size:N(),cost:G(Wte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ym=M({sessionId:Wd,update:I([om.and(M({sessionUpdate:k(`user_message_chunk`)})),om.and(M({sessionUpdate:k(`agent_message_chunk`)})),om.and(M({sessionUpdate:k(`agent_thought_chunk`)})),sm.and(M({sessionUpdate:k(`tool_call`)})),rf.and(M({sessionUpdate:k(`tool_call_update`)})),dm.and(M({sessionUpdate:k(`plan`)})),gm.and(M({sessionUpdate:k(`plan_update`)})),_m.and(M({sessionUpdate:k(`plan_removed`)})),Bte.and(M({sessionUpdate:k(`available_commands_update`)})),Vte.and(M({sessionUpdate:k(`current_mode_update`)})),Hte.and(M({sessionUpdate:k(`config_option_update`)})),Ute.and(M({sessionUpdate:k(`session_info_update`)})),Gte.and(M({sessionUpdate:k(`usage_update`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bm=M({elicitationId:Df,_meta:G(E(F(),O()).nullish(),()=>void 0)}),xm=M({connectionId:Mf,method:F(),params:G(E(F(),O()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sm=O();M({method:F(),params:I([ym,bm,xm,Sm]).nullish()});const Kte=M({readTextFile:G(D().optional().default(!1),()=>!1),writeTextFile:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qte=M({configOptions:G(M({boolean:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yte=M({terminal:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qte=M({form:G(Xte.nullish(),()=>void 0),url:G(Zte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),$te=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ene=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),tne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),nne=M({jump:G($te.nullish(),()=>void 0),rename:G(ene.nullish(),()=>void 0),searchAndReplace:G(tne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cm=M({protocolVersion:If,clientCapabilities:G(M({fs:G(Kte.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:G(D().optional().default(!1),()=>!1),session:G(qte.nullish(),()=>void 0),plan:G(Jte.nullish(),()=>void 0),auth:G(Yte.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:G(Qte.nullish(),()=>void 0),nes:G(nne.nullish(),()=>void 0),positionEncodings:G(Hd(cp).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:G(gp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wm=M({methodId:up,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tm=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Em=M({providerId:yp,apiType:bp,baseUrl:F(),headers:E(F(),F()).optional(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dm=M({providerId:yp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Om=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),km=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rne=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ine=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ane=M({name:F(),serverId:Af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),one=M({name:F(),command:F(),args:j(F()),env:j(sf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Am=I([rne.and(M({type:k(`http`)})),ine.and(M({type:k(`sse`)})),ane.and(M({type:k(`acp`)})),one]),jm=M({cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),mcpServers:Rd(Hd(Am),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mm=M({mcpServers:Rd(Hd(Am),()=>[]),cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Nm=M({cwd:F().nullish(),cursor:F().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Pm=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fm=M({sessionId:Wd,cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),mcpServers:G(Hd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Im=M({sessionId:Wd,cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),mcpServers:G(Hd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lm=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rm=M({sessionId:Wd,modeId:Ep,_meta:G(E(F(),O()).nullish(),()=>void 0)}),zm=_e(I([M({value:D(),type:k(`boolean`)}),M({value:Ap})]),M({sessionId:Wd,configId:Op,_meta:G(E(F(),O()).nullish(),()=>void 0)})),Bm=M({sessionId:Wd,prompt:j($d),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sne=M({uri:F(),name:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cne=M({name:F(),owner:F(),remoteUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vm=M({workspaceUri:G(F().nullish(),()=>void 0),workspaceFolders:j(sne).nullish(),repository:G(cne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),lne=I([k(`automatic`),k(`diagnostic`),k(`manual`)]),une=M({uri:F(),languageId:F(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dne=M({startLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fne=M({uri:F(),excerpts:j(dne),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pne=M({uri:F(),diff:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mne=M({action:F(),uri:F(),position:Jp,timestampMs:N(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hne=M({uri:F(),languageId:F(),visibleRange:G(Yp.nullish(),()=>void 0),lastFocusedMs:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gne=I([k(`error`),k(`warning`),k(`information`),k(`hint`)]),_ne=M({uri:F(),range:Yp,severity:gne,message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vne=M({recentFiles:j(une).nullish(),relatedSnippets:j(fne).nullish(),editHistory:j(pne).nullish(),userActions:j(mne).nullish(),openFiles:j(hne).nullish(),diagnostics:j(_ne).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hm=M({sessionId:Wd,uri:F(),version:N(),position:Jp,selection:Yp.nullish(),triggerKind:lne,context:vne.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Um=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)});M({id:Ud,method:F(),params:I([Cm,wm,Tm,Em,Dm,Om,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Nf,Ff]).nullish()});const yne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),bne=M({content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xne=M({optionId:af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sne=M({outcome:I([M({outcome:k(`cancelled`)}),xne.and(M({outcome:k(`selected`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cne=M({terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),wne=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tne=M({output:F(),truncated:D(),exitStatus:G(wne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ene=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dne=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),One=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),kne=I([F(),N(),N(),D(),j(F())]),Wm=M({content:E(F(),kne).nullish()});I([M({id:Ud,result:I([yne,bne,Sne,Cne,Tne,Ene,Dne,One,Vd(_e(I([Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)}),Bd(M({action:F()}),`action`,[`accept`,`cancel`,`decline`])]),M({_meta:G(E(F(),O()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),M({connectionId:Mf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),im,rm])}),M({id:Ud,error:am})]);const Gm=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Km=M({sessionId:Wd,uri:F(),languageId:F(),version:N(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ane=M({range:Yp.nullish(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qm=M({sessionId:Wd,uri:F(),version:N(),contentChanges:Rd(Hd(Ane),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jm=M({sessionId:Wd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ym=M({sessionId:Wd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xm=M({sessionId:Wd,uri:F(),version:N(),position:Jp,visibleRange:Yp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zm=M({sessionId:Wd,id:qp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qm=M({sessionId:Wd,id:qp,reason:G(I([k(`rejected`),k(`ignored`),k(`replaced`),k(`cancelled`)]).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)});M({method:F(),params:I([Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,xm,Sm]).nullish()}),M({requestId:Ud,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ef.and(M({mode:k(`form`)})).and(M({message:F()})),Of.and(M({mode:k(`url`)})).and(M({message:F()})),I([pf,mf]).and(M({message:F()})),gf.and(M({type:k(`string`)})),_f.and(M({type:k(`number`)})),vf.and(M({type:k(`integer`)})),yf.and(M({type:k(`boolean`)})),Cf.and(M({type:k(`array`)})),bf.and(M({type:k(`string`)})),Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)});const $m=`$/cancel_request`;function eh(e){return typeof e==`object`&&!!e}function jne(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Mne(e){if(!(!eh(e)||!jne(e.requestId)))return e.requestId}const th={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function nh(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Nne(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Pne(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`&&`issues`in e&&Array.isArray(e.issues)&&`format`in e&&typeof e.format==`function`}function rh(e){if(e instanceof oh)return e.toResult();if(Pne(e))return oh.invalidParams(e.format()).toResult();let t=Nne(e);try{return oh.internalError(t?JSON.parse(t):{}).toResult()}catch{return oh.internalError({details:t}).toResult()}}function Fne(e){return e instanceof oh&&e.code===-32800?e:oh.requestCancelled(e)}function Ine(e,t){let n=Lne(e,t);return n?n.toResult():rh(e)}function Lne(e,t){if(!(!t.aborted||!Rne(e)))return Fne(t.reason)}function Rne(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var zne=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof oh?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?nh(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},ih=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Bne=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ah=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Bne(this);receiveReader;constructor(e,t,n,r){if(typeof e==`function`){let i=e,a=t,o=n;this.initialize(o,[...r?.handlers??[],this.legacyHandler(i,a)]);return}let i=e,a=t,o=n;this.initialize(i,[...o?.handlers??[],...a])}static builder(){return new Vne}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let e of this.retryQueue.splice(0))this.processIncomingMessage(e).catch(e=>this.close(e));return new ih(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return nh(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification($m,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?nh(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return th.yes()}}}async receive(){let e;try{let e=this.stream.readable.getReader();this.receiveReader=e;try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(this.abortController.signal.aborted||n)break;t&&this.receiveMessage(t)}}finally{this.receiveReader===e&&(this.receiveReader=void 0),e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveMessage(e){if(!this.abortController.signal.aborted){if(!eh(e)){console.error(`Invalid message`,{message:e});return}`method`in e?(`id`in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e)).catch(e=>this.close(e))):`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e})}}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let e of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let r=await e.handleMessage(t,this.context)??{handled:!0};if(r.handled)return;t=r.message??t,n||=!!r.retry}n?this.retryQueue.push(t):t.kind===`request`&&await t.responder.respondWithError(oh.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Ine(n,t.responder.signal));else{let t=rh(n);`error`in t&&console.error(`Error handling notification`,e.raw,t.error)}}}toIncomingMessage(e){if(`id`in e){let t=new AbortController;return this.incomingRequests.set(e.id,t),{kind:`request`,method:e.method,params:e.params,raw:e,signal:t.signal,responder:new zne(e.id,t=>this.sendMessage({jsonrpc:`2.0`,id:e.id,...t}),t.signal,()=>{this.incomingRequests.get(e.id)===t&&this.incomingRequests.delete(e.id)})}}return{kind:`notification`,method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),`result`in e)t.resolve(e.result);else if(`error`in e&&eh(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new oh(n,r,i))}else t.reject(oh.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==$m)return;let t=Mne(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(oh.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?nh(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},Vne=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??th.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?th.no(r):await n(t(r.params),r.responder,i)??th.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?th.no(r):await n(t(r.params),i)??th.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new ah(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},oh=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static requestCancelled(t,n){return new e(-32800,`Request cancelled${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}},Hne=class{#e=[];push(e){let t=[],n=0,r=e.indexOf(10,n);for(;r!==-1;)t.push(this.#t(e.subarray(n,r))),n=r+1,r=e.indexOf(10,n);return n<e.byteLength&&this.#e.push(n===0?e:new Uint8Array(e.subarray(n))),t}flush(){if(this.#e.length!==0)return this.#t(new Uint8Array)}#t(e){if(this.#e.length===0)return e;let t=e.byteLength;for(let e of this.#e)t+=e.byteLength;let n=new Uint8Array(t),r=0;for(let e of this.#e)n.set(e,r),r+=e.byteLength;return n.set(e,r),this.#e=[],n}};function Une(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Hne,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);eh(t)?e.enqueue(t):console.warn(`Skipping JSON line that is not an object:`,n)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}},s=t.getReader();a=s;try{for(;;){let{value:e,done:t}=await s.read();if(i)return;if(t)break;if(e){for(let t of n.push(e))if(o(t),i)return}}if(i)return;let e=n.flush();e&&o(e)}catch(t){if(i)return;e.error(t);return}finally{a===s&&(a=void 0),s.releaseLock()}i||e.close()},cancel(e){return i=!0,a?.cancel(e)}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
|
|
4
|
+
`)){let e=n.trim();if(!e.startsWith(ld))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=dd(r);i&&t.push(i)}return t}function Cte(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function hd(e){let t=md(e);return t.length>0?t.map(Cte):cd(e)}function gd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function _d(e){return`reconcile: ${e}`}function vd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function wte(e,t){return`park: ${e} -> ${t}`}function yd(e,t){return`rename: ${e} -> ${t}`}function bd(e){return`checkpoint: ${e}`}function Tte(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Ete=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function xd(e){return e.replace(Ete,` `)}function Dte(e,t){let n=xd(e);if(t.length===0)return n;if(t.length>=2)return`${n} (${t.length} edits)`;let[r]=t;if(r===void 0)return n;let i=xd(r),a=`${n} — ${i}`;if(a.length<=72)return a;let o=`${n} — `,s=72-o.length-1;return s<=0?a.slice(0,72):`${o}${i.slice(0,s)}…`}function Sd(e){return bte.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function Cd(e){let t=ed(e);if(t.kind!==`linked`)return V(e);try{let n=U(z(t.path,`commondir`),`utf-8`).trim();return n===``?V(e):V(R(V(t.path,n)),t.projectSubPath)}catch{return V(e)}}function wd(e){return e.kind??`other`}function Ote(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Td=class{filePath;log;grants=null;constructor(e,t){this.filePath=z(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=wd(t),i=Ote(n,[`allow_once`,`allow_always`]);return i===void 0?{auto:null}:r===`read`||this.hasAllowAlways(e,r)?{auto:{optionId:i.optionId}}:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n){if(n.kind!==`allow_always`)return;let r=wd(t);if(this.hasAllowAlways(e,r))return;let i=[...this.loadGrants(),{agentId:e,toolKind:r}];this.grants=i;try{let{tracedMkdir:e,tracedWriteFile:t}=await import(`./fs-traced-CbQ-GS7x.mjs`);await e(z(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(U(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const Ed=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],kte={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Dd=`acp-agents.json`,Od=`acp-registry-cache.json`;function kd(){let e=su(),t=ru(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`windows`:null,r=t===`arm64`?`aarch64`:t===`x64`?`x86_64`:null;return n===null||r===null?null:`${n}-${r}`}function Ad(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.name==`string`&&typeof t.version==`string`&&typeof t.distribution==`object`&&t.distribution!==null}function jd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Ad):null}var Md=class{localDir;log;ttlMs;fetchImpl;memory=null;inflight=null;constructor(e){this.localDir=e.localDir,this.log=e.log,this.ttlMs=e.ttlMs??36e5,this.fetchImpl=e.fetchImpl??fetch}async getCatalog(){return this.memory!==null&&Date.now()-this.memory.fetchedAt<this.ttlMs&&!this.memory.stale?this.memory:(this.inflight===null&&(this.inflight=this.refresh().finally(()=>{this.inflight=null})),this.inflight)}async getAgent(e){let{agents:t}=await this.getCatalog();return t.find(t=>t.id===e)}async refresh(){try{let e=await this.fetchImpl(`https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json`,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw Error(`registry fetch failed: HTTP ${e.status}`);let t=await e.text(),n=jd(t);if(n===null)throw Error(`registry payload did not parse as a catalog`);this.memory={agents:n,fetchedAt:Date.now(),stale:!1};try{let{tracedMkdir:e,tracedWriteFile:n}=await import(`./fs-traced-CbQ-GS7x.mjs`);await e(this.localDir,{recursive:!0}),await n(z(this.localDir,Od),t)}catch(e){this.log.warn({err:e},`[acp-registry] disk cache write failed`)}return this.memory}catch(e){let t=await this.readDiskCache();if(t!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving disk cache`),this.memory=t,t;if(this.memory!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving stale memory copy`),this.memory={...this.memory,stale:!0},this.memory;throw e instanceof Error?e:Error(String(e))}}async readDiskCache(){try{let e=jd(await pu(z(this.localDir,Od),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Nd(e,t){let n;try{n=await pu(z(e,Dd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Dd} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return[];let i=[];for(let e of r){let n=e;typeof n?.id==`string`&&/^[a-zA-Z0-9_-]+$/.test(n.id)&&typeof n.name==`string`&&typeof n.command==`string`&&n.command.length>0&&(n.args===void 0||Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))&&(n.env===void 0||typeof n.env==`object`&&n.env!==null&&!Array.isArray(n.env)&&Object.values(n.env).every(e=>typeof e==`string`))?i.push({id:n.id,name:n.name,command:n.command,args:n.args,env:n.env??void 0}):t.warn({entry:e},`[acp-registry] dropping malformed ${Dd} entry`)}return i}const Pd={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,nes_accept:`nes/accept`,nes_reject:`nes/reject`,nes_close:`nes/close`,document_did_open:`document/didOpen`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_save:`document/didSave`,document_did_focus:`document/didFocus`},Fd={session_request_permission:`session/request_permission`,session_update:`session/update`,fs_write_text_file:`fs/write_text_file`,fs_read_text_file:`fs/read_text_file`,terminal_create:`terminal/create`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`,terminal_kill:`terminal/kill`,mcp_connect:`mcp/connect`,mcp_message:`mcp/message`,mcp_disconnect:`mcp/disconnect`,elicitation_create:`elicitation/create`,elicitation_complete:`elicitation/complete`},Id={cancel_request:`$/cancel_request`},Ld=Symbol(`skippedItem`);function G(e,t){return e.catch(t)}function Rd(e,t){let n=e.catch(t);return O().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),S):n.parse(e))}function zd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Bd(e,t,n){return e.superRefine((e,r)=>{let i=zd(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Vd(e,t,n){return O().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return S}let o=a.data,s=zd(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function Hd(e){return j(e.catch(Ld)).transform(e=>e.filter(e=>e!==Ld))}const Ud=I([N(),F()]).nullable(),Wd=F(),Gd=M({sessionId:Wd,path:F(),content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kd=M({sessionId:Wd,path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qd=F(),Jd=I([k(`read`),k(`edit`),k(`delete`),k(`move`),k(`search`),k(`execute`),k(`think`),k(`fetch`),k(`switch_mode`),k(`other`)]),Yd=I([k(`pending`),k(`in_progress`),k(`completed`),k(`failed`)]),Xd=M({audience:G(Hd(I([k(`assistant`),k(`user`)])).nullish(),()=>void 0),lastModified:G(F().nullish(),()=>void 0),priority:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zd=M({annotations:G(Xd.nullish(),()=>void 0),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qd=M({annotations:G(Xd.nullish(),()=>void 0),data:F(),mimeType:F(),uri:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ate=M({annotations:G(Xd.nullish(),()=>void 0),data:F(),mimeType:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),jte=M({annotations:G(Xd.nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),mimeType:G(F().nullish(),()=>void 0),name:F(),size:G(N().nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mte=I([M({mimeType:G(F().nullish(),()=>void 0),text:F(),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({blob:F(),mimeType:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})]),Nte=M({annotations:G(Xd.nullish(),()=>void 0),resource:Mte,_meta:G(E(F(),O()).nullish(),()=>void 0)}),$d=I([Zd.and(M({type:k(`text`)})),Qd.and(M({type:k(`image`)})),Ate.and(M({type:k(`audio`)})),jte.and(M({type:k(`resource_link`)})),Nte.and(M({type:k(`resource`)}))]),Pte=M({content:$d,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fte=M({path:F(),oldText:G(F().nullish(),()=>void 0),newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ef=F(),Ite=M({terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),tf=I([Pte.and(M({type:k(`content`)})),Fte.and(M({type:k(`diff`)})),Ite.and(M({type:k(`terminal`)}))]),nf=M({path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rf=M({toolCallId:qd,kind:G(Jd.nullish(),()=>void 0),status:G(Yd.nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),content:G(Hd(tf).nullish(),()=>void 0),locations:G(Hd(nf).nullish(),()=>void 0),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),af=F(),Lte=I([k(`allow_once`),k(`allow_always`),k(`reject_once`),k(`reject_always`)]),of=M({sessionId:Wd,toolCall:rf,options:j(M({optionId:af,name:F(),kind:Lte,_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sf=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cf=M({sessionId:Wd,command:F(),args:G(Hd(F()).optional(),()=>[]),env:G(Hd(sf).optional(),()=>[]),cwd:G(F().nullish(),()=>void 0),outputByteLimit:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),lf=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),uf=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),df=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),ff=M({sessionId:Wd,terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),pf=M({sessionId:Wd,toolCallId:G(qd.nullish(),()=>void 0)}),mf=M({requestId:Ud}),Rte=k(`object`),zte=I([k(`email`),k(`uri`),k(`date`),k(`date-time`)]),hf=M({const:F(),title:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:F().nullish(),format:zte.nullish(),default:G(F().nullish(),()=>void 0),enum:j(F()).nullish(),oneOf:j(hf).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_f=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),yf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),default:G(D().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bf=M({enum:j(F()),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xf=M({anyOf:j(hf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sf=Vd(I([bf.and(M({type:k(`string`)})),Bd(M({type:F()}),`type`,[`string`]),xf]),`type`,[`string`]),Cf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minItems:N().nullish(),maxItems:N().nullish(),items:Sf,default:G(Hd(F()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wf=Vd(I([gf.and(M({type:k(`string`)})),_f.and(M({type:k(`number`)})),vf.and(M({type:k(`integer`)})),yf.and(M({type:k(`boolean`)})),Cf.and(M({type:k(`array`)})),Bd(M({type:F()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Tf=M({type:G(Rte.optional().default(`object`),()=>`object`),title:G(F().nullish(),()=>void 0),properties:E(F(),wf).optional().default({}),required:j(F()).nullish(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ef=_e(I([pf,mf]),M({requestedSchema:Tf})),Df=F(),Of=_e(I([pf,mf]),M({elicitationId:Df,url:Oe()})),kf=Vd(_e(I([Ef.and(M({mode:k(`form`)})),Of.and(M({mode:k(`url`)})),Bd(_e(I([pf,mf]),M({mode:F()})),`mode`,[`form`,`url`])]),M({message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Af=F(),jf=M({serverId:Af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mf=F(),Nf=M({connectionId:Mf,method:F(),params:E(F(),O()).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Pf=M({connectionId:Mf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ff=O();M({id:Ud,method:F(),params:I([Gd,Kd,of,cf,lf,uf,df,ff,kf,jf,Nf,Pf,Ff]).nullish()});const If=oe().gte(0).lte(65535),Lf=M({image:G(D().optional().default(!1),()=>!1),audio:G(D().optional().default(!1),()=>!1),embeddedContext:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rf=M({http:G(D().optional().default(!1),()=>!1),sse:G(D().optional().default(!1),()=>!1),acp:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),zf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Uf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gf=M({list:G(zf.nullish(),()=>void 0),delete:G(Bf.nullish(),()=>void 0),additionalDirectories:G(Vf.nullish(),()=>void 0),fork:G(Hf.nullish(),()=>void 0),resume:G(Uf.nullish(),()=>void 0),close:G(Wf.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kf=M({logout:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yf=M({syncKind:I([k(`full`),k(`incremental`)]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),$f=M({document:G(M({didOpen:G(Jf.nullish(),()=>void 0),didChange:G(Yf.nullish(),()=>void 0),didClose:G(Xf.nullish(),()=>void 0),didSave:G(Zf.nullish(),()=>void 0),didFocus:G(Qf.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ep=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),tp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),np=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rp=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ip=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ap=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),op=M({recentFiles:G(ep.nullish(),()=>void 0),relatedSnippets:G(tp.nullish(),()=>void 0),editHistory:G(np.nullish(),()=>void 0),userActions:G(rp.nullish(),()=>void 0),openFiles:G(ip.nullish(),()=>void 0),diagnostics:G(ap.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sp=M({events:G($f.nullish(),()=>void 0),context:G(op.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cp=I([k(`utf-16`),k(`utf-32`),k(`utf-8`)]),lp=M({loadSession:G(D().optional().default(!1),()=>!1),promptCapabilities:G(Lf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:G(Rf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:G(Gf.optional().default({}),()=>({})),auth:G(Kf.optional().default({}),()=>({})),providers:G(qf.nullish(),()=>void 0),nes:G(sp.nullish(),()=>void 0),positionEncoding:G(cp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),up=F(),dp=M({name:F(),label:G(F().nullish(),()=>void 0),secret:G(D().optional().default(!0),()=>!0),optional:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fp=M({id:up,name:F(),description:G(F().nullish(),()=>void 0),vars:Rd(Hd(dp),()=>[]),link:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pp=M({id:up,name:F(),description:G(F().nullish(),()=>void 0),args:G(Hd(F()).optional(),()=>[]),env:G(E(F(),F()).optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mp=M({id:up,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hp=I([fp.and(M({type:k(`env_var`)})),pp.and(M({type:k(`terminal`)})),mp]),gp=M({name:F(),title:G(F().nullish(),()=>void 0),version:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_p=M({protocolVersion:If,agentCapabilities:G(lp.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:G(Hd(hp).optional().default([]),()=>[]),agentInfo:G(gp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),yp=F(),bp=I([k(`anthropic`),k(`openai`),k(`azure`),k(`vertex`),k(`bedrock`),F()]),xp=M({apiType:bp,baseUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sp=M({providers:j(M({providerId:yp,supported:Rd(Hd(bp),()=>[]),required:D(),current:xp.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),wp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ep=F(),Dp=M({currentModeId:Ep,availableModes:Rd(Hd(M({id:Ep,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Op=F(),kp=I([k(`mode`),k(`model`),k(`model_config`),k(`thought_level`),F()]),Ap=F(),jp=M({value:Ap,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mp=M({group:F(),name:F(),options:Rd(Hd(jp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Np=M({currentValue:Ap,options:I([j(jp),j(Mp)])}),Pp=M({currentValue:D()}),Fp=_e(I([Np.and(M({type:k(`select`)})),Pp.and(M({type:k(`boolean`)}))]),M({id:Op,name:F(),description:G(F().nullish(),()=>void 0),category:G(kp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),Ip=M({sessionId:Wd,modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lp=M({modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rp=M({sessions:Rd(Hd(M({sessionId:Wd,cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),nextCursor:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),zp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bp=M({sessionId:Wd,modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vp=M({modes:G(Dp.nullish(),()=>void 0),configOptions:G(Hd(Fp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Up=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wp=M({configOptions:Rd(Hd(Fp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gp=M({stopReason:I([k(`end_turn`),k(`max_tokens`),k(`max_turn_requests`),k(`refusal`),k(`cancelled`)]),usage:G(M({totalTokens:N(),inputTokens:N(),outputTokens:N(),thoughtTokens:G(N().nullish(),()=>void 0),cachedReadTokens:G(N().nullish(),()=>void 0),cachedWriteTokens:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kp=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),qp=F(),Jp=M({line:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yp=M({start:Jp,end:Jp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xp=M({range:Yp,newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zp=M({id:qp,uri:F(),edits:j(Xp),cursorPosition:G(Jp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qp=M({id:qp,uri:F(),position:Jp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),$p=M({id:qp,uri:F(),position:Jp,newName:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),em=M({id:qp,uri:F(),search:F(),replace:F(),isRegex:D().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),tm=M({suggestions:j(I([Zp.and(M({kind:k(`edit`)})),Qp.and(M({kind:k(`jump`)})),$p.and(M({kind:k(`rename`)})),em.and(M({kind:k(`searchAndReplace`)}))])),_meta:G(E(F(),O()).nullish(),()=>void 0)}),nm=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),rm=O(),im=O(),am=M({code:I([k(-32700),k(-32600),k(-32601),k(-32602),k(-32603),k(-32800),k(-32e3),k(-32002),oe().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:F(),data:G(O().optional(),()=>void 0)});I([M({id:Ud,result:I([_p,vp,Sp,Cp,wp,Tp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,tm,nm,rm,im])}),M({id:Ud,error:am})]);const om=M({content:$d,messageId:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sm=M({toolCallId:qd,title:F(),kind:G(Jd.optional(),()=>void 0),status:G(Yd.optional(),()=>void 0),content:G(Hd(tf).optional(),()=>[]),locations:G(Hd(nf).optional(),()=>[]),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cm=I([k(`high`),k(`medium`),k(`low`)]),lm=I([k(`pending`),k(`in_progress`),k(`completed`)]),um=M({content:F(),priority:cm,status:lm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),dm=M({entries:Rd(Hd(um),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fm=F(),pm=M({planId:fm,entries:Rd(Hd(um),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mm=M({planId:fm,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hm=M({planId:fm,content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gm=M({plan:I([pm.and(M({type:k(`items`)})),mm.and(M({type:k(`file`)})),hm.and(M({type:k(`markdown`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_m=M({planId:fm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),vm=M({hint:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bte=M({availableCommands:Rd(Hd(M({name:F(),description:F(),input:G(vm.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vte=M({currentModeId:Ep,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hte=M({configOptions:Rd(Hd(Fp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ute=M({title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wte=M({amount:N(),currency:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gte=M({used:N(),size:N(),cost:G(Wte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ym=M({sessionId:Wd,update:I([om.and(M({sessionUpdate:k(`user_message_chunk`)})),om.and(M({sessionUpdate:k(`agent_message_chunk`)})),om.and(M({sessionUpdate:k(`agent_thought_chunk`)})),sm.and(M({sessionUpdate:k(`tool_call`)})),rf.and(M({sessionUpdate:k(`tool_call_update`)})),dm.and(M({sessionUpdate:k(`plan`)})),gm.and(M({sessionUpdate:k(`plan_update`)})),_m.and(M({sessionUpdate:k(`plan_removed`)})),Bte.and(M({sessionUpdate:k(`available_commands_update`)})),Vte.and(M({sessionUpdate:k(`current_mode_update`)})),Hte.and(M({sessionUpdate:k(`config_option_update`)})),Ute.and(M({sessionUpdate:k(`session_info_update`)})),Gte.and(M({sessionUpdate:k(`usage_update`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bm=M({elicitationId:Df,_meta:G(E(F(),O()).nullish(),()=>void 0)}),xm=M({connectionId:Mf,method:F(),params:G(E(F(),O()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sm=O();M({method:F(),params:I([ym,bm,xm,Sm]).nullish()});const Kte=M({readTextFile:G(D().optional().default(!1),()=>!1),writeTextFile:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qte=M({configOptions:G(M({boolean:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yte=M({terminal:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qte=M({form:G(Xte.nullish(),()=>void 0),url:G(Zte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),$te=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ene=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),tne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),nne=M({jump:G($te.nullish(),()=>void 0),rename:G(ene.nullish(),()=>void 0),searchAndReplace:G(tne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cm=M({protocolVersion:If,clientCapabilities:G(M({fs:G(Kte.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:G(D().optional().default(!1),()=>!1),session:G(qte.nullish(),()=>void 0),plan:G(Jte.nullish(),()=>void 0),auth:G(Yte.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:G(Qte.nullish(),()=>void 0),nes:G(nne.nullish(),()=>void 0),positionEncodings:G(Hd(cp).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:G(gp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wm=M({methodId:up,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tm=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Em=M({providerId:yp,apiType:bp,baseUrl:F(),headers:E(F(),F()).optional(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dm=M({providerId:yp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Om=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),km=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rne=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ine=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ane=M({name:F(),serverId:Af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),one=M({name:F(),command:F(),args:j(F()),env:j(sf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Am=I([rne.and(M({type:k(`http`)})),ine.and(M({type:k(`sse`)})),ane.and(M({type:k(`acp`)})),one]),jm=M({cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),mcpServers:Rd(Hd(Am),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mm=M({mcpServers:Rd(Hd(Am),()=>[]),cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Nm=M({cwd:F().nullish(),cursor:F().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Pm=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fm=M({sessionId:Wd,cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),mcpServers:G(Hd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Im=M({sessionId:Wd,cwd:F(),additionalDirectories:G(Hd(F()).optional(),()=>[]),mcpServers:G(Hd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lm=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rm=M({sessionId:Wd,modeId:Ep,_meta:G(E(F(),O()).nullish(),()=>void 0)}),zm=_e(I([M({value:D(),type:k(`boolean`)}),M({value:Ap})]),M({sessionId:Wd,configId:Op,_meta:G(E(F(),O()).nullish(),()=>void 0)})),Bm=M({sessionId:Wd,prompt:j($d),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sne=M({uri:F(),name:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cne=M({name:F(),owner:F(),remoteUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vm=M({workspaceUri:G(F().nullish(),()=>void 0),workspaceFolders:j(sne).nullish(),repository:G(cne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),lne=I([k(`automatic`),k(`diagnostic`),k(`manual`)]),une=M({uri:F(),languageId:F(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dne=M({startLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fne=M({uri:F(),excerpts:j(dne),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pne=M({uri:F(),diff:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mne=M({action:F(),uri:F(),position:Jp,timestampMs:N(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hne=M({uri:F(),languageId:F(),visibleRange:G(Yp.nullish(),()=>void 0),lastFocusedMs:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gne=I([k(`error`),k(`warning`),k(`information`),k(`hint`)]),_ne=M({uri:F(),range:Yp,severity:gne,message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vne=M({recentFiles:j(une).nullish(),relatedSnippets:j(fne).nullish(),editHistory:j(pne).nullish(),userActions:j(mne).nullish(),openFiles:j(hne).nullish(),diagnostics:j(_ne).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hm=M({sessionId:Wd,uri:F(),version:N(),position:Jp,selection:Yp.nullish(),triggerKind:lne,context:vne.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Um=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)});M({id:Ud,method:F(),params:I([Cm,wm,Tm,Em,Dm,Om,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Nf,Ff]).nullish()});const yne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),bne=M({content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xne=M({optionId:af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sne=M({outcome:I([M({outcome:k(`cancelled`)}),xne.and(M({outcome:k(`selected`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cne=M({terminalId:ef,_meta:G(E(F(),O()).nullish(),()=>void 0)}),wne=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tne=M({output:F(),truncated:D(),exitStatus:G(wne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ene=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dne=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),One=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),kne=I([F(),N(),N(),D(),j(F())]),Wm=M({content:E(F(),kne).nullish()});I([M({id:Ud,result:I([yne,bne,Sne,Cne,Tne,Ene,Dne,One,Vd(_e(I([Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)}),Bd(M({action:F()}),`action`,[`accept`,`cancel`,`decline`])]),M({_meta:G(E(F(),O()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),M({connectionId:Mf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),im,rm])}),M({id:Ud,error:am})]);const Gm=M({sessionId:Wd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Km=M({sessionId:Wd,uri:F(),languageId:F(),version:N(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ane=M({range:Yp.nullish(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qm=M({sessionId:Wd,uri:F(),version:N(),contentChanges:Rd(Hd(Ane),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jm=M({sessionId:Wd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ym=M({sessionId:Wd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xm=M({sessionId:Wd,uri:F(),version:N(),position:Jp,visibleRange:Yp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zm=M({sessionId:Wd,id:qp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qm=M({sessionId:Wd,id:qp,reason:G(I([k(`rejected`),k(`ignored`),k(`replaced`),k(`cancelled`)]).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)});M({method:F(),params:I([Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,xm,Sm]).nullish()}),M({requestId:Ud,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ef.and(M({mode:k(`form`)})).and(M({message:F()})),Of.and(M({mode:k(`url`)})).and(M({message:F()})),I([pf,mf]).and(M({message:F()})),gf.and(M({type:k(`string`)})),_f.and(M({type:k(`number`)})),vf.and(M({type:k(`integer`)})),yf.and(M({type:k(`boolean`)})),Cf.and(M({type:k(`array`)})),bf.and(M({type:k(`string`)})),Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)});const $m=`$/cancel_request`;function eh(e){return typeof e==`object`&&!!e}function jne(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Mne(e){if(!(!eh(e)||!jne(e.requestId)))return e.requestId}const th={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function nh(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Nne(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Pne(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`&&`issues`in e&&Array.isArray(e.issues)&&`format`in e&&typeof e.format==`function`}function rh(e){if(e instanceof oh)return e.toResult();if(Pne(e))return oh.invalidParams(e.format()).toResult();let t=Nne(e);try{return oh.internalError(t?JSON.parse(t):{}).toResult()}catch{return oh.internalError({details:t}).toResult()}}function Fne(e){return e instanceof oh&&e.code===-32800?e:oh.requestCancelled(e)}function Ine(e,t){let n=Lne(e,t);return n?n.toResult():rh(e)}function Lne(e,t){if(!(!t.aborted||!Rne(e)))return Fne(t.reason)}function Rne(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var zne=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof oh?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?nh(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},ih=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Bne=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ah=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Bne(this);receiveReader;constructor(e,t,n,r){if(typeof e==`function`){let i=e,a=t,o=n;this.initialize(o,[...r?.handlers??[],this.legacyHandler(i,a)]);return}let i=e,a=t,o=n;this.initialize(i,[...o?.handlers??[],...a])}static builder(){return new Vne}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let e of this.retryQueue.splice(0))this.processIncomingMessage(e).catch(e=>this.close(e));return new ih(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return nh(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification($m,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?nh(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return th.yes()}}}async receive(){let e;try{let e=this.stream.readable.getReader();this.receiveReader=e;try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(this.abortController.signal.aborted||n)break;t&&this.receiveMessage(t)}}finally{this.receiveReader===e&&(this.receiveReader=void 0),e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveMessage(e){if(!this.abortController.signal.aborted){if(!eh(e)){console.error(`Invalid message`,{message:e});return}`method`in e?(`id`in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e)).catch(e=>this.close(e))):`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e})}}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let e of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let r=await e.handleMessage(t,this.context)??{handled:!0};if(r.handled)return;t=r.message??t,n||=!!r.retry}n?this.retryQueue.push(t):t.kind===`request`&&await t.responder.respondWithError(oh.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Ine(n,t.responder.signal));else{let t=rh(n);`error`in t&&console.error(`Error handling notification`,e.raw,t.error)}}}toIncomingMessage(e){if(`id`in e){let t=new AbortController;return this.incomingRequests.set(e.id,t),{kind:`request`,method:e.method,params:e.params,raw:e,signal:t.signal,responder:new zne(e.id,t=>this.sendMessage({jsonrpc:`2.0`,id:e.id,...t}),t.signal,()=>{this.incomingRequests.get(e.id)===t&&this.incomingRequests.delete(e.id)})}}return{kind:`notification`,method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),`result`in e)t.resolve(e.result);else if(`error`in e&&eh(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new oh(n,r,i))}else t.reject(oh.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==$m)return;let t=Mne(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(oh.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?nh(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},Vne=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??th.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?th.no(r):await n(t(r.params),r.responder,i)??th.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?th.no(r):await n(t(r.params),i)??th.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new ah(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},oh=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static requestCancelled(t,n){return new e(-32800,`Request cancelled${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}},Hne=class{#e=[];push(e){let t=[],n=0,r=e.indexOf(10,n);for(;r!==-1;)t.push(this.#t(e.subarray(n,r))),n=r+1,r=e.indexOf(10,n);return n<e.byteLength&&this.#e.push(n===0?e:new Uint8Array(e.subarray(n))),t}flush(){if(this.#e.length!==0)return this.#t(new Uint8Array)}#t(e){if(this.#e.length===0)return e;let t=e.byteLength;for(let e of this.#e)t+=e.byteLength;let n=new Uint8Array(t),r=0;for(let e of this.#e)n.set(e,r),r+=e.byteLength;return n.set(e,r),this.#e=[],n}};function Une(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Hne,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);eh(t)?e.enqueue(t):console.warn(`Skipping JSON line that is not an object:`,n)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}},s=t.getReader();a=s;try{for(;;){let{value:e,done:t}=await s.read();if(i)return;if(t)break;if(e){for(let t of n.push(e))if(o(t),i)return}}if(i)return;let e=n.flush();e&&o(e)}catch(t){if(i)return;e.error(t);return}finally{a===s&&(a=void 0),s.releaseLock()}i||e.close()},cancel(e){return i=!0,a?.cancel(e)}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
|
|
5
5
|
`,i=e.getWriter();try{await i.write(n.encode(r))}finally{i.releaseLock()}}})}}function sh(e){return e??{}}function Wne(e){return typeof e==`object`&&!!e&&`readable`in e&&`writable`in e}function Gne(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}const ch={agent:{initialize:Pd.initialize,authenticate:Pd.authenticate,logout:Pd.logout,providers:{list:Pd.providers_list,set:Pd.providers_set,disable:Pd.providers_disable},session:{new:Pd.session_new,load:Pd.session_load,list:Pd.session_list,delete:Pd.session_delete,fork:Pd.session_fork,resume:Pd.session_resume,close:Pd.session_close,setMode:Pd.session_set_mode,setConfigOption:Pd.session_set_config_option,prompt:Pd.session_prompt,cancel:Pd.session_cancel},nes:{start:Pd.nes_start,suggest:Pd.nes_suggest,accept:Pd.nes_accept,reject:Pd.nes_reject,close:Pd.nes_close},document:{didOpen:Pd.document_did_open,didChange:Pd.document_did_change,didClose:Pd.document_did_close,didSave:Pd.document_did_save,didFocus:Pd.document_did_focus}},client:{session:{requestPermission:Fd.session_request_permission,update:Fd.session_update},fs:{writeTextFile:Fd.fs_write_text_file,readTextFile:Fd.fs_read_text_file},terminal:{create:Fd.terminal_create,output:Fd.terminal_output,release:Fd.terminal_release,waitForExit:Fd.terminal_wait_for_exit,kill:Fd.terminal_kill},elicitation:{create:Fd.elicitation_create,complete:Fd.elicitation_complete}},protocol:{cancelRequest:Id.cancel_request}},lh=Symbol(`startActiveSession`);var uh=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,t,n,r){return this.cx.sendRequest(e,t,n,r)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},Kne=class e extends uh{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}request(e,t,n){let r=Mh[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},dh=class e extends uh{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}[lh](e,t){return this.sendRequest(Pd.session_new,e,e=>this.attachSession(e),t)}buildSession(e){return typeof e==`string`?yh.create(this,{cwd:e,mcpServers:[]}):yh.create(this,e)}attachSession(e){let t=new _h,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error(`ACP connection closed`))};n.aborted?r():n.addEventListener(`abort`,r);let i=Rh(this.connectionContext).attach(e,t),a=new ih(()=>{n.removeEventListener(`abort`,r)});return bh.create(this,e,t,[i,a])}request(e,t,n){let r=jh[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},fh=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},ph=class extends fh{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=Kne.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,zh(this,this.connectHandlers))}},mh=class extends fh{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=dh.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,zh(this,this.connectHandlers))}};function hh(e,t=[]){return new ph(e,t)}function gh(e,t=[]){return new mh(e,t)}var _h=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push({kind:`value`,value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:`error`,error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind===`value`)}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind===`error`?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function vh(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}var yh=class e{cx;request;constructor(e,t){this.cx=e,this.request=vh(t)}static create(t,n){return new e(t,n)}toRequest(){return vh(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[lh](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},bh=class e{cx;sessionResponse;updates;registrations;constructor(e,t,n,r){this.cx=e,this.sessionResponse=t,this.updates=n,this.registrations=r}static create(t,n,r,i){return new e(t,n,r,i)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let n=this.cx.request(Pd.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return n.then(e=>{this.updates.enqueue({kind:`stop`,response:e,stopReason:e.stopReason})},e=>{this.updates.reject(e)}),n}nextUpdate(){return this.updates.next()}async readText(){let e=``;for(;;){let t=await this.nextUpdate();if(t.kind===`stop`)return e;let{update:n}=t;n.sessionUpdate===`agent_message_chunk`&&n.content.type===`text`&&(e+=n.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(Error(`Active session disposed`))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e==`string`?[{type:`text`,text:e}]:Array.isArray(e)?e:[e]}};function xh(e,t){return e?typeof e==`function`?e(t):e.parse(t):t}function Sh(e,t,n){return{method:e,params:t,mapResponse:n}}function Ch(e,t){return{method:e,params:t}}function wh(e,t,n,r){e.onReceiveRequest(t.method,e=>xh(t.params,e),async(e,i,a)=>{let o=await r(n(e,a,i.signal,i.id));await i.respond(t.mapResponse?t.mapResponse(o):o)})}function Th(e,t,n,r){e.onReceiveNotification(t.method,e=>xh(t.params,e),(e,t)=>r(n(e,t,t.signal)))}function Eh(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}const Dh={initialize:Sh(Pd.initialize,Cm),newSession:Sh(Pd.session_new,jm),loadSession:Sh(Pd.session_load,Mm,sh),unstable_forkSession:Sh(Pd.session_fork,Fm),listSessions:Sh(Pd.session_list,Nm),deleteSession:Sh(Pd.session_delete,Pm,sh),resumeSession:Sh(Pd.session_resume,Im),closeSession:Sh(Pd.session_close,Lm,sh),setSessionMode:Sh(Pd.session_set_mode,Rm,sh),setSessionConfigOption:Sh(Pd.session_set_config_option,zm),authenticate:Sh(Pd.authenticate,wm,sh),unstable_listProviders:Sh(Pd.providers_list,Tm),unstable_setProvider:Sh(Pd.providers_set,Em,sh),unstable_disableProvider:Sh(Pd.providers_disable,Dm,sh),logout:Sh(Pd.logout,Om,sh),prompt:Sh(Pd.session_prompt,Bm),unstable_startNes:Sh(Pd.nes_start,Vm),unstable_suggestNes:Sh(Pd.nes_suggest,Hm),unstable_closeNes:Sh(Pd.nes_close,Um,sh)},Oh={cancel:Ch(Pd.session_cancel,Gm),unstable_didOpenDocument:Ch(Pd.document_did_open,Km),unstable_didChangeDocument:Ch(Pd.document_did_change,qm),unstable_didCloseDocument:Ch(Pd.document_did_close,Jm),unstable_didSaveDocument:Ch(Pd.document_did_save,Ym),unstable_didFocusDocument:Ch(Pd.document_did_focus,Xm),unstable_acceptNes:Ch(Pd.nes_accept,Zm),unstable_rejectNes:Ch(Pd.nes_reject,Qm)},kh={requestPermission:Sh(Fd.session_request_permission,of),writeTextFile:Sh(Fd.fs_write_text_file,Gd,sh),readTextFile:Sh(Fd.fs_read_text_file,Kd),createTerminal:Sh(Fd.terminal_create,cf),terminalOutput:Sh(Fd.terminal_output,lf),releaseTerminal:Sh(Fd.terminal_release,uf,sh),waitForTerminalExit:Sh(Fd.terminal_wait_for_exit,df),killTerminal:Sh(Fd.terminal_kill,ff,sh),unstable_createElicitation:Sh(Fd.elicitation_create,kf)},Ah={sessionUpdate:Ch(Fd.session_update,ym),unstable_completeElicitation:Ch(Fd.elicitation_complete,bm)},jh=Eh(Dh);Eh(Oh);const Mh=Eh(kh),Nh=Eh(Ah);function Ph(e,t,n,r){return{params:e,requestId:r,signal:n,agent:t}}function Fh(e,t,n){return{params:e,signal:n,agent:t}}var Ih=class{activeSessions=new Map;handleMessage(e){if(e.kind!==`notification`||e.method!==Fd.session_update)return th.no(e);let t=ym.parse(e.params),n={kind:`session_update`,notification:t,update:t.update},r=this.activeSessions.get(t.sessionId);if(r&&r.size>0)for(let e of r)e.enqueue(n);return th.no(e)}attach(e,t){let n=this.activeSessions.get(e.sessionId)??new Set;return n.add(t),this.activeSessions.set(e.sessionId,n),new ih(()=>{n.delete(t),n.size===0&&this.activeSessions.delete(e.sessionId)})}};const Lh=new WeakMap;function Rh(e){let t=Lh.get(e);return t||(t=new Ih,Lh.set(e,t)),t}function zh(e,t){for(let n of t){let t;try{t=n(e)}catch(t){throw e.close(t),t}Promise.resolve(t).catch(t=>{e.close(t)})}}const Bh=Symbol(`appBuilder`),Vh=Symbol(`runAgentConnectHandlers`),Hh=Symbol(`runClientConnectHandlers`);function Uh(e){return new Wh(e)}var Wh=class{builder=ah.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(e,t)=>Rh(t).handleMessage(e),describe:()=>`client-session-update-router`})}[Bh](){return this.builder}[Hh](e){zh(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:n,connection:r}=this.connectConnection(e);return n.runUntil(()=>t(r.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,n){if(n)return this.request({method:e,params:t},n);let r=Mh[e];if(!r)throw Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(r,t)}onNotification(e,t,n){if(n)return this.notification({method:e,params:t},n);let r=Nh[e];if(!r)throw Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(r,t)}request(e,t){return wh(this.builder,e,(e,t,n,r)=>Ph(e,dh.create(t,r),n,r),t),this}notification(e,t){return Th(this.builder,e,(e,t,n)=>Fh(e,dh.create(t),n),t),this}connectConnection(e){if(Wne(e)){let t=this.openStreamConnection(e);return this[Hh](t.connection),t}let[t,n]=Gne(),r=e[Bh]().connect(n),i=hh(r),a=this.openStreamConnection(t);a.rawConnection.closed.then(()=>i.close()),r.closed.then(()=>a.connection.close());try{e[Vh](i),this[Hh](a.connection)}catch(e){throw i.close(e),a.connection.close(e),e}return a}openStreamConnection(e){let t=this.builder.connect(e);return{rawConnection:t,connection:gh(t,this.connectHandlers)}}};new Set([Pd.initialize,Pd.authenticate,Pd.providers_list,Pd.providers_set,Pd.providers_disable,Pd.session_new,Pd.session_load,Pd.session_set_mode,Pd.session_set_config_option,Pd.session_prompt,Pd.session_list,Pd.session_delete,Pd.session_fork,Pd.session_resume,Pd.session_close,Pd.logout,Pd.nes_start,Pd.nes_suggest,Pd.nes_close]),new Set([Pd.session_cancel,Pd.nes_accept,Pd.nes_reject,Pd.document_did_open,Pd.document_did_change,Pd.document_did_close,Pd.document_did_save,Pd.document_did_focus]),new Set([Fd.session_request_permission,Fd.fs_write_text_file,Fd.fs_read_text_file,Fd.terminal_create,Fd.terminal_output,Fd.terminal_release,Fd.terminal_wait_for_exit,Fd.terminal_kill,Fd.elicitation_create]),new Set([Fd.session_update,Fd.elicitation_complete]);function Gh(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const Kh=/^[a-zA-Z0-9_-]+$/,qh=64;function Jh(e){return typeof e!=`string`||e.length===0||e.length>64||!Kh.test(e)?null:e}function Yh(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function Xh(e){return!e.startsWith(`principal-`)}function Zh(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function Qh(e){let t=Jh(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:Yh(t),displayName:typeof e.agentName==`string`?Gh(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?Gh(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?Gh(e.clientVersion):void 0,label:typeof e.label==`string`?Gh(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}const $h=()=>new Map,eg=e=>{let t=$h();return e.forEach((e,n)=>{t.set(n,e)}),t},tg=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},ng=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},rg=()=>new Set,ig=e=>e[e.length-1],ag=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},og=Array.from,sg=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},cg=Array.isArray;var lg=class{constructor(){this._observers=$h()}on(e,t){return tg(this._observers,e,rg).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return og((this._observers.get(e)||$h()).values()).forEach(e=>e(...t))}destroy(){this._observers=$h()}};const ug=Math.floor,dg=Math.abs,fg=(e,t)=>e<t?e:t,pg=(e,t)=>e>t?e:t;Number.isNaN;const mg=e=>e===0?1/e<0:e<0,hg=2**53-1,gg=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&ug(e)===e);Number.isNaN,Number.parseInt;const _g=String.fromCharCode;String.fromCodePoint,_g(65535);const vg=e=>e.toLowerCase(),yg=/^\s*/g,bg=e=>e.replace(yg,``),xg=/([A-Z])/g,Sg=(e,t)=>bg(e.replace(xg,e=>`${t}${vg(e)}`)),Cg=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},wg=typeof TextEncoder<`u`?new TextEncoder:null,Tg=wg?e=>wg.encode(e):Cg;let Eg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Eg&&Eg.decode(new Uint8Array).length===1&&(Eg=null);var Dg=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Og=()=>new Dg,kg=e=>{let t=Og();return e(t),jg(t)},Ag=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},jg=e=>{let t=new Uint8Array(Ag(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Mg=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(pg(n,t)*2),e.cpos=0)},Ng=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Pg=Ng,Fg=(e,t)=>{for(;t>127;)Ng(e,128|127&t),t=ug(t/128);Ng(e,127&t)},Ig=(e,t)=>{let n=mg(t);for(n&&(t=-t),Ng(e,(t>63?128:0)|(n?64:0)|63&t),t=ug(t/64);t>0;)Ng(e,(t>127?128:0)|127&t),t=ug(t/128)},Lg=new Uint8Array(3e4),Rg=Lg.length/3,zg=wg&&wg.encodeInto?(e,t)=>{if(t.length<Rg){let n=wg.encodeInto(t,Lg).written||0;Fg(e,n);for(let t=0;t<n;t++)Ng(e,Lg[t])}else Vg(e,Tg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Fg(e,r);for(let t=0;t<r;t++)Ng(e,n.codePointAt(t))},Bg=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=fg(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(pg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Vg=(e,t)=>{Fg(e,t.byteLength),Bg(e,t)},Hg=(e,t)=>{Mg(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Ug=(e,t)=>Hg(e,4).setFloat32(0,t,!1),Wg=(e,t)=>Hg(e,8).setFloat64(0,t,!1),Gg=(e,t)=>Hg(e,8).setBigInt64(0,t,!1),Kg=new DataView(new ArrayBuffer(4)),qg=e=>(Kg.setFloat32(0,e),Kg.getFloat32(0)===e),Jg=(e,t)=>{switch(typeof t){case`string`:Ng(e,119),zg(e,t);break;case`number`:gg(t)&&dg(t)<=2147483647?(Ng(e,125),Ig(e,t)):qg(t)?(Ng(e,124),Ug(e,t)):(Ng(e,123),Wg(e,t));break;case`bigint`:Ng(e,122),Gg(e,t);break;case`object`:if(t===null)Ng(e,126);else if(cg(t)){Ng(e,117),Fg(e,t.length);for(let n=0;n<t.length;n++)Jg(e,t[n])}else if(t instanceof Uint8Array)Ng(e,116),Vg(e,t);else{Ng(e,118);let n=Object.keys(t);Fg(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];zg(e,i),Jg(e,t[i])}}break;case`boolean`:Ng(e,t?120:121);break;default:Ng(e,127)}};var Yg=class extends Dg{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Fg(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const Xg=e=>{e.count>0&&(Ig(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Fg(e.encoder,e.count-2))};var Zg=class{constructor(){this.encoder=new Dg,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Xg(this),this.count=1,this.s=e)}toUint8Array(){return Xg(this),jg(this.encoder)}};const Qg=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Ig(e.encoder,t),e.count>1&&Fg(e.encoder,e.count-2)}};var $g=class{constructor(){this.encoder=new Dg,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Qg(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Qg(this),jg(this.encoder)}},e_=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Zg}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Dg;return this.sarr.push(this.s),this.s=``,zg(e,this.sarr.join(``)),Bg(e,this.lensE.toUint8Array()),jg(e)}};const t_=e=>Error(e),n_=()=>{throw t_(`Method unimplemented`)},r_=()=>{throw t_(`Unexpected case`)},i_=t_(`Unexpected end of array`),a_=t_(`Integer out of Range`);var o_=class{constructor(e){this.arr=e,this.pos=0}};const s_=e=>new o_(e),c_=e=>e.pos!==e.arr.length,l_=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},u_=e=>l_(e,f_(e)),d_=e=>e.arr[e.pos++],f_=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>hg)throw a_}throw i_},p_=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>hg)throw a_}throw i_},m_=Eg?e=>Eg.decode(u_(e)):e=>{let t=f_(e);if(t===0)return``;{let n=String.fromCodePoint(d_(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(d_(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},h_=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},g_=[e=>void 0,e=>null,p_,e=>h_(e,4).getFloat32(0,!1),e=>h_(e,8).getFloat64(0,!1),e=>h_(e,8).getBigInt64(0,!1),e=>!1,e=>!0,m_,e=>{let t=f_(e),n={};for(let r=0;r<t;r++){let t=m_(e);n[t]=__(e)}return n},e=>{let t=f_(e),n=[];for(let r=0;r<t;r++)n.push(__(e));return n},u_],__=e=>g_[127-d_(e)](e);var v_=class extends o_{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),c_(this)?this.count=f_(this)+1:this.count=-1),this.count--,this.s}},y_=class extends o_{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=p_(this);let e=mg(this.s);this.count=1,e&&(this.s=-this.s,this.count=f_(this)+2)}return this.count--,this.s}},b_=class extends o_{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=p_(this),t=e&1;this.diff=ug(e/2),this.count=1,t&&(this.count=f_(this)+2)}return this.s+=this.diff,this.count--,this.s}},x_=class{constructor(e){this.decoder=new y_(e),this.str=m_(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};wu.subtle;const S_=wu.getRandomValues.bind(wu),C_=()=>S_(new Uint32Array(1))[0],w_=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^C_()&15>>e/4).toString(16)),T_=Date.now,E_=e=>new Promise(e);Promise.all.bind(Promise);const D_=e=>e===void 0?null:e;let O_=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};try{typeof localStorage<`u`&&localStorage&&(O_=localStorage)}catch{}const k_=O_,A_=Symbol(`Equality`),j_=(e,t)=>e===t||!!e?.[A_]?.(t)||!1,M_=Object.assign,N_=Object.keys,P_=(e,t)=>{for(let n in e)t(e[n],n)},F_=e=>N_(e).length,I_=e=>{for(let t in e)return!1;return!0},L_=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},R_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),z_=(e,t)=>e===t||F_(e)===F_(t)&&L_(e,(e,n)=>(e!==void 0||R_(t,n))&&j_(t[n],e)),B_=Object.freeze,V_=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&V_(e[t])}return B_(e)},H_=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&H_(e,t,n+1)}},U_=e=>e,W_=(e,t)=>t.includes(e),G_=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,K_=typeof window<`u`&&typeof document<`u`&&!G_;typeof navigator<`u`&&/Mac/.test(navigator.platform);let q_;const J_=[],Y_=()=>{if(q_===void 0)if(G_){q_=$h();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&q_.set(t,``),t=r):t===null?J_.push(r):(q_.set(t,r),t=null)}t!==null&&q_.set(t,``)}else typeof location==`object`?(q_=$h(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);q_.set(`--${Sg(t,`-`)}`,n),q_.set(`-${Sg(t,`-`)}`,n)}})):q_=$h();return q_},X_=e=>Y_().has(e),Z_=e=>D_(G_?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:k_.getItem(e)),Q_=e=>X_(`--`+e)||Z_(e)!==null;Q_(`production`);const $_=G_&&W_(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!X_(`--no-colors`)&&!Q_(`no-color`)&&(!G_||process.stdout.isTTY)&&(!G_||X_(`--color`)||Z_(`COLORTERM`)!==null||(Z_(`TERM`)||``).includes(`color`)),ev=e=>new Uint8Array(e),tv=K_?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=_g(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),nv=e=>{let t=ev(e.byteLength);return t.set(e),t},rv=e=>kg(t=>Jg(t,e)),iv=Symbol,av=iv(),ov=iv(),sv=iv(),cv=iv(),lv=iv(),uv=iv(),dv=iv(),fv=iv(),pv=iv(),mv=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};T_();const hv={[av]:`\x1B[1m`,[ov]:`\x1B[2m`,[sv]:`\x1B[34m`,[lv]:`\x1B[32m`,[cv]:`\x1B[37m`,[uv]:`\x1B[31m`,[dv]:`\x1B[35m`,[fv]:`\x1B[38;5;208m`,[pv]:`\x1B[0m`},gv=$_?e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r],i=hv[n];if(i!==void 0)t.push(i);else if(n===void 0)break;else if(n.constructor===String||n.constructor===Number)t.push(n);else break}for(r>0&&(t.push(`\x1B[0m`),n.push(t.join(``)));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n}:mv,_v=(...e)=>{console.log(...gv(e))},vv=(...e)=>{console.warn(...gv(e))},yv=e=>({[Symbol.iterator](){return this},next:e}),bv=(e,t)=>yv(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),xv=(e,t)=>yv(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var Sv=class{constructor(e,t){this.clock=e,this.len=t}},Cv=class{constructor(){this.clients=new Map}};const wv=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])Iy(e,i,o.clock,o.len,n)}}),Tv=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=ug((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},Ev=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&Tv(n,t.clock)!==null},Dv=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new Sv(r.clock,pg(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},Ov=e=>{let t=new Cv;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)ag(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return Dv(t),t},kv=(e,t,n,r)=>{tg(e.clients,t,()=>[]).push(new Sv(n,r))},Av=()=>new Cv,jv=e=>{let t=Av();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new Sv(i,a))}}r.length>0&&t.clients.set(n,r)}),t},Mv=(e,t)=>{Fg(e.restEncoder,t.clients.size),og(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Fg(e.restEncoder,t);let r=n.length;Fg(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},Nv=e=>{let t=new Cv,n=f_(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=f_(e.restDecoder),r=f_(e.restDecoder);if(r>0){let i=tg(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new Sv(e.readDsClock(),e.readDsLen()))}}return t},Pv=(e,t,n)=>{let r=new Cv,i=f_(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=f_(e.restDecoder),a=f_(e.restDecoder),o=n.clients.get(i)||[],s=Oy(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&kv(r,i,s,a-s);let e=Ay(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,bx(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,bx(t,c,a-c.id.clock)),c.delete(t))}else kv(r,i,n,a-n)}}if(r.clients.size>0){let e=new Gv;return Fg(e.restEncoder,0),Mv(e,r),e.toUint8Array()}return null},Fv=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[n,r]of e.clients.entries()){let e=t.clients.get(n);if(e===void 0||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},Iv=C_;var Lv=class e extends lg{constructor({guid:e=w_(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Iv(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Ey,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=E_(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>E_(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&Wy(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(og(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Wy(this,e,t)}get(e,t=yb){let n=tg(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==yb&&r!==t)if(r===yb){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=``){return this.get(e,Bb)}getText(e=``){return this.get(e,rx)}getMap(e=``){return this.get(e,Ub)}getXmlElement(e=``){return this.get(e,ox)}getXmlFragment(e=``){return this.get(e,ax)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,og(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Wy(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},Rv=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return f_(this.restDecoder)}readDsLen(){return f_(this.restDecoder)}},zv=class extends Rv{readLeftID(){return gy(f_(this.restDecoder),f_(this.restDecoder))}readRightID(){return gy(f_(this.restDecoder),f_(this.restDecoder))}readClient(){return f_(this.restDecoder)}readInfo(){return d_(this.restDecoder)}readString(){return m_(this.restDecoder)}readParentInfo(){return f_(this.restDecoder)===1}readTypeRef(){return f_(this.restDecoder)}readLen(){return f_(this.restDecoder)}readAny(){return __(this.restDecoder)}readBuf(){return nv(u_(this.restDecoder))}readJSON(){return JSON.parse(m_(this.restDecoder))}readKey(){return m_(this.restDecoder)}},Bv=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=f_(this.restDecoder),this.dsCurrVal}readDsLen(){let e=f_(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Vv=class extends Bv{constructor(e){super(e),this.keys=[],f_(e),this.keyClockDecoder=new b_(u_(e)),this.clientDecoder=new y_(u_(e)),this.leftClockDecoder=new b_(u_(e)),this.rightClockDecoder=new b_(u_(e)),this.infoDecoder=new v_(u_(e),d_),this.stringDecoder=new x_(u_(e)),this.parentInfoDecoder=new v_(u_(e),d_),this.typeRefDecoder=new y_(u_(e)),this.lenDecoder=new y_(u_(e))}readLeftID(){return new my(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new my(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return __(this.restDecoder)}readBuf(){return u_(this.restDecoder)}readJSON(){return __(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},Hv=class{constructor(){this.restEncoder=Og()}toUint8Array(){return jg(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Fg(this.restEncoder,e)}writeDsLen(e){Fg(this.restEncoder,e)}},Uv=class extends Hv{writeLeftID(e){Fg(this.restEncoder,e.client),Fg(this.restEncoder,e.clock)}writeRightID(e){Fg(this.restEncoder,e.client),Fg(this.restEncoder,e.clock)}writeClient(e){Fg(this.restEncoder,e)}writeInfo(e){Pg(this.restEncoder,e)}writeString(e){zg(this.restEncoder,e)}writeParentInfo(e){Fg(this.restEncoder,+!!e)}writeTypeRef(e){Fg(this.restEncoder,e)}writeLen(e){Fg(this.restEncoder,e)}writeAny(e){Jg(this.restEncoder,e)}writeBuf(e){Vg(this.restEncoder,e)}writeJSON(e){zg(this.restEncoder,JSON.stringify(e))}writeKey(e){zg(this.restEncoder,e)}},Wv=class{constructor(){this.restEncoder=Og(),this.dsCurrVal=0}toUint8Array(){return jg(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Fg(this.restEncoder,t)}writeDsLen(e){e===0&&r_(),Fg(this.restEncoder,e-1),this.dsCurrVal+=e}},Gv=class extends Wv{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new $g,this.clientEncoder=new Zg,this.leftClockEncoder=new $g,this.rightClockEncoder=new $g,this.infoEncoder=new Yg(Pg),this.stringEncoder=new e_,this.parentInfoEncoder=new Yg(Pg),this.typeRefEncoder=new Zg,this.lenEncoder=new Zg}toUint8Array(){let e=Og();return Fg(e,0),Vg(e,this.keyClockEncoder.toUint8Array()),Vg(e,this.clientEncoder.toUint8Array()),Vg(e,this.leftClockEncoder.toUint8Array()),Vg(e,this.rightClockEncoder.toUint8Array()),Vg(e,jg(this.infoEncoder)),Vg(e,this.stringEncoder.toUint8Array()),Vg(e,jg(this.parentInfoEncoder)),Vg(e,this.typeRefEncoder.toUint8Array()),Vg(e,this.lenEncoder.toUint8Array()),Bg(e,jg(this.restEncoder)),jg(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(+!!e)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Jg(this.restEncoder,e)}writeBuf(e){Vg(this.restEncoder,e)}writeJSON(e){Jg(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const Kv=(e,t,n,r)=>{r=pg(r,t[0].id.clock);let i=Ay(t,r);Fg(e.restEncoder,t.length-i),e.writeClient(n),Fg(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},qv=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{Oy(t,n)>e&&r.set(n,e)}),Dy(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Fg(e.restEncoder,r.size),og(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Kv(e,t.clients.get(n),n,r)})},Jv=(e,t)=>{let n=$h(),r=f_(e.restDecoder);for(let i=0;i<r;i++){let r=f_(e.restDecoder),i=Array(r),a=e.readClient(),o=f_(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new lx(gy(a,o),t),o+=t;break}case 10:{let t=f_(e.restDecoder);i[n]=new Tx(gy(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new Cx(gy(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,wx(e,r));i[n]=c,o+=c.length}}}}return n},Yv=(e,t,n)=>{let r=[],i=og(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new Ey,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Tx){let i=tg(d,u.id.client,()=>Oy(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,Oy(t,a)),f();else{u=e.refs[e.i++];continue}}else (i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new Gv;return qv(e,s,new Map),Fg(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},Xv=(e,t)=>qv(e,t.doc.store,t.beforeState),Zv=(e,t,n,r=new Vv(e))=>Wy(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Yv(e,i,Jv(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<Oy(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=eb([o.update,a.update])}}else i.pendingStructs=a;let s=Pv(r,e,i);if(i.pendingDs){let t=new Vv(s_(i.pendingDs));f_(t.restDecoder);let n=Pv(t,e,i);s&&n?i.pendingDs=eb([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,Qv(e.doc,t)}},n,!1),Qv=(e,t,n,r=Vv)=>{let i=s_(t);Zv(i,e,n,new r(i))},$v=(e,t,n)=>Qv(e,t,n,zv),ey=(e,t,n=new Map)=>{qv(e,t.store,n),Mv(e,jv(t.store))},ty=(e,t=new Uint8Array([0]),n=new Gv)=>{ey(n,e,iy(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(tb(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Uv)return Qy(r.map((e,t)=>t===0?e:ob(e)));if(n.constructor===Gv)return eb(r)}return r[0]},ny=(e,t)=>ty(e,t,new Uv),ry=e=>{let t=new Map,n=f_(e.restDecoder);for(let r=0;r<n;r++){let n=f_(e.restDecoder),r=f_(e.restDecoder);t.set(n,r)}return t},iy=e=>ry(new Rv(s_(e))),ay=(e,t)=>(Fg(e.restEncoder,t.size),og(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Fg(e.restEncoder,t),Fg(e.restEncoder,n)}),e),oy=(e,t)=>ay(e,Dy(t.store)),sy=(e,t=new Wv)=>(e instanceof Map?ay(t,e):oy(t,e),t.toUint8Array()),cy=e=>sy(e,new Hv);var ly=class{constructor(){this.l=[]}};const uy=()=>new ly,dy=(e,t)=>e.l.push(t),fy=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},py=(e,t,n)=>H_(e.l,[t,n]);var my=class{constructor(e,t){this.client=e,this.clock=t}};const hy=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,gy=(e,t)=>new my(e,t),_y=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw r_()},vy=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var yy=class{constructor(e,t){this.ds=e,this.sv=t}};const by=(e,t)=>new yy(e,t);by(Av(),new Map);const xy=e=>by(jv(e.store),Dy(e.store)),Sy=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Ev(t.ds,e.id),Cy=(e,t)=>{let n=tg(e.meta,Cy,rg),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Oy(r,n)&&Ny(e,gy(n,t))}),wv(e,t.ds,e=>{}),n.add(t))},wy=(e,t,n=Vv)=>{let r=new n(s_(t)),i=new Xy(r,!1);for(let t=i.curr;t!==null;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let a=Ov([e.ds,Nv(r)]);return Fv(e.ds,a)},Ty=(e,t)=>wy(e,t,zv);var Ey=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const Dy=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},Oy=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},ky=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw r_()}n.push(t)},Ay=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=ug(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=ug((n+r)/2)}throw r_()},jy=(e,t)=>{let n=e.clients.get(t.client);return n[Ay(n,t.clock)]},My=(e,t,n)=>{let r=Ay(t,n),i=t[r];return i.id.clock<n&&i instanceof Cx?(t.splice(r+1,0,bx(e,i,n-i.id.clock)),r+1):r},Ny=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[My(e,n,t.clock)]},Py=(e,t,n)=>{let r=t.clients.get(n.client),i=Ay(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==lx&&r.splice(i+1,0,bx(e,a,n.clock-a.id.clock+1)),a},Fy=(e,t,n)=>{let r=e.clients.get(t.id.client);r[Ay(r,t.id.clock)]=n},Iy=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=My(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&My(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Ly=class{constructor(e,t,n){this.doc=e,this.deleteSet=new Cv,this.beforeState=Dy(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const Ry=(e,t)=>t.deleteSet.clients.size===0&&!ng(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(Dv(t.deleteSet),Xv(e,t),Mv(e,t.deleteSet),!0),zy=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&tg(e.changed,t,rg).add(n)},By=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Cx&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},Vy=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=Ay(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof Cx&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Hy=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=fg(r.length-1,1+Ay(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+By(r,e)}})},Uy=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{Dv(a),n.afterState=Dy(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{py(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Yne(n)})}),H_(e,[])}finally{r.gc&&Vy(a,i,r.gcFilter),Hy(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=pg(Ay(e,r),1);for(let t=e.length-1;t>=n;)t-=1+By(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=Ay(r,n);a+1<r.length&&By(r,a+1)>1||a>0&&By(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(_v(fv,av,`[yjs] `,ov,uv,`Changed the client-id because another client seems to be using it.`),r.clientID=Iv()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Uv;Ry(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Gv;Ry(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):Uy(e,t+1)}}},Wy=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Ly(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&Uy(i,0)}}return o};var Gy=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const Ky=(e,t,n)=>{wv(e,n.deletions,n=>{n instanceof Cx&&t.scope.some(t=>t===e.doc||vy(t,n))&&yx(n,!1)})},qy=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;Wy(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;wv(n,o.insertions,e=>{if(e instanceof Cx){if(e.redone!==null){let{item:t,diff:i}=Cre(r,e.id);i>0&&(t=Ny(n,gy(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||vy(t,e))&&c.push(e)}}),wv(n,o.deletions,e=>{e instanceof Cx&&a.some(t=>t===n.doc||vy(t,e))&&!Ev(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=Sx(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o};var Jy=class extends lg{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=cg(e)?e[0].doc:e instanceof Lv?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new Cv;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&kv(i,n,r,a)});let a=T_(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=Ov([t.deletions,e.deleteSet]),t.insertions=Ov([t.insertions,i])}else r.push(new Gy(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),wv(e,e.deleteSet,t=>{t instanceof Cx&&this.scope.some(n=>n===e.doc||vy(n,t))&&yx(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=cg(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof yb?e.doc!==this.doc:e!==this.doc)&&vv(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>Ky(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>Ky(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=qy(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=qy(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*Yy(e){let t=f_(e.restDecoder);for(let n=0;n<t;n++){let t=f_(e.restDecoder),n=e.readClient(),r=f_(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=f_(e.restDecoder);yield new Tx(gy(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new Cx(gy(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,wx(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new lx(gy(n,r),t),r+=t}}}}var Xy=class{constructor(e,t){this.gen=Yy(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Tx);return this.curr}},Zy=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Qy=e=>eb(e,zv,Uv),$y=(e,t)=>{if(e.constructor===lx){let{client:n,clock:r}=e.id;return new lx(gy(n,r+t),e.length-t)}else if(e.constructor===Tx){let{client:n,clock:r}=e.id;return new Tx(gy(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new Cx(gy(r,i+t),null,gy(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},eb=(e,t=Vv,n=Gv)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(s_(e))),i=r.map(e=>new Xy(e,!0)),a=null,o=new n,s=new Zy(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Tx?1:-1:n}else return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)rb(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock)if(a.struct.constructor===Tx)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{rb(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Tx(gy(t,a.struct.id.clock+a.struct.length),e),offset:0}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===Tx?a.struct.length-=t:n=$y(n,t)),a.struct.mergeWith(n)||(rb(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==Tx;n=e.next())rb(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(rb(s,a.struct,a.offset),a=null),ib(s),Mv(o,Ov(r.map(e=>Nv(e)))),o.toUint8Array()},tb=(e,t,n=Vv,r=Gv)=>{let i=iy(t),a=new r,o=new Zy(a),s=new n(s_(e)),c=new Xy(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Tx){c.next();continue}if(e.id.clock+e.length>n)for(rb(o,e,pg(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)rb(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return ib(o),Mv(a,Nv(s)),a.toUint8Array()},nb=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:jg(e.encoder.restEncoder)}),e.encoder.restEncoder=Og(),e.written=0)},rb=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&nb(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Fg(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ib=e=>{nb(e);let t=e.encoder.restEncoder;Fg(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Fg(t,r.written),Bg(t,r.restEncoder)}},ab=(e,t,n,r)=>{let i=new n(s_(e)),a=new Xy(i,!1),o=new r,s=new Zy(o);for(let e=a.curr;e!==null;e=a.next())rb(s,t(e),0);return ib(s),Mv(o,Nv(i)),o.toUint8Array()},ob=e=>ab(e,U_,Vv,Uv),sb=`You must not compute changes after the event-handler fired.`;var cb=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=lb(this.currentTarget,this.target)}deletes(e){return Ev(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw t_(sb);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r))if(e!==null&&this.deletes(e))i=`delete`,a=ig(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=ig(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=ig(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw t_(sb);let t=this.target,n=rg(),r=rg(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}};const lb=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},ub=()=>{vv(`Invalid access: Add Yjs type to a document before reading data.`)};let db=0;var fb=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=db++}};const pb=e=>{e.timestamp=db++},mb=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=db++},hb=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return mb(r,t,n),r}else{let r=new fb(t,n);return e.push(r),r}},gb=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>dg(t-e.index)<dg(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,pb(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&dg(n.index-i)<r.parent.length/80?(mb(n,r,i),n):hb(e._searchMarker,r,i)},_b=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=pg(t,i.index+n))}},vb=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;tg(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;py(r._eH,n,t)};var yb=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=uy(),this._dEH=uy(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw n_()}clone(){throw n_()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){dy(this._eH,e)}observeDeep(e){dy(this._dEH,e)}unobserve(e){fy(this._eH,e)}unobserveDeep(e){fy(this._dEH,e)}toJSON(){}};const bb=(e,t,n)=>{e.doc??ub(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},xb=e=>{e.doc??ub();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Sb=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&Sy(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},Cb=(e,t)=>{let n=0,r=e._start;for(e.doc??ub();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},wb=(e,t)=>{let n=[];return Cb(e,(r,i)=>{n.push(t(r,i,e))}),n},Tb=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},Eb=(e,t)=>{e.doc??ub();let n=gb(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Db=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new Cx(gy(o,Oy(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new gx(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new Cx(gy(o,Oy(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ux(new Uint8Array(n))),i.integrate(e,0);break;case Lv:i=new Cx(gy(o,Oy(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new px(n)),i.integrate(e,0);break;default:if(n instanceof yb)i=new Cx(gy(o,Oy(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new vx(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},Ob=()=>t_(`Length exceeded!`),kb=(e,t,n,r)=>{if(n>t._length)throw Ob();if(n===0)return t._searchMarker&&_b(t._searchMarker,n,r.length),Db(e,t,null,r);let i=n,a=gb(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Ny(e,gy(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&_b(t._searchMarker,i,r.length),Db(e,t,o,r)},Ab=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Db(e,t,r,n)},jb=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=gb(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&Ny(e,gy(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Ny(e,gy(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw Ob();t._searchMarker&&_b(t._searchMarker,i,-a+r)},Mb=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Nb=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new gx([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new gx([r]);break;case Uint8Array:s=new ux(r);break;case Lv:s=new px(r);break;default:if(r instanceof yb)s=new vx(r);else throw Error(`Unexpected content type`)}new Cx(gy(o,Oy(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},Pb=(e,t)=>{e.doc??ub();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Fb=e=>{let t={};return e.doc??ub(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Ib=(e,t)=>{e.doc??ub();let n=e._map.get(t);return n!==void 0&&!n.deleted},Lb=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Sy(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Rb=e=>(e.doc??ub(),bv(e._map.entries(),e=>!e[1].deleted));var zb=class extends cb{},Bb=class e extends yb{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof yb?e.clone():e)),t}get length(){return this.doc??ub(),this._length}_callObserver(e,t){super._callObserver(e,t),vb(this,e,new zb(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Wy(this.doc,n=>{kb(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):Wy(this.doc,t=>{Ab(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Wy(this.doc,n=>{jb(n,this,e,t)})}get(e){return Eb(this,e)}toArray(){return xb(this)}slice(e=0,t=this.length){return bb(this,e,t)}toJSON(){return this.map(e=>e instanceof yb?e.toJSON():e)}map(e){return wb(this,e)}forEach(e){Cb(this,e)}[Symbol.iterator](){return Tb(this)}_write(e){e.writeTypeRef(hre)}};const Vb=e=>new Bb;var Hb=class extends cb{constructor(e,t,n){super(e,t),this.keysChanged=n}},Ub=class e extends yb{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof yb?e.clone():e)}),t}_callObserver(e,t){vb(this,e,new Hb(this,e,t))}toJSON(){this.doc??ub();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof yb?r.toJSON():r}}),e}get size(){return[...Rb(this)].length}keys(){return xv(Rb(this),e=>e[0])}values(){return xv(Rb(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return xv(Rb(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??ub(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):Wy(this.doc,t=>{Mb(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):Wy(this.doc,n=>{Nb(n,this,e,t)}),t}get(e){return Pb(this,e)}has(e){return Ib(this,e)}clear(){this.doc===null?this._prelimContent.clear():Wy(this.doc,e=>{this.forEach(function(t,n,r){Mb(e,r,n)})})}_write(e){e.writeTypeRef(gre)}};const Wb=e=>new Ub,Gb=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&z_(e,t);var Kb=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&r_(),this.right.content.constructor){case hx:this.right.deleted||Xb(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const qb=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case hx:t.right.deleted||Xb(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Ny(e,gy(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},Jb=(e,t,n,r)=>{let i=new Map,a=r?gb(t,n):null;return a?qb(e,new Kb(a.p.left,a.p,a.index,i),n-a.index):qb(e,new Kb(null,t._start,0,i),n)},Yb=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===hx&&Gb(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new Cx(gy(a,Oy(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new hx(o,r));l.integrate(e,0),n.right=l,n.forward()})},Xb=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Zb=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===hx&&Gb(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Qb=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!Gb(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new Cx(gy(a,Oy(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new hx(s,c)),n.right.integrate(e,0),n.forward()}}return o},$b=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;Zb(n,i);let s=Qb(e,t,n,i),c=r.constructor===String?new _x(r):r instanceof yb?new vx(r):new mx(r),{left:l,right:u,index:d}=n;t._searchMarker&&_b(t._searchMarker,n.index,c.getLength()),u=new Cx(gy(o,Oy(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Yb(e,t,n,s)},ex=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;Zb(n,i);let s=Qb(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===hx));){if(!n.right.deleted)switch(n.right.content.constructor){case hx:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Gb(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&Ny(e,gy(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
|
|
6
6
|
`;n.right=new Cx(gy(o,Oy(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new _x(i)),n.right.integrate(e,0),n.forward()}Yb(e,t,n,s)},tx=(e,t,n,r,i)=>{let a=t,o=$h();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===hx){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case hx:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Xb(i,n);break}}}t=t.right}return s},qne=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===hx){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Jne=e=>{let t=0;return Wy(e.doc,n=>{let r=e._start,i=e._start,a=$h(),o=eg(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case hx:Xb(o,i.content);break;default:t+=tx(n,r,i,a,o),a=eg(o),r=i;break}i=i.right}}),t},Yne=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Iy(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===hx&&e.constructor!==lx&&t.add(e.parent)})}Wy(n,n=>{wv(e,e.deleteSet,e=>{if(e instanceof lx||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===hx?t.add(r):qne(n,e)});for(let e of t)Jne(e)})},nx=(e,t,n)=>{let r=n,i=eg(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case vx:case mx:case _x:n<t.right.length&&Ny(e,gy(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&tx(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&_b(o._searchMarker,t.index,-r+n),t};var Xne=class extends cb{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];Wy(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},I_(o)||(e.attributes=M_({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case vx:case mx:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case _x:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case hx:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Gb(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Gb(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;Gb(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Gb(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Xb(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},rx=class e extends yb{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??ub(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new Xne(this,e,t);vb(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??ub();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===_x&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Wy(this.doc,n=>{let r=new Kb(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
|
7
7
|
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&$b(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&nx(n,r,a.delete):ex(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??ub();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Sy(s,e)||t!==void 0&&Sy(s,t))switch(s.content.constructor){case _x:{let r=i.get(`ychange`);e!==void 0&&!Sy(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Sy(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case vx:case mx:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case hx:Sy(s,e)&&(c(),Xb(i,s.content));break}s=s.right}c()};return e||t?Wy(a,n=>{e&&Cy(n,e),t&&Cy(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Wy(r,r=>{let i=Jb(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),$b(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Wy(r,r=>{let i=Jb(r,this,e,!n);$b(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Wy(n,n=>{nx(n,Jb(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Wy(r,r=>{let i=Jb(r,this,e,!1);i.right!==null&&ex(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Wy(this.doc,t=>{Mb(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Wy(this.doc,n=>{Nb(n,this,e,t)})}getAttribute(e){return Pb(this,e)}getAttributes(){return Fb(this)}_write(e){e.writeTypeRef(_re)}};const Zne=e=>new rx;var ix=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??ub()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===ox||t.constructor===ax)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},ax=class e extends yb{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof yb?e.clone():e)),t}get length(){return this.doc??ub(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new ix(this,e)}querySelector(e){e=e.toUpperCase();let t=new ix(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),og(new ix(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){vb(this,e,new ere(this,t,e))}toString(){return wb(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),Cb(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Wy(this.doc,n=>{kb(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Wy(this.doc,n=>{let r=e&&e instanceof yb?e._item:e;Db(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw t_(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Wy(this.doc,n=>{jb(n,this,e,t)})}toArray(){return xb(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Eb(this,e)}slice(e=0,t=this.length){return bb(this,e,t)}forEach(e){Cb(this,e)}_write(e){e.writeTypeRef(yre)}};const Qne=e=>new ax;var ox=class e extends ax{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return P_(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof yb?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):Wy(this.doc,t=>{Mb(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Wy(this.doc,n=>{Nb(n,this,e,t)})}getAttribute(e){return Pb(this,e)}hasAttribute(e){return Ib(this,e)}getAttributes(e){return e?Lb(this,e):Fb(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return Cb(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(vre),e.writeKey(this.nodeName)}};const $ne=e=>new ox(e.readKey());var ere=class extends cb{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},tre=class e extends Ub{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(bre),e.writeKey(this.hookName)}};const nre=e=>new tre(e.readKey());var sx=class e extends rx{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(xre)}};const rre=e=>new sx;var cx=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw n_()}mergeWith(e){return!1}write(e,t,n){throw n_()}integrate(e,t){throw n_()}},lx=class extends cx{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),ky(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},ux=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw n_()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const ire=e=>new ux(e.readBuf());var dx=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){kv(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}};const are=e=>new dx(e.readLen()),fx=(e,t)=>new Lv({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var px=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(fx(this.doc.guid,this.opts))}splice(e){throw n_()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}};const ore=e=>new px(fx(e.readString(),e.readAny()));var mx=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw n_()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const sre=e=>new mx(e.readJSON());var hx=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw n_()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}};const cre=e=>new hx(e.readKey(),e.readJSON());var lre=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}};const ure=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new lre(n)},dre=Z_(`node_env`)===`development`;var gx=class e{constructor(e){this.arr=e,dre&&V_(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}};const fre=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new gx(n)};var _x=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}};const pre=e=>new _x(e.readString()),mre=[Vb,Wb,Zne,$ne,Qne,nre,rre],hre=0,gre=1,_re=2,vre=3,yre=4,bre=5,xre=6;var vx=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw n_()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}};const Sre=e=>new vx(mre[e.readTypeRef()](e)),Cre=(e,t)=>{let n=t,r=0,i;do r>0&&(n=gy(n.client,n.clock+r)),i=jy(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof Cx);return{item:i,diff:r}},yx=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},bx=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new Cx(gy(r,i+n),t,gy(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=gy(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},xx=(e,t)=>sg(e,e=>Ev(e.deletions,t)),Sx=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Ny(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Sx(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Ny(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Ny(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Ny(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else{if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||Ev(r,d.right.id)||xx(a.undoStack,d.right.id)||xx(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Ny(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;d!==null&&d.parent._item!==u&&(d=p._map.get(t.parentSub)||null)}let m=gy(c,Oy(s,c)),h=new Cx(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,yx(h,!0),h.integrate(e,0),h};var Cx=class e extends cx{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Oy(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Oy(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===my&&this.id.client!==this.parent.client&&this.parent.clock>=Oy(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Py(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Ny(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===lx||this.right&&this.right.constructor===lx)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===my){let e=jy(n,this.parent);e.constructor===lx?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Py(e,e.doc.store,gy(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),hy(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(hy(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(jy(e.doc.store,n.origin)))r.has(jy(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),ky(e.doc.store,this),this.content.integrate(e,this),zy(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new lx(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:gy(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&hy(e.origin,this.lastId)&&this.right===e&&hy(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),kv(e.deleteSet,this.id.client,this.id.clock,this.length),zy(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw r_();this.content.gc(e),t?Fy(e,this,new lx(this.id,this.length)):this.content=new dx(this.length)}write(e,t){let n=t>0?gy(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=_y(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===my?(e.writeParentInfo(!1),e.writeLeftID(t)):r_();i!==null&&e.writeString(i)}this.content.write(e,t)}};const wx=(e,t)=>wre[t&31](e),wre=[()=>{r_()},are,ure,ire,pre,sre,cre,Sre,fre,ore,()=>{r_()}];var Tx=class extends cx{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){r_()}write(e,t){e.writeInfo(10),Fg(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const Ex=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},Dx=`__ $YJS$ __`;Ex[Dx]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),Ex[Dx]=!0;const Tre=/[\uD800-\uDBFF]/,Ere=/[\uDC00-\uDFFF]/,Dre=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&Tre.test(e[n-1])&&n--;r+n<e.length&&r+n<t.length&&e[e.length-r-1]===t[t.length-r-1];)r++;return r>0&&Ere.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Ore=e=>{let t=Su(`sha256`);return t.update(e),t.digest()},kre=new uo(`y-sync`);new uo(`y-undo`),new uo(`yjs-cursor`);const Are=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},jre=e=>tv(Are(Ore(rv(e)))),Mre=()=>({mapping:new Map,isOMark:new Map}),Ox=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!Ev(t.ds,e.id),Nre=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof ox)return kx(e,t,n,r,i,a);throw n_()}return o},kx=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof ox){let s=Nre(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof rx&&!s._item.deleted&&s._item.id.client===s.doc.clientID&&(e.applyDelta([{retain:e.length},...s.toDelta()]),s.doc.transact(e=>{s._item.delete(e)}));let c=Pre(e,t,n,r,i,a);c!==null&&c.forEach(e=>{e!==null&&o.push(e)})}};r===void 0||i===void 0?e.toArray().forEach(s):Sb(e,new yy(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(Ox(e._item,r)?Ox(e._item,i)||(s.ychange=a?a(`added`,e._item.id):{type:`added`}):s.ychange=a?a(`removed`,e._item.id):{type:`removed`});let c=Ix(s),l=Vx(c.marks,t),u=t.node(e.nodeName,c.plain,o,l.length?l:void 0);return n.mapping.set(e,u),u}catch(r){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(r&&r.message||r));let i=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)i.inline++;else if(i.block++,t.nodes.rawMdxFallback)try{let i=t.node(`rawMdxFallback`,{reason:String(r&&r.message||r)},[t.text(e.nodeName)]);return n.mapping.set(e,i),i}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return n.mapping.delete(e),null}},Pre=(e,t,n,r,i,a)=>{let o=[],s=e.toDelta(r,i,a);try{for(let e=0;e<s.length;e++){let n=s[e];o.push(t.text(n.insert,Vx(n.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return o},Fre=(e,t)=>{let n=new sx,r=e.map(e=>({insert:e.text,attributes:Hx(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Ire=(e,t)=>{let n=new ox(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}let r=Hx(e.marks||[],t);for(let e in r)n.setAttribute(Fx+e,{...r[e]});return n.insert(0,Nx(e).map(e=>Ax(e,t))),t.mapping.set(n,e),n},Ax=(e,t)=>e instanceof Array?Fre(e,t):Ire(e,t),jx=e=>typeof e==`object`&&!!e,Mx=(e,t)=>{let n=Object.keys(e).filter(t=>e[t]!==null),r=n.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let i=0;i<n.length&&r;i++){let a=n[i],o=e[a],s=t[a];r=a===`ychange`||o===s||jx(o)&&jx(s)&&Mx(o,s)}return r},Nx=e=>{let t=e.content.content,n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.isText){let r=[];for(let n=t[e];e<t.length&&n.isText;n=t[++e])r.push(n);e--,n.push(r)}else n.push(r)}return n},Px=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&N_(e.attributes||{}).length===t[n].marks.length&&L_(e.attributes,(e,r)=>{let i=Bx(r),a=t[n].marks;return a.find(e=>e.type.name===i)?Mx(e,a.find(e=>e.type.name===i)?.attrs):!1}))},Fx=`ymark:`,Ix=e=>{let t={},n={};for(let r in e)r.startsWith(Fx)?n[r.slice(6)]=e[r]:t[r]=e[r];return{plain:t,marks:n}},Lre=(e,t)=>{let n=Object.keys(e);return n.length===t.length?n.every(n=>{let r=Bx(n),i=t.find(e=>e.type.name===r);return i?Mx(e[n],i.attrs):!1}):!1},Lx=(e,t)=>{if(e instanceof ox&&!(t instanceof Array)&&Wx(e,t)){let n=Nx(t),r=Ix(e.getAttributes());return e._length===n.length&&Lre(r.marks,t.marks)&&Mx(r.plain,t.attrs)&&e.toArray().every((e,t)=>Lx(e,n[t]))}return e instanceof sx&&t instanceof Array&&Px(e,t)},Rx=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),zx=(e,t,n)=>{let r=e.toArray(),i=Nx(t),a=i.length,o=r.length,s=fg(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(Rx(n.mapping.get(e),t))u=!0;else if(!Lx(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(Rx(n.mapping.get(e),t))u=!0;else if(!Lx(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},Rre=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof _x?t+=n.content.str:n.content instanceof hx&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},zre=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=Rre(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,Hx(e.marks,n))})),{insert:o,remove:s,index:c}=Dre(i,a.map(e=>e.insert).join(``));e.delete(c,s),e.insert(c,o),e.applyDelta(a.map(e=>({retain:e.insert.length,attributes:e.attributes})))},Bre=/(.*)(--[a-zA-Z0-9+/=]{8})$/,Bx=e=>Bre.exec(e)?.[1]??e,Vx=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(Bx(r),e[r]));return n},Hx=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=tg(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${jre(e.toJSON())}`:e.type.name]=e.attrs}}),n},Ux=(e,t,n,r)=>{if(t instanceof ox&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof ox){let e=t.getAttributes(),i=n.attrs;for(let n in i)i[n]===null?t.removeAttribute(n):e[n]!==i[n]&&n!==`ychange`&&t.setAttribute(n,i[n]);for(let n in e)i[n]===void 0&&!n.startsWith(Fx)&&t.removeAttribute(n);let a=Hx(n.marks||[],r);for(let n in a){let r=e[Fx+n];(r===void 0||!Mx(r,a[n]))&&t.setAttribute(Fx+n,{...a[n]})}for(let n in e)n.startsWith(Fx)&&a[n.slice(6)]===void 0&&t.removeAttribute(n)}let i=Nx(n),a=i.length,o=t.toArray(),s=o.length,c=fg(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!Rx(r.mapping.get(e),t))if(Lx(e,t))r.mapping.set(e,t);else break}for(;u+l+1<c;u++){let e=o[s-u-1],t=i[a-u-1];if(!Rx(r.mapping.get(e),t))if(Lx(e,t))r.mapping.set(e,t);else break}e.transact(()=>{for(;s-l-u>0&&a-l-u>0;){let n=o[l],c=i[l],d=o[s-u-1],f=i[a-u-1];if(n instanceof sx&&c instanceof Array)Px(n,c)||zre(n,c,r),l+=1;else{let i=n instanceof ox&&Wx(n,c),a=d instanceof ox&&Wx(d,f);if(i&&a){let e=zx(n,c,r),t=zx(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Ux(e,n,c,r),l+=1):a?(Ux(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[Ax(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof sx?(r.mapping.delete(o[0]),o[0].delete(0,o[0].length)):n>0&&(t.slice(l,l+n).forEach(e=>r.mapping.delete(e)),t.delete(l,n)),l+u<a){let e=[];for(let t=l;t<a-u;t++)e.push(Ax(i[t],r));t.insert(l,e)}},kre)},Wx=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,Vre=(e,t)=>{let n=e.toArray().map(e=>kx(e,t,Mre())).filter(e=>e!==null);return Fn.fromArray(n)},Gx=(e,t)=>t.topNodeType.create(null,Vre(e,t));function Kx(e,t,n,r){let{body:i}=eo(t);return r!==void 0&&r.rawContent===t?r.parsedJson:Mo(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Oo.parseWithFallback(i,qx(n)))}function qx(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function Jx(e){return Oo.serialize(Gx(e,Do).toJSON())}function Yx(e,t,n,r,i,a){let o=Jx(r),s=Oo.serialize(n),{body:c}=eo(e.baselineFullMd),l=Oo.serialize(Oo.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:rn(i,t).md})}function Xx(e,t,n,r,i,a){Mo(`bridge.composeAndWriteRawBody`,{attributes:{surface:n,"body.bytes":t.length,"doc.name":e.guid}},()=>{let n=e.getXmlFragment(`default`),o=e.getText(`source`),s=o.toString(),c=Kx(e,t,r,i),l=Do.nodeFromJSON(c),u=a?Jx(n):void 0;if(s!==t&&vn(o,s,t),Ux(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=eo(a.baselineFullMd);Yx(a,u,c,n,e,qx(r))}})}function Zx(e,t,n,r,i){Mo(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=Kx(e,t,n,r),c=Do.nodeFromJSON(s),l=i?Jx(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),Ux(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=eo(i.baselineFullMd);Yx(i,l,s,a,e,qx(n))}})}function Hre(e,t,n){let r=e.getXmlFragment(`default`),{frontmatter:i,body:a}=eo(e.getText(`source`).toString()),o=qx(t),s=Oo.parseWithFallback(a,o),c=Do.nodeFromJSON(s),l=n?Oo.serialize(Gx(r,Do).toJSON()):void 0;if(Ux(e,r,c,{mapping:new Map,isOMark:new Map}),n&&l!==void 0){let e=Oo.serialize(Gx(r,Do).toJSON()),t=Oo.serialize(s),{body:a}=eo(n.baselineFullMd),c=Oo.serialize(Oo.parseWithFallback(a,o));n.report({pendingBody:l,baselineBody:c,ytextDerivedBody:t,rebuiltBody:e,restorePayload:rn(i,l).md})}}const Ure=L(`loss-capture`),Qx=`detector-trip`,$x=`backstop-trip`,eS=`checkpoint-write`;M({ts:N(),schemaVersion:N(),seq:N(),event:F(),docName:F(),writerId:F().nullable(),site:F().optional(),direction:F().optional(),lostLen:N().optional(),digest:F().optional(),checkpointSha:F().optional()});const tS=[`.ok`,`local`,`loss-capture`];function Wre(e){return z(e,...tS,`loss-current.jsonl`)}function Gre(e){return z(e,...tS,`loss-prev.jsonl`)}var Kre=class{#e;#t;#n=new Map;constructor(e){this.#e=new ps({currentPath:Wre(e.projectDir),previousPath:Gre(e.projectDir),maxBytes:e.maxBytes}),this.#t=e.now??Date.now}record(e){let t=(this.#n.get(e.docName)??0)+1;this.#n.set(e.docName,t);let n={ts:this.#t(),schemaVersion:1,seq:t,event:e.event,docName:e.docName,writerId:e.writerId,...e.site===void 0?{}:{site:e.site},...e.direction===void 0?{}:{direction:e.direction},...e.lostLen===void 0?{}:{lostLen:e.lostLen},...e.digest===void 0?{}:{digest:e.digest},...e.checkpointSha===void 0?{}:{checkpointSha:e.checkpointSha}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{Ure.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const nS=L(`checkpoint-chain`);async function rS(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw nS.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
|
|
@@ -24,7 +24,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D
|
|
|
24
24
|
`))n.trim()!==``&&(e.stderrTail.push(n.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())}),i.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`)}),i.on(`exit`,(t,n)=>{if(e.child=null,e.terminals?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),e.closed||e.info.archived===!0)return;let r=e.stderrTail.slice(-10).join(`
|
|
25
25
|
`);this.emitStatus(e,e.info.status===`error`?`error`:`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),i.stdin===null||i.stdout===null)throw new uD(`spawn-failed`,`agent process has no stdio`);let a=Une(bu.toWeb(i.stdin),vu.toWeb(i.stdout)),o=new xoe({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log});e.terminals=o;let s=Uh({name:`open-knowledge`}).onRequest(ch.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(ch.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(ch.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(ch.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),o.create(t.params))).onRequest(ch.client.terminal.output,e=>o.output(e.params.terminalId)).onRequest(ch.client.terminal.waitForExit,e=>o.waitForExit(e.params.terminalId)).onRequest(ch.client.terminal.kill,async e=>(await o.kill(e.params.terminalId),{})).onRequest(ch.client.terminal.release,async e=>(await o.release(e.params.terminalId),{})).onNotification(ch.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(a);e.conn=s,s.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let c;try{c=await s.agent.request(ch.agent.initialize,{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(e){throw new uD(`spawn-failed`,`initialize failed: ${mD(e)}`)}return e.closed?null:{conn:s,init:c,launch:n}}async ensureLaunchable(e,t){try{return await TE(t),t}catch(n){if(!(n instanceof hE)||n.code!==`command-not-found`||t.kind!==`npx`&&t.kind!==`uvx`)throw n;let r=UE(t.kind);if(!hoe(r))throw n;let i=await this.provideManagedRuntime(e,r);if(i===null)return null;let a=xE(t,i);return await TE(a),a}}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root,r=await ZE(t,n).catch(()=>null);if(r!==null)return r;let i=(await eD(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new hE(`command-not-found`,joe(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=WE(t).displayName;throw new hE(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=WE(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:n,runtime:t,displayName:r.displayName,provides:r.provides,version:r.version,approxSizeMB:r.approxSizeMB,sourceHost:r.sourceHost,agentName:e.info.agent.name,ts:Date.now()}),new Promise(r=>{let i=setTimeout(()=>{e.pendingRuntimeConsent.delete(n),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:n,decision:`timeout`,ts:Date.now()}),r(`timeout`)},3e5);i.unref?.(),e.pendingRuntimeConsent.set(n,{runtime:t,resolve:r,timer:i})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;n.remember===!0&&yoe(i.runtime,a,this.opts.log,this.opts.runtimeInstall?.consentHome),this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return voe(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t){if(await this.harnessAlreadyHasOkMcp(e)!==null)return[];let n=[],r=this.opts.getServerUrl?.();if(r!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)n.push({type:`http`,name:`open-knowledge`,url:`${r}/mcp`,headers:[]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=kte[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async startThread(e,t,n){let r;try{r=await this.connectAgent(e,n)}catch(t){let n=t instanceof hE||t instanceof uD?t.message:String(t);this.emitStatus(e,`error`,n);return}if(r===null)return;let{conn:i,init:a,launch:o}=r,s=await this.buildMcpServers(e,a);try{let t=await i.agent.request(ch.agent.session.new,{cwd:e.cwd,mcpServers:s});e.sessionId=t.sessionId,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),t.modes!==void 0&&t.modes!==null&&(e.info.modes=t.modes,this.emitInfo(e)),t.configOptions!==void 0&&t.configOptions!==null&&(e.info.configOptions=t.configOptions,this.emitInfo(e))}catch(t){let n=(a.authMethods??[]).map(e=>typeof e==`object`&&e?e.name:null).filter(e=>typeof e==`string`);n.length>0?this.emitStatus(e,`auth_required`,`sign in first (${n.join(` / `)}), then start a new thread — ${mD(t)}`):this.emitStatus(e,`error`,`session setup failed: ${mD(t)}`);return}e.closed||t.settings?.config!==void 0&&(await this.applyInitialConfig(e,i,t.settings.config),e.closed)||t.settings?.modeId!==void 0&&(await this.applyInitialMode(e,i,t.settings.modeId),e.closed)||(this.setPresence(e,`idle`),this.emitStatus(e,`ready`),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:o.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),t.prompt!==void 0&&t.prompt!==``&&this.sendPrompt(e.info.threadId,t.prompt))}async resumeThread(e,t){if(this.destroyed)throw new uD(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new uD(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new uD(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new uD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.resumeInFlight=!0;let r=Date.now();try{await this.ensureLogResolved(n);let i=n.sessionId,{info:a,custom:o}=await this.resolveAgentInfo(n.agentRef);if(this.destroyed)throw new uD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new uD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.info.agent=a,n.info.archived=!1,n.stderrTail=[],n.midTurnOnDisk&&(n.midTurnOnDisk=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),t!==void 0&&t!==``&&(this.echoUserMessage(n,t),this.flushBroadcast(n)),this.emitStatus(n,`installing`);try{if(i===null)throw new uD(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new uD(`not-ready`,`thread closed during resume`);let{conn:s,init:c}=a,l=await this.buildMcpServers(n,c),u=c.agentCapabilities,d=u?.sessionCapabilities?.resume!=null,f;if(d)f=await s.agent.request(ch.agent.session.resume,{sessionId:i,cwd:n.cwd,mcpServers:l});else if(u?.loadSession===!0){n.suppressUpdates=!0,n.lastSuppressedAt=Date.now();try{f=await s.agent.request(ch.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new uD(`resume-unsupported`,`${n.info.agent.name} doesn't support resuming previous sessions`);n.sessionId=i;let p=f.modes;p!=null&&(n.info.modes=p);let m=f.configOptions;return m!=null&&(n.info.configOptions=m),this.setPresence(n,`idle`),this.emitStatus(n,`ready`),this.opts.log.info({threadId:e,agentId:n.info.agent.id,method:d?`session/resume`:`session/load`,msToResumed:Date.now()-r},`[acp-threads] thread resumed`),t!==void 0&&t!==``&&this.dispatchPrompt(n,t,{echo:!1}),{...n.info}}catch(e){throw await this.abortResume(n),e instanceof uD?e:e instanceof hE?new uD(e.code===`install-failed`?`install-failed`:`spawn-failed`,e.message):new uD(`resume-unsupported`,`couldn't resume the previous session: ${mD(e)}`)}}finally{n.resumeInFlight=!1}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingRuntimeConsent(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await LE(t,{graceMs:lD}),e.child=null,e.conn=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(Yh(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),this.flushBroadcast(e),this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),await this.persistence.whenIdle(e.info.threadId),e.baseSeq=e.info.lastSeq+1,e.events=[]}async awaitReplayQuiescence(e){let t=Date.now()+3e3;for(;Date.now()-e.lastSuppressedAt<300&&Date.now()<t;)await new Promise(e=>setTimeout(e,50))}sendPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new uD(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new uD(`not-ready`,`the thread is still resuming`);if(n.sessionId===null||n.conn===null)throw new uD(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new uD(`not-ready`,`20 messages are already waiting — let the agent catch up`);n.info.queue=[...e,{id:crypto.randomUUID(),content:t,ts:Date.now()}],n.info.lastActivityAt=Date.now(),this.emitInfo(n);return}this.dispatchPrompt(n,t,{echo:!0})}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];i.some(e=>e.id===t)&&(r.info.queue=i.map(e=>e.id===t?{...e,content:n}:e),this.emitInfo(r))}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);i.length!==r.length&&(n.info.queue=i.length>0?i:void 0,this.emitInfo(n))}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let[n,...r]=t;return e.info.queue=r.length>0?r:void 0,n??null}echoUserMessage(e,t){if(e.hadUserMessage=!0,e.info.title===e.info.agent.name&&t.trim()!==``){let n=e.titleHint!==void 0&&e.titleHint.trim()!==``?e.titleHint:t;e.titleHint=void 0,e.info.title=Doe(n),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}this.appendEvent(e,{kind:`user_message`,content:t,ts:Date.now()})}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new uD(`not-ready`,`the thread is closing`);let r=sD(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n){if(e.sessionId===null||e.conn===null)throw new uD(`not-ready`,`thread has no live agent session`);n.echo&&this.echoUserMessage(e,t),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`),this.setPresence(e,`writing`);let r=e.sessionId;e.conn.agent.request(ch.agent.session.prompt,{sessionId:r,prompt:[{type:`text`,text:t}]}).then(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:t.stopReason,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeNextQueued(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}}this.emitStatus(e,`ready`),this.setPresence(e,`idle`)}}).catch(t=>{e.turnActive=!1,!e.closed&&(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.cancelRequested?this.emitStatus(e,`ready`):this.emitStatus(e,`error`,`prompt failed: ${mD(t)}`),this.setPresence(e,`idle`))})}cancel(e){let t=this.mustGet(e);t.info.queue!==void 0&&(t.info.queue=void 0,this.emitInfo(t)),!(t.conn===null||t.sessionId===null)&&(t.turnActive&&(t.cancelRequested=!0),this.failPendingPermissions(t),this.restoreRunningAfterPermission(t),t.conn.agent.notify(ch.agent.session.cancel,{sessionId:t.sessionId}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new uD(`not-ready`,`thread has no live agent session`);n.conn.agent.request(ch.agent.session.setMode,{sessionId:n.sessionId,modeId:t}).then(()=>{n.info.modes&&(n.info.modes={...n.info.modes,currentModeId:t},this.emitInfo(n))}).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] set_mode failed`)})}setConfigOption(e,t,n){let r=this.mustGet(e);if(r.conn===null||r.sessionId===null)throw new uD(`not-ready`,`thread has no live agent session`);let i=typeof n==`boolean`?{sessionId:r.sessionId,configId:t,type:`boolean`,value:n}:{sessionId:r.sessionId,configId:t,value:n};r.conn.agent.request(ch.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n){let r=e.sessionId;if(r===null)return;let i=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,a=Object.keys(n).sort((e,t)=>Number(i(t))-Number(i(e))),o=!1,s=[];for(let i of a){let a=n[i];if(a===void 0)continue;let c=(e.info.configOptions??[]).find(e=>e.id===i);if(c===void 0||c.currentValue===a||!pD(c,a))continue;let l=typeof a==`boolean`?{sessionId:r,configId:i,type:`boolean`,value:a}:{sessionId:r,configId:i,value:a};try{let n=await t.agent.request(ch.agent.session.setConfigOption,l);e.info.configOptions=n.configOptions,o=!0}catch(t){s.push(i),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:i},`[acp-threads] initial config apply failed`)}if(e.closed)return}s.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:s},`[acp-threads] some remembered config options could not be applied to the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n){let r=e.sessionId;if(r===null)return;let i=e.info.modes;if(i!=null&&i.availableModes.some(e=>e.id===n)){if(i.currentModeId===n)return;try{await t.agent.request(ch.agent.session.setMode,{sessionId:r,modeId:n}),e.info.modes={...i,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let a=(e.info.configOptions??[]).find(e=>e.category===`mode`&&pD(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(ch.agent.session.setConfigOption,{sessionId:r,configId:a.id,value:n});e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;if(r!==null&&(await LE(r,{graceMs:t?.killGraceMs??5e3})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(Yh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)}),!n.hadUserMessage){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(n,`exited`,`thread closed`),this.flushBroadcast(n),this.persistence.queueMetaWrite(e,this.buildMeta(n)),await this.persistence.whenIdle(e),n.baseSeq=n.info.lastSeq+1,n.events=[],n.pendingBroadcast=[],n.closed=!1,this.opts.log.info({threadId:e},`[acp-threads] thread archived`)}async deleteThread(e){let t=this.mustGet(e);if(t.info.archived!==!0)throw new uD(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new uD(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:lD})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:rE(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await pu(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await pu(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
26
26
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
27
|
-
`)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=HT(t.dc.document);VT(t.dc.document,n,`replace`,i,void 0,zT(t));let a=to(r,HT(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,`writing`,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-DbSNN5G0.mjs`);await e(R(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return koe(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new uD(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&cE(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>cD){let t=e.events.length-cD;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n){(t===`exited`||t===`error`)&&(e.info.queue=void 0),e.info.status=t,e.info.lastActivityAt=Date.now(),this.appendEvent(e,{kind:`status`,status:t,detail:n,ts:Date.now()}),this.emitInfo(e)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e));for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}buildMeta(e){let{queue:t,...n}=e.info;return{version:1,info:n,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t,n){let r=this.opts.agentPresenceBroadcaster;if(r!=null)try{let i=Br(e.info.agent.id),a=Nr[i]??Gi(e.agentSessionId);r.setPresence(Yh(e.agentSessionId),{displayName:e.info.agent.name,icon:i,color:a,currentDoc:n??e.docName??`(agent thread)`,mode:t,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function koe(e,t,n){let r=await hu(e),i=Ol(Dl(t)?t:V(r,t)),a=i,o=``;for(;;)try{let e=await hu(a),i=o===``?e:z(e,o),s=B(r,i);if(s===``||s.startsWith(`..`)||Dl(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(Al).join(`/`),t=s.split(Al).join(`/`);!fC(e)&&!pC(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Al).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=R(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):z(a.slice(t.length+1),o),a=t}}function Aoe(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0}}function pD(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function joe(e){let t=WE(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function mD(e){if(e instanceof Error){let t=e.data;if(t!=null)try{return`${e.message} (${JSON.stringify(t).slice(0,300)})`}catch{return e.message}return e.message}return String(e)}const Moe=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`queue_edit`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`delete`,`list`]);function Noe(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;if(typeof n.op!=`string`||!Moe.has(n.op))return null;let r=e=>typeof n[e]==`string`&&n[e]!==``;switch(n.op){case`create`:{if(!r(`reqId`))return null;let e=n.agent;if(typeof e!=`object`||!e||e.source!==`registry`&&e.source!==`custom`||typeof e.id!=`string`||e.id===``||n.prompt!==void 0&&typeof n.prompt!=`string`||n.docName!==void 0&&typeof n.docName!=`string`)return null;if(n.settings!==void 0){let e=n.settings;if(typeof e!=`object`||!e)return null;if(e.config!==void 0){let t=e.config;if(typeof t!=`object`||!t||Array.isArray(t))return null;for(let e of Object.values(t))if(typeof e!=`string`&&typeof e!=`boolean`)return null}if(e.modeId!==void 0&&typeof e.modeId!=`string`)return null}return n}case`subscribe`:return!r(`threadId`)||n.sinceSeq!==void 0&&typeof n.sinceSeq!=`number`?null:n;case`prompt`:return!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`?null:n;case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)?null:n;case`queue_remove`:return!r(`threadId`)||!r(`id`)?null:n;case`permission_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;if(typeof e!=`object`||!e)return null;if(e.kind===`selected`){if(typeof e.optionId!=`string`||e.optionId===``)return null}else if(e.kind!==`cancelled`)return null;return n}case`runtime_consent_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;return typeof e!=`object`||!e||e.kind!==`granted`&&e.kind!==`declined`||e.remember!==void 0&&typeof e.remember!=`boolean`?null:n}case`set_mode`:return!r(`threadId`)||!r(`modeId`)?null:n;case`rename`:return!r(`threadId`)||!r(`title`)?null:n;case`set_config_option`:return!r(`threadId`)||!r(`configId`)||typeof n.value!=`string`&&typeof n.value!=`boolean`||n.value===``?null:n;case`resume`:return!r(`threadId`)||!r(`reqId`)||n.prompt!==void 0&&typeof n.prompt!=`string`?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function hD(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(Poe(e,t,n));e.on(`message`,e=>{let s=Noe(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content);return;case`queue_edit`:t.editQueued(s.threadId,s.id,s.content);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:await t.renameThread(s.threadId,s.title);return;case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof uD?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{let s=t.getInfo(e);if(s===void 0){r.delete(e),a(`unknown-thread`,`no thread '${e}'`,{threadId:e});return}i({op:`subscribed`,threadId:e,fromSeq:Math.max(n,0),info:s}),await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof uD)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function Poe(e,t,n){return{op:`error`,code:e,message:t,...n}}var gD=class{hocuspocus;log=L(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){Xh(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){Xh(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),Foe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function Foe(e){return e?.awareness??null}var _D=class{hocuspocus;log=L(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!Xh(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!Xh(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!Xh(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!Xh(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return uae(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Ioe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Ioe(e){return e?.awareness??null}var vD=class extends Error{};const Loe=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],yD=1024*1024;async function bD(e,t,n,r){let i=t;for(let t=0;t<=5;t++){let t=await e(i,{...r,redirect:`manual`});if(t.status<300||t.status>=400)return t;let a=t.headers.get(`location`);if(a===null||a===``)throw new vD(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new vD(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new vD(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new vD(`Website skill fetch exceeded 5 redirects: ${t}`)}function xD(e){let t;try{t=new URL(e)}catch{throw new vD(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new vD(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new vD(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function SD(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function Roe(e){if(!e||typeof e!=`object`)return null;let t=e.skills;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{name:t,description:r,files:i}=e;if(typeof t!=`string`||!SD(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&SD(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function zoe(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function CD(e,t,n){let r=[];for(let i of Loe){let a=new URL(i,e).href;try{let o=await bD(t,a,e,{signal:AbortSignal.timeout(n)});if(!o.ok){r.push(`${i}: HTTP ${o.status}`);continue}let s=await o.text();if(Buffer.byteLength(s)>yD){r.push(`${i}: index exceeds ${yD} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=Roe(c);if(!l){r.push(`${i}: unsupported or malformed index`);continue}return{basePath:i.slice(0,-11),skills:l}}catch(e){r.push(`${i}: ${e instanceof Error?e.message:String(e)}`)}}throw new vD(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function Boe(e,t={}){let{skills:n}=t.index??await wD(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function wD(e,t={}){let n=xD(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new vD(`No fetch implementation available.`);return CD(n,r,t.timeoutMs??15e3)}async function Voe(e,t={}){if(!SD(e.skill)||e.skill.includes(`/`))throw new vD(`Invalid website skill name: ${e.skill}`);let n=xD(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new vD(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await CD(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new vD(`Website skill index does not contain ${e.skill}`);let c=Wl(z(cu(),`ok-skill-site-`)),l=z(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await bD(r,zoe(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new vD(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new vD(`Website skill file exceeds ${ji} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new vD(`Website skill file exceeds ${ji} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new vD(`Website skill bundle exceeds ${$t} bytes.`);let d=z(l,...e.split(`/`));Ul(R(d),{recursive:!0}),tu(d,c)};return await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(let n=e.shift();n!==void 0;n=e.shift())await t(n)})),{dir:l,cleanup:()=>Zl(c,{recursive:!0,force:!0})}}catch(t){throw Zl(c,{recursive:!0,force:!0}),t instanceof vD?t:new vD(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const Hoe=Pu(yl),Uoe=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,TD=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function ED(e){let t=e.trim();if(t===``)return null;if(t.startsWith(`file://`))return{kind:`local`,path:t.slice(7)};if(t.startsWith(`/`)||t.startsWith(`.`)||t.startsWith(`~`))return{kind:`local`,path:t};if(t.startsWith(`git@`)||t.includes(`://`))return TD.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=Uoe.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function DD(e){let t=e.trim();if(t===``)return null;let n=e=>{let t=e.split(`/`).filter(Boolean).map(decodeURIComponent);if(t.length!==3)return null;let[n,r,i]=t,a=n===`site`?r:n,o=i;return a&&o?{owner:a,skill:o}:null};if(/^https?:\/\//i.test(t))try{let e=new URL(t),r=e.hostname.toLowerCase();return r!==`skills.sh`&&r!==`www.skills.sh`?null:n(e.pathname)}catch{return null}let r=/^skills\.sh\/(.+)$/i.exec(t);if(r)return n(r[1]??``);let i=/^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(t);if(i){let[,e,t]=i;return e&&t?{owner:e,skill:t}:null}return null}async function OD(e,t={}){if(e.kind===`well-known`)return Voe(e,t);if(e.kind===`local`){let t=V(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!H(t))throw new vD(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!TD.some(t=>t.test(e.url)))throw new vD(`Unsupported git transport: ${e.url}`);let n=Wl(z(cu(),`ok-skill-import-`));try{await Hoe(`git`,[`-c`,`core.symlinks=false`,`clone`,`-q`,`--depth`,`1`,`--`,e.url,n],{timeout:6e4,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}})}catch(t){Zl(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new vD(`git clone failed for ${e.url}: ${r}`)}let r;try{r=bl(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?V(n,e.subpath):n,a=B(n,i);if(a.startsWith(`..`)||Dl(a))throw Zl(n,{recursive:!0,force:!0}),new vD(`subpath escapes the clone: ${e.subpath}`);if(!H(i))throw Zl(n,{recursive:!0,force:!0}),new vD(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>Zl(n,{recursive:!0,force:!0})}}const kD=[`.ok`,`skills-lock.json`],Woe=ue({source:F(),pluginProvider:F().optional(),skill:F().optional(),ref:F().optional(),contentHash:F(),files:j(F()).optional(),localHash:F().optional(),baselineRef:F().optional(),publisher:F().optional(),importedAt:i(),autoUpdate:D().optional()}),Goe=ue({schema:k(1),skills:E(F(),Woe).default({})});function AD(){return{schema:1,skills:{}}}function jD(e){let t;try{t=JSON.parse(e)}catch{return null}let n=Goe.safeParse(t);return n.success?n.data:null}function MD(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}function Koe(e,t,n){return e.startsWith(`open-knowledge-pack-`)?{source:ao,skill:e,contentHash:t,importedAt:n}:null}function qoe(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function ND(e,t){let n=t,r=``,{frontmatter:i}=eo(e);if(i!==``){let{map:e}=Wi(mo(i)),t=e?.name,a=e?.description;typeof t==`string`&&t.trim()!==``&&(n=t),typeof a==`string`&&(r=a)}return{name:n,description:r}}const PD=new Set([`.git`,`node_modules`]),Joe=new Set([...PD,`scripts`,`references`]);function Yoe(e){let t=[],n=r=>{for(let i of Jl(r,{withFileTypes:!0})){let a=z(r,i.name);if(i.isDirectory()){PD.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=B(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=U(a);t.push(s.includes(0)?{relPath:o,content:null,bytes:new Uint8Array(s)}:{relPath:o,content:s.toString(`utf-8`)})}};return n(e),t.sort((e,t)=>e.relPath.localeCompare(t.relPath))}function FD(e){let t=z(e,`SKILL.md`);return H(t)?ND(U(t,`utf-8`),wl(e)):null}function ID(e){let t=0,n=0,r=null,i=(e,t)=>(r=`Skill bundle could not be read (${e}): ${t instanceof Error?t.message:String(t)}`,null);try{n=H(z(e,`SKILL.md`))?$l(z(e,`SKILL.md`)).size:0}catch(e){return i(`stat SKILL.md`,e)??r}if(n>16777216)return`SKILL.md is ${n} bytes; the import per-file cap is ${ji}.`;if(n>67108864)return`Skill exceeds ${$t} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=Jl(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=z(o,c.name);if(c.isDirectory()){PD.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=B(e,s).split(`\\`).join(`/`);if(l===`SKILL.md`)continue;if(t+=1,t>512){r=`Skill has more than 512 dependent files; that is the import cap.`;return}let u;try{u=$l(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${ji}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${$t} bytes; that is the import bundle cap.`;return}}};try{a(e)}catch(e){return`Skill bundle could not be measured: ${e instanceof Error?e.message:String(e)}`}return r}function LD(e){let t=z(e,`SKILL.md`);if(!H(t))return null;let n=U(t,`utf-8`),{name:r,description:i}=ND(n,wl(e)),a=Yoe(e),o=Su(`sha256`);o.update(`SKILL.md\n${n}\n`);for(let e of a)o.update(`${e.relPath}\n`),o.update(e.bytes??e.content??``),o.update(`
|
|
27
|
+
`)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=HT(t.dc.document);VT(t.dc.document,n,`replace`,i,void 0,zT(t));let a=to(r,HT(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,`writing`,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-CbQ-GS7x.mjs`);await e(R(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return koe(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new uD(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&cE(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>cD){let t=e.events.length-cD;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n){(t===`exited`||t===`error`)&&(e.info.queue=void 0),e.info.status=t,e.info.lastActivityAt=Date.now(),this.appendEvent(e,{kind:`status`,status:t,detail:n,ts:Date.now()}),this.emitInfo(e)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e));for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}buildMeta(e){let{queue:t,...n}=e.info;return{version:1,info:n,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t,n){let r=this.opts.agentPresenceBroadcaster;if(r!=null)try{let i=Br(e.info.agent.id),a=Nr[i]??Gi(e.agentSessionId);r.setPresence(Yh(e.agentSessionId),{displayName:e.info.agent.name,icon:i,color:a,currentDoc:n??e.docName??`(agent thread)`,mode:t,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function koe(e,t,n){let r=await hu(e),i=Ol(Dl(t)?t:V(r,t)),a=i,o=``;for(;;)try{let e=await hu(a),i=o===``?e:z(e,o),s=B(r,i);if(s===``||s.startsWith(`..`)||Dl(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(Al).join(`/`),t=s.split(Al).join(`/`);!fC(e)&&!pC(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Al).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=R(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):z(a.slice(t.length+1),o),a=t}}function Aoe(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0}}function pD(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function joe(e){let t=WE(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function mD(e){if(e instanceof Error){let t=e.data;if(t!=null)try{return`${e.message} (${JSON.stringify(t).slice(0,300)})`}catch{return e.message}return e.message}return String(e)}const Moe=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`queue_edit`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`delete`,`list`]);function Noe(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;if(typeof n.op!=`string`||!Moe.has(n.op))return null;let r=e=>typeof n[e]==`string`&&n[e]!==``;switch(n.op){case`create`:{if(!r(`reqId`))return null;let e=n.agent;if(typeof e!=`object`||!e||e.source!==`registry`&&e.source!==`custom`||typeof e.id!=`string`||e.id===``||n.prompt!==void 0&&typeof n.prompt!=`string`||n.docName!==void 0&&typeof n.docName!=`string`)return null;if(n.settings!==void 0){let e=n.settings;if(typeof e!=`object`||!e)return null;if(e.config!==void 0){let t=e.config;if(typeof t!=`object`||!t||Array.isArray(t))return null;for(let e of Object.values(t))if(typeof e!=`string`&&typeof e!=`boolean`)return null}if(e.modeId!==void 0&&typeof e.modeId!=`string`)return null}return n}case`subscribe`:return!r(`threadId`)||n.sinceSeq!==void 0&&typeof n.sinceSeq!=`number`?null:n;case`prompt`:return!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`?null:n;case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)?null:n;case`queue_remove`:return!r(`threadId`)||!r(`id`)?null:n;case`permission_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;if(typeof e!=`object`||!e)return null;if(e.kind===`selected`){if(typeof e.optionId!=`string`||e.optionId===``)return null}else if(e.kind!==`cancelled`)return null;return n}case`runtime_consent_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;return typeof e!=`object`||!e||e.kind!==`granted`&&e.kind!==`declined`||e.remember!==void 0&&typeof e.remember!=`boolean`?null:n}case`set_mode`:return!r(`threadId`)||!r(`modeId`)?null:n;case`rename`:return!r(`threadId`)||!r(`title`)?null:n;case`set_config_option`:return!r(`threadId`)||!r(`configId`)||typeof n.value!=`string`&&typeof n.value!=`boolean`||n.value===``?null:n;case`resume`:return!r(`threadId`)||!r(`reqId`)||n.prompt!==void 0&&typeof n.prompt!=`string`?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function hD(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(Poe(e,t,n));e.on(`message`,e=>{let s=Noe(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content);return;case`queue_edit`:t.editQueued(s.threadId,s.id,s.content);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:await t.renameThread(s.threadId,s.title);return;case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof uD?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{let s=t.getInfo(e);if(s===void 0){r.delete(e),a(`unknown-thread`,`no thread '${e}'`,{threadId:e});return}i({op:`subscribed`,threadId:e,fromSeq:Math.max(n,0),info:s}),await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof uD)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function Poe(e,t,n){return{op:`error`,code:e,message:t,...n}}var gD=class{hocuspocus;log=L(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){Xh(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){Xh(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),Foe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function Foe(e){return e?.awareness??null}var _D=class{hocuspocus;log=L(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!Xh(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!Xh(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!Xh(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!Xh(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return uae(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Ioe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Ioe(e){return e?.awareness??null}var vD=class extends Error{};const Loe=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],yD=1024*1024;async function bD(e,t,n,r){let i=t;for(let t=0;t<=5;t++){let t=await e(i,{...r,redirect:`manual`});if(t.status<300||t.status>=400)return t;let a=t.headers.get(`location`);if(a===null||a===``)throw new vD(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new vD(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new vD(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new vD(`Website skill fetch exceeded 5 redirects: ${t}`)}function xD(e){let t;try{t=new URL(e)}catch{throw new vD(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new vD(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new vD(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function SD(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function Roe(e){if(!e||typeof e!=`object`)return null;let t=e.skills;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{name:t,description:r,files:i}=e;if(typeof t!=`string`||!SD(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&SD(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function zoe(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function CD(e,t,n){let r=[];for(let i of Loe){let a=new URL(i,e).href;try{let o=await bD(t,a,e,{signal:AbortSignal.timeout(n)});if(!o.ok){r.push(`${i}: HTTP ${o.status}`);continue}let s=await o.text();if(Buffer.byteLength(s)>yD){r.push(`${i}: index exceeds ${yD} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=Roe(c);if(!l){r.push(`${i}: unsupported or malformed index`);continue}return{basePath:i.slice(0,-11),skills:l}}catch(e){r.push(`${i}: ${e instanceof Error?e.message:String(e)}`)}}throw new vD(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function Boe(e,t={}){let{skills:n}=t.index??await wD(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function wD(e,t={}){let n=xD(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new vD(`No fetch implementation available.`);return CD(n,r,t.timeoutMs??15e3)}async function Voe(e,t={}){if(!SD(e.skill)||e.skill.includes(`/`))throw new vD(`Invalid website skill name: ${e.skill}`);let n=xD(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new vD(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await CD(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new vD(`Website skill index does not contain ${e.skill}`);let c=Wl(z(cu(),`ok-skill-site-`)),l=z(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await bD(r,zoe(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new vD(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new vD(`Website skill file exceeds ${ji} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new vD(`Website skill file exceeds ${ji} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new vD(`Website skill bundle exceeds ${$t} bytes.`);let d=z(l,...e.split(`/`));Ul(R(d),{recursive:!0}),tu(d,c)};return await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(let n=e.shift();n!==void 0;n=e.shift())await t(n)})),{dir:l,cleanup:()=>Zl(c,{recursive:!0,force:!0})}}catch(t){throw Zl(c,{recursive:!0,force:!0}),t instanceof vD?t:new vD(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const Hoe=Pu(yl),Uoe=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,TD=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function ED(e){let t=e.trim();if(t===``)return null;if(t.startsWith(`file://`))return{kind:`local`,path:t.slice(7)};if(t.startsWith(`/`)||t.startsWith(`.`)||t.startsWith(`~`))return{kind:`local`,path:t};if(t.startsWith(`git@`)||t.includes(`://`))return TD.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=Uoe.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function DD(e){let t=e.trim();if(t===``)return null;let n=e=>{let t=e.split(`/`).filter(Boolean).map(decodeURIComponent);if(t.length!==3)return null;let[n,r,i]=t,a=n===`site`?r:n,o=i;return a&&o?{owner:a,skill:o}:null};if(/^https?:\/\//i.test(t))try{let e=new URL(t),r=e.hostname.toLowerCase();return r!==`skills.sh`&&r!==`www.skills.sh`?null:n(e.pathname)}catch{return null}let r=/^skills\.sh\/(.+)$/i.exec(t);if(r)return n(r[1]??``);let i=/^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(t);if(i){let[,e,t]=i;return e&&t?{owner:e,skill:t}:null}return null}async function OD(e,t={}){if(e.kind===`well-known`)return Voe(e,t);if(e.kind===`local`){let t=V(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!H(t))throw new vD(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!TD.some(t=>t.test(e.url)))throw new vD(`Unsupported git transport: ${e.url}`);let n=Wl(z(cu(),`ok-skill-import-`));try{await Hoe(`git`,[`-c`,`core.symlinks=false`,`clone`,`-q`,`--depth`,`1`,`--`,e.url,n],{timeout:6e4,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}})}catch(t){Zl(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new vD(`git clone failed for ${e.url}: ${r}`)}let r;try{r=bl(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?V(n,e.subpath):n,a=B(n,i);if(a.startsWith(`..`)||Dl(a))throw Zl(n,{recursive:!0,force:!0}),new vD(`subpath escapes the clone: ${e.subpath}`);if(!H(i))throw Zl(n,{recursive:!0,force:!0}),new vD(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>Zl(n,{recursive:!0,force:!0})}}const kD=[`.ok`,`skills-lock.json`],Woe=ue({source:F(),pluginProvider:F().optional(),skill:F().optional(),ref:F().optional(),contentHash:F(),files:j(F()).optional(),localHash:F().optional(),baselineRef:F().optional(),publisher:F().optional(),importedAt:i(),autoUpdate:D().optional()}),Goe=ue({schema:k(1),skills:E(F(),Woe).default({})});function AD(){return{schema:1,skills:{}}}function jD(e){let t;try{t=JSON.parse(e)}catch{return null}let n=Goe.safeParse(t);return n.success?n.data:null}function MD(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}function Koe(e,t,n){return e.startsWith(`open-knowledge-pack-`)?{source:ao,skill:e,contentHash:t,importedAt:n}:null}function qoe(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function ND(e,t){let n=t,r=``,{frontmatter:i}=eo(e);if(i!==``){let{map:e}=Wi(mo(i)),t=e?.name,a=e?.description;typeof t==`string`&&t.trim()!==``&&(n=t),typeof a==`string`&&(r=a)}return{name:n,description:r}}const PD=new Set([`.git`,`node_modules`]),Joe=new Set([...PD,`scripts`,`references`]);function Yoe(e){let t=[],n=r=>{for(let i of Jl(r,{withFileTypes:!0})){let a=z(r,i.name);if(i.isDirectory()){PD.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=B(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=U(a);t.push(s.includes(0)?{relPath:o,content:null,bytes:new Uint8Array(s)}:{relPath:o,content:s.toString(`utf-8`)})}};return n(e),t.sort((e,t)=>e.relPath.localeCompare(t.relPath))}function FD(e){let t=z(e,`SKILL.md`);return H(t)?ND(U(t,`utf-8`),wl(e)):null}function ID(e){let t=0,n=0,r=null,i=(e,t)=>(r=`Skill bundle could not be read (${e}): ${t instanceof Error?t.message:String(t)}`,null);try{n=H(z(e,`SKILL.md`))?$l(z(e,`SKILL.md`)).size:0}catch(e){return i(`stat SKILL.md`,e)??r}if(n>16777216)return`SKILL.md is ${n} bytes; the import per-file cap is ${ji}.`;if(n>67108864)return`Skill exceeds ${$t} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=Jl(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=z(o,c.name);if(c.isDirectory()){PD.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=B(e,s).split(`\\`).join(`/`);if(l===`SKILL.md`)continue;if(t+=1,t>512){r=`Skill has more than 512 dependent files; that is the import cap.`;return}let u;try{u=$l(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${ji}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${$t} bytes; that is the import bundle cap.`;return}}};try{a(e)}catch(e){return`Skill bundle could not be measured: ${e instanceof Error?e.message:String(e)}`}return r}function LD(e){let t=z(e,`SKILL.md`);if(!H(t))return null;let n=U(t,`utf-8`),{name:r,description:i}=ND(n,wl(e)),a=Yoe(e),o=Su(`sha256`);o.update(`SKILL.md\n${n}\n`);for(let e of a)o.update(`${e.relPath}\n`),o.update(e.bytes??e.content??``),o.update(`
|
|
28
28
|
`);return{name:r,description:i,skillMd:n,files:a,contentHash:o.digest(`hex`)}}function RD(e){if(H(z(e,`SKILL.md`)))return[{name:wl(e),dir:e}];let t=[],n=0,r=(e,i)=>{if(i>8||++n>5e3)return;if(H(z(e,`SKILL.md`))){t.push({name:wl(e),dir:e});return}let a;try{a=Jl(e,{withFileTypes:!0})}catch{return}for(let t of a)t.isDirectory()&&!Joe.has(t.name)&&r(z(e,t.name),i+1)};return r(e,0),t.sort((e,t)=>e.name.localeCompare(t.name))}function zD(e){let t=e?.skills;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.source==`string`&&t.source?t.source:void 0,i=typeof t.id==`string`&&t.id?t.id:r;!i||!r||n.push({id:i,name:typeof t.name==`string`&&t.name?t.name:jn(i),source:r,description:typeof t.description==`string`?t.description:``,installs:Number.isInteger(t.installs)&&t.installs>=0?t.installs:null,publisher:po(r)})}return n}const Xoe={"&":`&`,"<":`<`,">":`>`,""":`"`,"'":`'`,"'":`'`,"'":`'`};function Zoe(e){return e.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g,e=>Xoe[e]??e)}function Qoe(e){let t={},n=e.match(/<meta\b[^>]*>/gi)??[];for(let e of n){let n=e.match(/\bproperty\s*=\s*["'](og:[^"']+)["']/i)?.[1]?.toLowerCase();if(!n)continue;let r=e.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1];if(r==null)continue;let i=Zoe(r);n===`og:title`&&t.title==null?t.title=i:n===`og:description`&&t.description==null?t.description=i:n===`og:image`&&t.image==null&&(t.image=i)}return t}function $oe(e){let t=e?.items;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.full_name==`string`&&t.full_name?t.full_name:void 0;r&&n.push({id:r,name:typeof t.name==`string`&&t.name?t.name:jn(r),source:r,description:typeof t.description==`string`?t.description:``,installs:null,publisher:po(r)})}return n}function BD(e){return e.trim().toLowerCase()}function ese(e){return e.split(`/`).filter(Boolean).pop()??e}function VD(e){let t=Or(e.trim());if(t?.kind===`site`)return{hostname:t.hostname};let n=DD(e);if(!n)return null;let r=Or(n.owner);return r?.kind===`site`?{hostname:r.hostname,skill:n.skill}:null}async function HD(e,t,n={}){let r=VD(e);if(r){let e=t??r.skill;if(!e)throw new vD(`Website skill sources require a skill name.`);return{source:r.hostname,skill:e,publisher:r.hostname,spec:{kind:`well-known`,origin:`https://${r.hostname}`,skill:e}}}let i=DD(e);if(!i)return null;let a=n.fetchImpl??globalThis.fetch;if(!a)throw new vD(`No fetch implementation available.`);let o=t??i.skill,s=BD(o),c=BD(i.owner),l;try{let e=await a(`https://skills.sh/api/search?q=${encodeURIComponent(o)}&limit=30`,{signal:AbortSignal.timeout(n.timeoutMs??8e3)});if(!e.ok)throw new vD(`skills.sh lookup failed with HTTP ${e.status}`);l=await e.json()}catch(e){throw e instanceof vD?e:new vD(`skills.sh lookup failed: ${e instanceof Error?e.message:String(e)}`)}let u=zD(l).find(e=>{if((e.publisher?BD(e.publisher):``)!==c)return!1;let t=BD(e.name),n=BD(ese(e.id));return t===s||n===s});if(!u)throw new vD(`No skills.sh result matched ${i.owner}/${i.skill}`);let d=Or(u.source),f=d?.kind===`site`?{kind:`well-known`,origin:`https://${d.hostname}`,skill:t??u.name}:ED(u.source);if(!f||f.kind===`local`)throw new vD(`skills.sh returned an unsafe source for ${i.owner}/${i.skill}: ${u.source}`);return{source:u.source,skill:t??u.name,...u.publisher?{publisher:u.publisher}:{},spec:f}}const UD=[`agents`,`claude`,`cursor`,`codex`,`opencode`,`pi`,`copilot`];function WD(e){let t=UD.indexOf(e);return t===-1?UD.length:t}function GD(e){let t=new Map,n=new Map;for(let r of e){let e=`${r.scope}|${r.name}`,i=`${e}|${r.contentHash}`,a=t.get(i);a||(a=[],t.set(i,a)),a.push(r);let o=n.get(e);o||(o=new Set,n.set(e,o)),o.add(r.contentHash)}let r=[];for(let e of t.values()){let t=[...e].sort((e,t)=>{let n=Number(e.viaLink===!0)-Number(t.viaLink===!0);if(n!==0)return n;let r=Number(t.preferredSource===!0)-Number(e.preferredSource===!0);if(r!==0)return r;let i=WD(e.editor)-WD(t.editor);return i===0?e.editor.localeCompare(t.editor):i}),i=t[0];i&&r.push({name:i.name,scope:i.scope,contentHash:i.contentHash,canonical:i,copies:t.slice(1),isFork:(n.get(`${i.scope}|${i.name}`)?.size??1)>1})}return r.sort((e,t)=>e.scope.localeCompare(t.scope)||e.name.localeCompare(t.name)||e.contentHash.localeCompare(t.contentHash))}function KD(e){if(!H(e))return[];try{return Jl(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>z(e.parentPath,e.name)).sort()}catch{return[]}}function qD(e,t,n,r){let i=z(e,`SKILL.md`);if(!H(i))return null;let a=wl(e),o=a,s=``;try{({name:o,description:s}=ND(U(i,`utf-8`),a))}catch{}return{name:o,description:s,home:e,harness:t,skillMd:i,scripts:KD(z(e,`scripts`)),references:KD(z(e,`references`)),provenance:n,inert:r}}function JD(e){if(!H(e))return[];try{return Jl(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function tse(e){let t=e=>{try{return $l(e).isDirectory()}catch{return!1}};return{commands:t(z(e,`commands`)),hooks:t(z(e,`hooks`)),mcp:H(z(e,`.mcp.json`))}}const nse={commands:!1,hooks:!1,mcp:!1};function YD(e,t){let n=[];for(let r of JD(e)){let i=qD(z(e,r),t,{},nse);i&&n.push({packName:i.name,packVersion:`0.0.0`,harness:t,skills:[i]})}return n}function XD(e){try{return Jl(e).length>0}catch{return!1}}function rse(e){let t=new Set,n=(e,r)=>{if(r>4)return;let i;try{i=Jl(e,{withFileTypes:!0})}catch{return}if(H(z(e,`SKILL.md`))||H(z(e,`SKILL.mdx`))){t.add(e.split(`/`).pop()??e);return}for(let t of i)t.isDirectory()&&n(z(e,t.name),r+1)};return n(z(e,`skills`),0),[...t].sort()}function ise(e){return{commands:XD(z(e,`commands`)),hooks:XD(z(e,`hooks`))||H(z(e,`hooks.json`)),mcp:H(z(e,`.mcp.json`)),agents:XD(z(e,`agents`))}}function ase(e){let t=e.lastIndexOf(`@`);return t<=0?{plugin:e}:{plugin:e.slice(0,t),marketplace:e.slice(t+1)}}function ose(e){let t=new Map;for(let n of e){if(n.orphaned_at||!n.installPath||!H(n.installPath))continue;let e=`${n.scope??``} ${n.projectPath??``}`,r=t.get(e);(!r||(n.lastUpdated??``)>(r.lastUpdated??``))&&t.set(e,n)}return[...t.values()]}function sse(e){let t=z(e,`.claude-plugin`,`plugin.json`);try{let e=JSON.parse(U(t,`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function cse(e,t){let n=z(e,`installed_plugins.json`);if(!H(n))return[];let r;try{r=JSON.parse(U(n,`utf-8`))}catch(e){return console.warn(`[skills-catalog] failed to parse installed_plugins.json, skipping Claude plugins`,{manifestPath:n,err:e}),[]}let i=r?.plugins;if(!i||typeof i!=`object`)return[];let a=[];for(let[e,n]of Object.entries(i)){if(!Array.isArray(n))continue;let{plugin:r,marketplace:i}=ase(e);for(let e of ose(n)){let n=e.installPath,o=tse(n),s=sse(n),c=z(n,`skills`),l=[];for(let n of JD(c)){let a={plugin:r,...i?{marketplace:i}:{},...e.version?{version:e.version}:{},...e.gitCommitSha?{gitCommitSha:e.gitCommitSha}:{},...e.scope?{scope:e.scope}:{},...e.projectPath?{projectPath:e.projectPath}:{}},s=qD(z(c,n),t,a,o);s&&l.push(s)}l.length!==0&&a.push({packName:r,packVersion:e.version??s.version??`0.0.0`,...typeof s.description==`string`?{packDescription:s.description}:{},...typeof s.author?.name==`string`?{packAuthor:s.author.name}:{},harness:t,skills:l})}}return a}const ZD=/^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/,lse=/^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//,use=/^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;function QD(e){return e.replaceAll(`\\`,`/`).replace(/\/+$/,``)}function dse(e){let t=lse.exec(QD(e));if(!t)return null;try{let e=U(`${t[1]}/known_marketplaces.json`,`utf-8`),n=JSON.parse(e)[t[2]];return n?.source?.source===`github`&&n.source.repo?`https://github.com/${n.source.repo}`:null}catch{return null}}function $D(e,t){let n=V(e);try{$l(n).isDirectory()||(n=R(n))}catch{return null}let r=V(t);for(;n===r||n.startsWith(`${r}/`);){try{let e=JSON.parse(U(z(n,`.claude-plugin`,`plugin.json`),`utf-8`));if(typeof e.name==`string`&&e.name.length>0)return{name:e.name,...typeof e.version==`string`?{version:e.version}:{}}}catch{}if(n===r)break;n=R(n)}return null}function fse(e){let t=QD(e),n=ZD.exec(t);if(n){let t=$D(e,`${n[1]}/${n[4]}`);return!t||t.name!==n[3]?null:{plugin:n[3],marketplace:n[2],version:t.version??n[4]}}let r=use.exec(t);if(!r)return null;let i=$D(e,r[1]);return i?{plugin:i.name,marketplace:r[2],...i.version?{version:i.version}:{}}:null}function pse(e){return[...e].sort((e,t)=>e.localeCompare(t,void 0,{numeric:!0})).pop()}function mse(e){let t=QD(e),n=ZD.exec(t);if(!n)return e;let[r,i]=[n[1],n[4]],a=t.slice(n[0].indexOf(`/${i}`)+i.length+1),o;try{o=Jl(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return e}let s=pse(o);if(s===void 0||s===i)return e;let c=`${r}/${s}${a}`;return H(c)?c:e}function eO(e,t){for(let n of t)try{let t=JSON.parse(U(z(e,n),`utf-8`));if(typeof t.name==`string`&&t.name.length>0)return{plugin:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{}}}catch{}return null}function tO(e){let t=eO(e,[`.claude-plugin/plugin.json`]);if(t)return{...t,setupSupported:!0};try{let t=JSON.parse(U(z(e,`.claude-plugin`,`marketplace.json`),`utf-8`)),n=t.plugins?.find(e=>e.source===`./`)??t.plugins?.[0],r=typeof n?.name==`string`?n.name:t.name;if(typeof r==`string`&&r.length>0)return{plugin:r,...typeof n?.description==`string`?{description:n.description}:{},setupSupported:!0}}catch{}return null}const nO={id:`claude`,homes:e=>[{harness:`claude`,dir:z(e,`.claude`,`plugins`)}],enumerate:cse,inspectSource:fse,repositoryUrl:dse,resolveUpdateSource:mse,detectDir:tO};function rO(e,t){return{id:e,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let n=eO(e,t);return n?{...n,setupSupported:!1}:null}}}function iO(e,t){try{return JSON.parse(U(z(e,t),`utf-8`)).skills!==void 0}catch{return!1}}const aO=[nO,rO(`codex`,[`.codex-plugin/plugin.json`]),rO(`gemini`,[`gemini-extension.json`]),{id:`copilot`,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let t=eO(e,[`.plugin/plugin.json`,`.github/plugin/plugin.json`]);if(t)return{...t,setupSupported:!1};if(!iO(e,`plugin.json`))return null;let n=eO(e,[`plugin.json`]);return n?{...n,setupSupported:!1}:null}}];function oO(e){return aO.find(t=>t.id===e)}function sO(e){if(e===void 0)return aO;let t=oO(e);return t?[t]:[]}function cO(e){return aO.flatMap(t=>t.homes(e).map(e=>({provider:t.id,...e})))}function lO(e,t,n=e){let r=oO(e);if(!r)throw Error(`unknown plugin provider: ${e}`);return r.enumerate(t,n).map(t=>({...t,skills:t.skills.map(t=>({...t,provenance:{...t.provenance,pluginProvider:e}}))}))}function uO(e,t){for(let n of sO(t)){let t=n.inspectSource(e);if(!t)continue;let r=n.repositoryUrl(e);return{provider:n.id,...t,...r?{repositoryUrl:r}:{}}}return null}function dO(e){for(let t of aO){let n=t.detectDir(e);if(!n)continue;let r=rse(e);return r.length===0?null:{provider:t.id,plugin:n.plugin,...n.version?{version:n.version}:{},...n.description?{description:n.description}:{},bundledSkills:r,capabilities:ise(e),setupSupported:n.setupSupported}}return null}function fO(e,t){for(let n of sO(t)){if(!n.inspectSource(e))continue;let t=n.repositoryUrl(e);if(t)return t}return null}function pO(e,t){for(let n of sO(t))if(n.inspectSource(e))return n.resolveUpdateSource(e);return e}function mO(e=au()){let t=bo.flatMap(t=>{let n=Gn[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:z(e,...n.split(`/`))}]});return[...cO(e).map(e=>({kind:`plugin-provider`,...e})),...t,{harness:`agents`,kind:`skill-dir`,dir:z(e,`.agents`,`skills`)}]}function hO(e){return bo.flatMap(t=>{let n=Mt[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:z(e,...n.split(`/`))}]})}function gO(e){return Object.keys(e.provenance).length>0}function _O(e){return e.provenance.plugin!==void 0}function vO(e,t){if(_O(e)!==_O(t))return _O(e)?e:t;if(gO(e)!==gO(t))return gO(e)?e:t;let n=e.scripts.length+e.references.length;return t.scripts.length+t.references.length>n?t:e}function yO(e,t){return{name:e.name,description:e.description,files:{skillMd:e.skillMd,scripts:e.scripts,references:e.references},sourceHarness:e.harness,sourceHarnesses:t,home:e.home,provenance:e.provenance,inert:e.inert}}function bO(e){try{return LD(e.home)?.contentHash??`unreadable:${e.home}`}catch{return`unreadable:${e.home}`}}function xO(e){let t=new Map;for(let n of e){let e=Xe(n.provenance.scope),r=`${e}\0${e===`project`?n.provenance.projectPath??``:``}\0${n.name}\0${bO(n)}`,i=t.get(r);i?(i.winner=vO(i.winner,n),i.harnesses.add(n.harness)):t.set(r,{winner:n,harnesses:new Set([n.harness])})}return[...t.values()].map(({winner:e,harnesses:t})=>yO(e,[...t].sort())).sort((e,t)=>e.name.localeCompare(t.name)||Xe(e.provenance.scope).localeCompare(Xe(t.provenance.scope))||e.home.localeCompare(t.home))}function SO(e){let t=new Map;for(let n of e){let e=t.get(n.packName),r=e??{version:`0.0.0`,skills:new Set,hosts:new Set};r.version===`0.0.0`&&n.packVersion!==`0.0.0`&&(r.version=n.packVersion),!r.description&&n.packDescription&&(r.description=n.packDescription),!r.author&&n.packAuthor&&(r.author=n.packAuthor);for(let e of n.skills)r.skills.add(e.name);r.hosts.add(n.harness),e||t.set(n.packName,r)}return[...t.entries()].map(([e,t])=>({schema:1,name:e,version:t.version,...t.description?{description:t.description}:{},...t.author?{author:{name:t.author}}:{},skills:[...t.skills].sort(),hostCompatibility:[...t.hosts].sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function CO(e={}){let t=[];for(let n of mO(e.home))try{switch(n.kind){case`plugin-provider`:t.push(...lO(n.provider,n.dir,n.harness));break;case`skill-dir`:t.push(...YD(n.dir,n.harness));break;default:throw Error(`unhandled harness home kind: ${String(n)}`)}}catch(e){console.warn(`[skills-catalog] failed to enumerate harness home, skipping`,{harness:n.harness,dir:n.dir,err:e})}e.projectDir!==void 0&&t.push(...wO(e.projectDir));let n=e.projectDir===void 0?t:t.map(t=>({...t,skills:t.skills.filter(t=>ro(t.provenance,e.projectDir))})).filter(e=>e.skills.length>0);return{skills:xO(n.flatMap(e=>e.skills)),packs:SO(n)}}function wO(e){let t=DO(V(e,`.ok`,`skills`)),n=[];for(let r of hO(e))try{for(let i of YD(r.dir,r.harness)){let r=i.skills.filter(e=>!EO(e,t));r.length!==0&&n.push({...i,skills:r.map(t=>TO(t,e))})}}catch(e){console.warn(`[skills-catalog] failed to enumerate project harness skills, skipping`,{harness:r.harness,dir:r.dir,err:e})}return n}function TO(e,t){return{...e,provenance:{...e.provenance,scope:`project`,projectPath:t}}}function EO(e,t){if(e.name.startsWith(`open-knowledge`))return!0;let n=DO(e.home);return n===t||n.startsWith(t+Al)}function DO(e){try{return W(e)}catch{return V(e)}}function OO(e){if(!e.includes(`self.__next_f`))return e;let t=/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g,n=``;for(let r of e.matchAll(t))n+=JSON.parse(r[1]);return n}const kO=[`skillId`,`source`,`installs`];function AO(e){let t={};if(e.length>8192)return t;let n=new Uint8Array(e.length),r=0,i=!1,a=!1;for(let t=0;t<e.length;t++){n[t]=Math.min(r,255);let o=e[t];if(a){a=!1;continue}if(o===`\\`){a=i;continue}if(o===`"`){i=!i;continue}i||(o===`{`||o===`[`?r++:(o===`}`||o===`]`)&&r--)}for(let r of e.matchAll(/"(skillId|source|installs)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)/g)){let e=r[1];if(r.index===void 0||n[r.index]!==1||e in t)continue;let i=r[2];t[e]=i.startsWith(`"`)?JSON.parse(i):Number(i)}return t}function*jO(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){r=!1;continue}if(a===`\\`){r=n;continue}if(a===`"`){n=!n;continue}if(!n){if(a===`{`)t.push(i);else if(a===`}`){let n=t.pop();if(n===void 0)continue;let r=e.slice(n,i+1);if(!kO.every(e=>r.includes(`"${e}"`)))continue;try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)){yield e;continue}}catch{}yield AO(r)}}}}function MO(e){let t=OO(e),n=[];for(let e of jO(t)){let{skillId:t,source:r,installs:i}=e;typeof t!=`string`||t===``||typeof r!=`string`||r===``||typeof i!=`number`||!Number.isFinite(i)||n.push({skillId:t,source:r,installs:i})}return n}function NO(e){let t=new Map;for(let n of MO(e)){let e=`${n.source}/${n.skillId}`;t.has(e)||t.set(e,{id:e,name:n.skillId,source:n.source,description:``,installs:n.installs,publisher:po(n.source)})}return[...t.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}function PO(e,t){return`${e}/${t}`}function FO(e){if(e.preferredSource===!0)return-1;let t=UD.indexOf(e.editor);return t===-1?UD.length:t}function IO(e){let t=GD(e),n=new Set,r=new Map,i=new Set,a=new Map;for(let e of t){n.add(e.canonical.dir);for(let t of e.copies)i.add(t.dir);let t=PO(e.scope,e.name),o=FO(e.canonical),s=a.get(t);(s===void 0||o<s)&&(a.set(t,o),r.set(t,e.canonical.dir))}return{admittedDirs:n,canonicalDir:r,excludedCopyDirs:i}}var LO=n(((e,t)=>{function n(e){if(e.length===0)return;let t=Object.create(null),n=0;for(;n<e.length;++n){let t=e.charCodeAt(n);if(u[t]!==1){if(t!==47||n===0)return;break}}if(n===e.length)return;let i=e.slice(0,n).toLowerCase(),a=++n;for(;n<e.length;++n)if(u[e.charCodeAt(n)]!==1){if(n===a||r(e,n,t)===void 0)return;break}if(n!==a)return{type:i,subtype:e.slice(a,n).toLowerCase(),params:t}}function r(e,t,n){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let r,i=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n!==61)return;break}}if(t===e.length||(r=e.slice(i,t),++t,t===e.length))return;let a=``,o;if(e.charCodeAt(t)===34){o=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(o=t,n=!1):(a+=e.slice(o,t),n=!0);continue}if(r===34){if(n){o=t,n=!1;continue}a+=e.slice(o,t);break}if(n&&=(o=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(o=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===o)return;break}a=e.slice(o,t)}r=r.toLowerCase(),n[r]===void 0&&(n[r]=a)}return n}function i(e,t){if(e.length===0)return;let n=Object.create(null),r=0;for(;r<e.length;++r)if(u[e.charCodeAt(r)]!==1){if(a(e,r,n,t)===void 0)return;break}return{type:e.slice(0,r).toLowerCase(),params:n}}function a(e,t,n,r){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let i,a=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n===61)break;return}}if(t===e.length)return;let o=``,s,l;if(i=e.slice(a,t),i.charCodeAt(i.length-1)===42){let n=++t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(f[n]!==1){if(n!==39)return;break}}if(t===e.length)return;for(l=e.slice(n,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;s=t;let r=0;for(;t<e.length;++t){let n=e.charCodeAt(t);if(p[n]!==1){if(n===37){let n,i;if(t+2<e.length&&(n=m[e.charCodeAt(t+1)])!==-1&&(i=m[e.charCodeAt(t+2)])!==-1){let a=(n<<4)+i;o+=e.slice(s,t),o+=String.fromCharCode(a),t+=2,s=t+1,a>=128?r=2:r===0&&(r=1);continue}return}break}}if(o+=e.slice(s,t),o=c(o,l,r),o===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){s=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(s=t,n=!1):(o+=e.slice(s,t),n=!0);continue}if(r===34){if(n){s=t,n=!1;continue}o+=e.slice(s,t);break}if(n&&=(s=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(s=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===s)return;break}o=e.slice(s,t)}if(o=r(o,2),o===void 0)return}i=i.toLowerCase(),n[i]===void 0&&(n[i]=o)}return n}function o(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return s.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return s.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return s.utf16le;case`base64`:return s.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return s.other.bind(e)}}let s={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function c(e,t,n){let r=o(t);if(r)return r(e,n)}function l(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:l,convertToUTF8:c,getDecoder:o,parseContentType:n,parseDisposition:i}})),RO=n(((e,t)=>{function n(e,t,n,r,i){for(let a=0;a<i;++a)if(e[t+a]!==n[r+a])return!1;return!0}var r=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let n=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(n),this._occ=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let t=0;t<n-1;++t)this._occ[e[t]]=n-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let n;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let r=e.length;for(this._bufPos=t||0;n!==r&&this.matches<this.maxMatches;)n=i(this,e);return n}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function i(e,t){let r=t.length,i=e._needle,o=i.length,s=-e._lookbehindSize,c=o-1,l=i[c],u=r-o,d=e._occ,f=e._lookbehind;if(s<0){for(;s<0&&s<=u;){let n=s+c,r=n<0?f[e._lookbehindSize+n]:t[n];if(r===l&&a(e,t,s,c))return e._lookbehindSize=0,++e.matches,s>-e._lookbehindSize?e._cb(!0,f,0,e._lookbehindSize+s,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<0&&!a(e,t,s,r-s);)++s;if(s<0){let n=e._lookbehindSize+s;return n>0&&e._cb(!1,f,0,n,!1),e._lookbehindSize-=n,f.copy(f,0,n,e._lookbehindSize),f.set(t,e._lookbehindSize),e._lookbehindSize+=r,e._bufPos=r,r}e._cb(!1,f,0,e._lookbehindSize,!1),e._lookbehindSize=0}s+=e._bufPos;let p=i[0];for(;s<=u;){let r=t[s+c];if(r===l&&t[s]===p&&n(i,0,t,s,c))return++e.matches,s>0?e._cb(!0,t,e._bufPos,s,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<r;){if(t[s]!==p||!n(t,s,i,0,r-s)){++s;continue}t.copy(f,0,s,r),e._lookbehindSize=r-s;break}return s>0&&e._cb(!1,t,e._bufPos,s<r?s:r,!0),e._bufPos=r,r}function a(e,t,n,r){let i=e._lookbehind,a=e._lookbehindSize,o=e._needle;for(let e=0;e<r;++e,++n)if((n<0?i[a+n]:t[n])!==o[e])return!1;return!0}t.exports=r})),zO=n(((t,n)=>{let{Readable:r,Writable:i}=e(`stream`),a=RO(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=LO(),d=Buffer.from(`\r
|
|
29
29
|
`),f=Buffer.from(`\r`),p=Buffer.from(`-`);function m(){}let h=16*1024;var g=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,n){let r=t;for(;t<n;)switch(this.state){case 0:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(w[n]!==1){if(n!==58||(this.name+=e.latin1Slice(r,t),this.name.length===0))return-1;++t,i=!0,this.state=1;break}}if(!i){this.name+=e.latin1Slice(r,t);break}}case 1:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(n!==32&&n!==9){r=t,i=!0,this.state=2;break}}if(!i)break}case 2:switch(this.crlf){case 0:for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(T[n]!==1){if(n!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(r,t++);break;case 1:if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];n===32||n===9?(r=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),n===13?(++this.crlf,++t):(r=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;let n=this.header;return this.reset(),this.cb(n),t}}break}return t}},_=class extends r{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let v={push:(e,t)=>{},destroy:()=>{}};function y(e,t){let n=e._writecb;e._writecb=null,t?e.destroy(t):n&&n()}function b(e,t){return e}var x=class extends i{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let n=e.conType.params.boundary,r=typeof e.defParamCharset==`string`&&e.defParamCharset?c(e.defParamCharset):b,i=e.defCharset||`utf8`,h=e.preservePath,y={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},x=e.limits,S=x&&typeof x.fieldSize==`number`?x.fieldSize:1*1024*1024,C=x&&typeof x.fileSize==`number`?x.fileSize:1/0,w=x&&typeof x.files==`number`?x.files:1/0,T=x&&typeof x.fields==`number`?x.fields:1/0,ee=x&&typeof x.parts==`number`?x.parts:1/0,te=-1,ne=0,re=0,ie=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let E=0,D,ae=0,O,oe,se,k,ce=!1,le=!1,ue=!1;this._hparser=null;let de=new g(e=>{this._hparser=null,ie=!1,se=`text/plain`,O=i,oe=`7bit`,k=void 0,ce=!1;let t;if(!e[`content-disposition`]){ie=!0;return}let n=u(e[`content-disposition`][0],r);if(!n||n.type!==`form-data`){ie=!0;return}if(n.params&&(n.params.name&&(k=n.params.name),n.params[`filename*`]?t=n.params[`filename*`]:n.params.filename&&(t=n.params.filename),t!==void 0&&!h&&(t=o(t))),e[`content-type`]){let t=l(e[`content-type`][0]);t&&(se=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(O=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(oe=e[`content-transfer-encoding`][0].toLowerCase()),se===`application/octet-stream`||t!==void 0){if(re===w){le||(le=!0,this.emit(`filesLimit`)),ie=!0;return}if(++re,this.listenerCount(`file`)===0){ie=!0;return}E=0,this._fileStream=new _(y,this),++this._fileEndsLeft,this.emit(`file`,k,this._fileStream,{filename:t,encoding:oe,mimeType:se})}else{if(ne===T){ue||(ue=!0,this.emit(`fieldsLimit`)),ie=!0;return}if(++ne,this.listenerCount(`field`)===0){ie=!0;return}D=[],ae=0}}),fe=0,A=(e,t,n,r,i)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,n,r);if(e===-1){this._hparser=null,de.reset(),this.emit(`error`,Error(`Malformed part header`));break}n=e}if(n===r)break;if(fe!==0){if(fe===1){switch(t[n]){case 45:fe=2,++n;break;case 13:fe=3,++n;break;default:fe=0}if(n===r)return}if(fe===2){if(fe=0,t[n]===45){this._complete=!0,this._bparser=v;return}let e=this._writecb;this._writecb=m,A(!1,p,0,1,!1),this._writecb=e}else if(fe===3)if(fe=0,t[n]===10){if(++n,te>=ee||(this._hparser=de,n===r))break;continue retrydata}else{let e=this._writecb;this._writecb=m,A(!1,f,0,1,!1),this._writecb=e}}if(!ie){if(this._fileStream){let e,a=Math.min(r-n,C-E);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),E+=e.length,E===C?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,ie=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(D!==void 0){let e,a=Math.min(r-n,S-ae);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),ae+=a,D.push(e),ae===S&&(ie=!0,ce=!0)}}break}if(e){if(fe=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(D!==void 0){let e;switch(D.length){case 0:e=``;break;case 1:e=s(D[0],O,0);break;default:e=s(Buffer.concat(D,ae),O,0)}D=void 0,ae=0,this.emit(`field`,k,e,{nameTruncated:!1,valueTruncated:ce,encoding:oe,mimeType:se})}++te===ee&&this.emit(`partsLimit`)}};this._bparser=new a(`\r\n--${n}`,A),this._writecb=null,this._finalcb=null,this.write(d)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,n){this._writecb=n,this._bparser.push(e,0),this._writecb&&y(this)}_destroy(e,t){this._hparser=null,this._bparser=v,e||=C(this);let n=this._fileStream;n&&(this._fileStream=null,n.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=S.bind(null,this,e):S(this,e)}};function S(e,t,n){if(n)return t(n);n=C(e),t(n)}function C(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let w=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];n.exports=x})),BO=n(((t,n)=>{let{Writable:r}=e(`stream`),{getDecoder:i}=LO();var a=class extends r{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let n=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(n=e.conType.params.charset),this.charset=n;let r=e.limits;this.fieldSizeLimit=r&&typeof r.fieldSize==`number`?r.fieldSize:1*1024*1024,this.fieldsLimit=r&&typeof r.fields==`number`?r.fields:1/0,this.fieldNameSizeLimit=r&&typeof r.fieldNameSize==`number`?r.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=i(n)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,n){if(this._fields>=this.fieldsLimit)return n();let r=0,i=e.length;if(this._lastPos=0,this._byte!==-2){if(r=o(this,e,r,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;r<i;)if(this._inKey){for(r=s(this,e,r,i);r<i;){switch(e[r]){case 61:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue;case 43:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._key+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesKey,r=s(this,e,r,i);continue}++r,++this._bytesKey,r=s(this,e,r,i)}this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r))}else{for(r=c(this,e,r,i);r<i;){switch(e[r]){case 38:if(this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue main;case 43:this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._val+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesVal,r=c(this,e,r,i);continue}++r,++this._bytesVal,r=c(this,e,r,i)}this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r))}n()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function o(e,t,n,r){if(n>=r)return r;if(e._byte===-1){let i=l[t[n++]];if(i===-1)return-1;if(i>=8&&(e._encode=2),n<r){let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((i<<4)+r):e._val+=String.fromCharCode((i<<4)+r),e._byte=-2,e._lastPos=n}else e._byte=i}else{let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+r):e._val+=String.fromCharCode((e._byte<<4)+r),e._byte=-2,e._lastPos=n}return n}function s(e,t,n,r){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<n&&(e._key+=t.latin1Slice(e._lastPos,n-1)),e._keyTrunc=!0;n<r;++n){let r=t[n];if(r===61||r===38)break;++e._bytesKey}e._lastPos=n}return n}function c(e,t,n,r){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<n&&(e._val+=t.latin1Slice(e._lastPos,n-1)),e._valTrunc=!0;n<r&&t[n]!==38;++n)++e._bytesVal;e._lastPos=n}return n}let l=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];n.exports=a})),VO=t(n(((e,t)=>{let{parseContentType:n}=LO();function r(e){let t=e.headers,r=n(t[`content-type`]);if(!r)throw Error(`Malformed content type`);for(let n of i){if(!n.detect(r))continue;let i={limits:e.limits,headers:t,conType:r,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(i.highWaterMark=e.highWaterMark),e.fileHwm&&(i.fileHwm=e.fileHwm),i.defCharset=e.defCharset,i.defParamCharset=e.defParamCharset,i.preservePath=e.preservePath,new n(i)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let i=[zO(),BO()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return r(e)}}))(),1);const HO={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},UO={};for(let[e,t]of Object.entries(HO))UO[t]=Number.parseInt(e,10);let WO;function GO(){if(globalThis.TextDecoder!==void 0)return WO??=new globalThis.TextDecoder(`utf-8`)}const KO=32*1024,qO=65533;function JO(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=GO();return t?t.decode(e):QO(e)}case`utf-16le`:return $O(e);case`us-ascii`:case`ascii`:return ek(e);case`latin1`:case`iso-8859-1`:return tk(e);case`windows-1252`:return nk(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function YO(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function XO(e,t,n){t.push(n),t.length>=KO&&YO(e,t)}function ZO(e,t,n){if(n<=65535){XO(e,t,n);return}n-=65536,XO(e,t,55296+(n>>10)),XO(e,t,56320+(n&1023))}function QO(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r<e.length;){let i=e[r];if(i<=127){XO(t,n,i),r++;continue}if(i<194||i>244){XO(t,n,qO),r++;continue}if(i<=223){if(r+1>=e.length){XO(t,n,qO),r++;continue}let a=e[r+1];if((a&192)!=128){XO(t,n,qO),r++;continue}XO(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){XO(t,n,qO),r++;continue}let a=e[r+1],o=e[r+2];if(!((a&192)==128&&(o&192)==128&&!(i===224&&a<160)&&!(i===237&&a>=160))){XO(t,n,qO),r++;continue}XO(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){XO(t,n,qO),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if(!((a&192)==128&&(o&192)==128&&(s&192)==128&&!(i===240&&a<144)&&!(i===244&&a>143))){XO(t,n,qO),r++;continue}ZO(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return YO(t,n),t.join(``)}function $O(e){let t=[],n=[],r=e.length,i=0;for(;i+1<r;){let a=e[i]|e[i+1]<<8;if(i+=2,a>=55296&&a<=56319){if(i+1<r){let r=e[i]|e[i+1]<<8;r>=56320&&r<=57343?(XO(t,n,a),XO(t,n,r),i+=2):XO(t,n,qO)}else XO(t,n,qO);continue}if(a>=56320&&a<=57343){XO(t,n,qO);continue}XO(t,n,a)}return i<r&&XO(t,n,qO),YO(t,n),t.join(``)}function ek(e){let t=[];for(let n=0;n<e.length;n+=KO){let r=Math.min(e.length,n+KO),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t]&127;t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function tk(e){let t=[];for(let n=0;n<e.length;n+=KO){let r=Math.min(e.length,n+KO),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t];t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function nk(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?HO[i]:void 0;n+=a??String.fromCharCode(i),n.length>=KO&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function rk(e){return new DataView(e.buffer,e.byteOffset)}const ik={len:1,get(e,t){return rk(e).getUint8(t)},put(e,t,n){return rk(e).setUint8(t,n),t+1}},ak={len:2,get(e,t){return rk(e).getUint16(t,!0)},put(e,t,n){return rk(e).setUint16(t,n,!0),t+2}},ok={len:2,get(e,t){return rk(e).getUint16(t)},put(e,t,n){return rk(e).setUint16(t,n),t+2}},sk={len:4,get(e,t){return rk(e).getUint32(t,!0)},put(e,t,n){return rk(e).setUint32(t,n,!0),t+4}},ck={len:4,get(e,t){return rk(e).getUint32(t)},put(e,t,n){return rk(e).setUint32(t,n),t+4}},lk={len:4,get(e,t){return rk(e).getInt32(t)},put(e,t,n){return rk(e).setInt32(t,n),t+4}},uk={len:8,get(e,t){return rk(e).getBigUint64(t,!0)},put(e,t,n){return rk(e).setBigUint64(t,n,!0),t+8}};var dk=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return JO(e.subarray(t,t+this.len),this.encoding)}},fk=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},pk=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},mk=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new fk;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new pk;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new fk;return n}},hk=class extends mk{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},gk=class extends hk{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},_k=class extends mk{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new fk;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function vk(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new _k(t):new gk(t)}catch(t){if(t instanceof TypeError)return new _k(e.getReader());throw t}}var yk=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new fk;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new fk;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new fk;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new fk;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},bk=class extends yk{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new fk;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof fk)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new fk}return r}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},xk=class extends yk{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new fk;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},Sk=class extends yk{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new fk;let i=await this.blob.slice(n.position,n.position+r).arrayBuffer();return e.set(new Uint8Array(i)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function Ck(e,t){let n=vk(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new bk(n,r)}function wk(e,t){return new xk(e,t)}function Tk(e,t){return new Sk(e,t)}var Ek=t(bs(),1);const Dk={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Ok={get(e){return{signature:sk.get(e,0),compressedSize:sk.get(e,8),uncompressedSize:sk.get(e,12)}},len:16},kk={get(e){let t=ak.get(e,6);return{signature:sk.get(e,0),minVersion:ak.get(e,4),dataDescriptor:!!(t&8),compressedMethod:ak.get(e,8),compressedSize:sk.get(e,18),uncompressedSize:sk.get(e,22),filenameLength:ak.get(e,26),extraFieldLength:ak.get(e,28),filename:null}},len:30},Ak={get(e){return{signature:sk.get(e,0),nrOfThisDisk:ak.get(e,4),nrOfThisDiskWithTheStart:ak.get(e,6),nrOfEntriesOnThisDisk:ak.get(e,8),nrOfEntriesOfSize:ak.get(e,10),sizeOfCd:sk.get(e,12),offsetOfStartOfCd:sk.get(e,16),zipFileCommentLength:ak.get(e,20)}},len:22},jk={get(e){let t=ak.get(e,8);return{signature:sk.get(e,0),minVersion:ak.get(e,6),dataDescriptor:!!(t&8),compressedMethod:ak.get(e,10),compressedSize:sk.get(e,20),uncompressedSize:sk.get(e,24),filenameLength:ak.get(e,28),extraFieldLength:ak.get(e,30),fileCommentLength:ak.get(e,32),relativeOffsetOfLocalHeader:sk.get(e,42),filename:null}},len:46};function Mk(e){let t=new Uint8Array(sk.len);return sk.put(t,0,e),t}const Nk=(0,Ek.default)(`tokenizer:inflate`),Pk=256*1024,Fk=Mk(Dk.DataDescriptor),Ik=Mk(Dk.EndOfCentralDirectory);var Lk=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Pk)}async isZip(){return await this.peekSignature()===Dk.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(sk)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===Ik[0]&&n[r+1]===Ik[1]&&n[r+2]===Ik[2]&&n[r+3]===Ik[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Nk(`Cannot reading central-directory without random-read support`);return}Nk(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Nk(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Ak,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(jk);if(t.signature!==Dk.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new dk(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),Nk(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=Pk;Nk(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===Pk;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=Rk(this.syncBuffer.subarray(0,n),Fk);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}Nk(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,zk(e),r.handler)}else r.handler?(Nk(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(Nk(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Nk(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Ok)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Ok.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}async inflate(t,n,r){if(t.compressedMethod===0)return r(n);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return Nk(`Decompress filename=${t.filename}, compressed-size=${n.length}`),r(await e.decompressDeflateRaw(n))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=new DecompressionStream(`deflate-raw`),r=t.pipeThrough(n);try{let e=await new Response(r).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(sk);if(e===Dk.LocalFileHeader){let e=await this.tokenizer.readToken(kk);return e.filename=await this.tokenizer.readToken(new dk(e.filenameLength,`utf-8`)),e}if(e===Dk.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function Rk(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function zk(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Bk=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),r=await e.readBuffer(n,{mayBeLess:!0});if(r===0){t.close();return}t.enqueue(n.subarray(0,r))}}).pipeThrough(new DecompressionStream(`gzip`))}};const Vk=Object.prototype.toString;function Hk(e,t,n){return e?e.constructor===t?!0:Vk.call(e)===n:!1}function Uk(e){return Hk(e,Uint8Array,`[object Uint8Array]`)}function Wk(e){if(!Uk(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function Gk(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)Wk(t),n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Kk(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function qk(e,t){if(t===`utf-16le`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r&255,r>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r>>8&255,r&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function Jk(e,t=0){let n=Number.parseInt(new dk(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}const Yk={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},Xk=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),Zk=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),Qk=16*1024*1024;var $k=class extends Error{};function eA(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new $k(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function tA(e,t,{maximumLength:n=Qk,reason:r=`skip`}={}){let i=eA(t,n,r);await e.ignore(i)}async function nA(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=eA(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function rA(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}function iA(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function aA(e,t,n){return iA(e)&&e.position-t>n}const oA=1024*1024,sA=1024,cA=2**31-1,lA=oA,uA=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),dA=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],fA=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function pA(e,{maximumLength:t=oA}={}){let n=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.length,i>t)throw await n.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);r.push(a)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.length;return a}function mA(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function hA(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,cA)}function gA(e){if(e instanceof fk||e instanceof $k)return!0;if(!(e instanceof Error))return!1;if(uA.has(e.message)||fA.has(e.code))return!0;for(let t of dA)if(e.message.startsWith(t))return!0;return!1}function _A(e,t=oA){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function vA(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function yA(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function bA(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function xA(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function SA(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function CA(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function wA(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function TA(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return wA(e)}function EA(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let n=e.slice(0,t),r=n.lastIndexOf(`"`);return n.slice(r+1)}const DA=134695760;function OA(e,t){if(e.length<16)return-1;let n=e.length-16;for(let r=0;r<=n;r++)if(sk.get(e,r)===DA&&sk.get(e,r+8)===t+r)return r;return-1}async function kA(e,{shouldBuffer:t,maximumLength:n=oA}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=OA(r.subarray(0,s),o),l=c>=0?0:s===i?Math.min(15,s-1):0,u=c>=0?c:s-l;if(u===0)break;if(o+=u,o>n)throw Error(`ZIP entry compressed data exceeds ${n} bytes`);if(t){let t=new Uint8Array(u);await e.tokenizer.readBuffer(t),a.push(t)}else await e.tokenizer.ignore(u);if(c>=0)break}if(iA(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return mA(a,o)}function AA(e,t){return iA(e.tokenizer)?Math.max(0,Qk-(e.tokenizer.position-t)):Math.max(0,oA-e.knownSizeDescriptorScannedBytes)}async function jA(e,t,{shouldBuffer:n,maximumDescriptorLength:r=oA}={}){if(t.dataDescriptor&&t.compressedSize===0)return kA(e,{shouldBuffer:n,maximumLength:r});if(!n){await tA(e.tokenizer,t.compressedSize,{maximumLength:iA(e.tokenizer)?oA:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=hA(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>i)throw Error(`ZIP entry compressed data exceeds ${i} bytes`);let a=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(a),a}Lk.prototype.inflate=async function(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return n(await pA(t,{maximumLength:oA}))},Lk.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(aA(this.tokenizer,r,16777216))throw new $k(`ZIP stream probing exceeds ${Qk} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>sA)throw Error(`ZIP entry count exceeds ${sA}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await jA(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(oA,AA(this,r))});if(a.handler&&await this.inflate(i,o,a.handler),i.dataDescriptor){let e=new Uint8Array(16);if(await this.tokenizer.readBuffer(e),sk.get(e,0)!==DA)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(aA(this.tokenizer,r,16777216))throw new $k(`ZIP stream probing exceeds ${Qk} bytes`)}while(!t)};async function MA(e){let t,n=SA(),r=vA();try{await new Lk(e).unzip(e=>{if(CA(n,e.filename),yA(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=bA(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=TA(n);if(!i&&a)return t=a,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return _A(e,lA)?{async handler(e){t=xA(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,_A(e,lA)?(n.isParsingContentTypes=!0,{async handler(e){let r=EA(new TextDecoder(`utf-8`).decode(e));r&&(t=xA(r)),n.hasParsedContentTypesEntry=!0,n.isParsingContentTypes=!1},stop:!0}):(n.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!gA(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof fk&&!n.hasContentTypesEntry&&(t=wA(n))}let i=iA(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:bA(r);return t??TA(n)??i??{ext:`zip`,mime:`application/zip`}}const NA=1024*1024;async function PA(e){async function t(){let t=await e.peekNumber(ik),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await nA(e,i,void 0,{maximumLength:i.length,reason:`EBML field`}),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:Kk(i),len:Kk(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>256||aA(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>64)return;let t=eA(o.len,64,`EBML DocType`);return(await e.readToken(new dk(t))).replaceAll(/\0.*$/gv,``)}if(iA(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>NA)||(await tA(e,o.len,{maximumLength:iA(e)?NA:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=i))return}}let i=await n(),a=e.position;switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const FA=1024*1024;function IA(e){return(e.codePointAt(0)&32)!=0}async function LA(e){let t={ext:`png`,mime:`image/png`},n={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function r(){return{length:await e.readToken(lk),type:await e.readToken(new dk(4,`latin1`))}}let i=iA(e),a=e.position,o=0,s=!1;do{if(o++,o>512||aA(e,a,16777216))break;let c=e.position,l=await r();if(l.length<0)return;if(l.type===`IHDR`){if(l.length!==13)return;s=!0}switch(l.type){case`IDAT`:return t;case`acTL`:return n;default:if(!s&&l.type!==`CgBI`)return;if(i&&l.length>FA)return s&&IA(l.type)?t:void 0;try{await tA(e,l.length+4,{maximumLength:i?FA+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof $k||e instanceof fk))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}const RA=1024*1024;async function zA(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await nA(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(uk))}}await tA(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=iA(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>512||aA(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(rA(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(o-=await nA(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),rA(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(rA(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(r&&o>RA){t=!0;break}if(await tA(e,o,{maximumLength:r?RA:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof fk||n instanceof $k)iA(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const BA=4100;BA-2;const VA=Qk,HA=Qk;function UA(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):BA}function WA(e){return Number.isFinite(e)?Math.max(0,Math.min(4098,Math.trunc(e))):0}function GA(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function KA(e){return import(e)}function qA(e){return e.pipeThrough(new TransformStream)}function JA(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((n,r)=>{t.addEventListener(`abort`,()=>{r(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function YA(e,t){let n=e.getReader(),r=0,i=!1,a=!1,o=async e=>{i||a||(a=!0,await n.cancel(e))};return new ReadableStream({async pull(e){if(r>=t){e.close(),await o();return}let{done:a,value:s}=await n.read();if(a||!s){i=!0,e.close();return}let c=t-r;if(s.length>c){e.enqueue(s.subarray(0,c)),r+=c,e.close(),await o();return}e.enqueue(s),r+=s.length},async cancel(e){await o(e)}})}async function XA(e,t){return new ZA(t).fromBuffer(e)}var ZA=class e{constructor(e){let t=WA(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return Ck(qA(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let t of this.detectors){let r;try{r=await t.detect(e)}catch(e){if(e instanceof fk||e instanceof $k)return;throw e}if(r)return r;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(wk(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=Tk(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([KA(`node:fs/promises`),KA(`strtok3`)]),r=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await r.stat();if(!i.isFile()){await r.close();return}let a=new n(r,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(a)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=UA(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await JA(a,this.options.signal);if(t||!e){i=!0;break}o.push(e),s+=e.length}if(!i&&s===n){let{value:e,done:t}=await JA(a,this.options.signal);t||!e?i=!0:(o.push(e),s+=e.length)}}finally{a.releaseLock()}if(s>0){let e=o.length===1?o[0]:Gk(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof fk))throw e;r=void 0}!i&&r?.ext===`pages`&&(r={ext:`zip`,mime:`application/zip`})}let c=new TransformStream({start(e){for(let t of o)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),l=e.pipeThrough(c);return l.fileType=r,l}async detectGzip(t){if(this.gzipProbeDepth>=1)return{ext:`gz`,mime:`application/gzip`};let n=YA(new Bk(t).inflate(),16777216),r=iA(t),i,a,o,s;if(r){let t=new AbortController;i=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after 100 ms`,`TimeoutError`))},100),a=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),o=new e({...this.options,signal:a}),o.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(o??this).fromStream(n)}catch(e){if(e?.name===`AbortError`&&a?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(i),r||this.gzipProbeDepth--}return s?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return rA(this.buffer,e,t)}checkString(e,t){return this.check(qk(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(BA),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,iA(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await tA(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(Yk),n=iA(e);if(!Number.isFinite(t)||t<0||n&&(t>VA||e.position+t>VA))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await tA(e,t,{maximumLength:n?VA:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof fk)return;throw e}return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return MA(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),rA(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:rA(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:rA(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:rA(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:rA(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:rA(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return PA(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=ck.get(this.buffer,4),t=ok.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new dk(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new dk(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
30
30
|
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return LA(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new dk(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
|
|
@@ -1212,7 +1212,7 @@ tags: [lore, history]
|
|
|
1212
1212
|
`:``)+t).md;Xx(b.dc.document,i,`agent`,void 0,S),UC(`mcp-write`),ee=!0}T=!0},b.origin)})}finally{ce?.touchMode(c,`idle`)}if(w){let e;switch(w.kind){case`invalid_value`:e={[w.key]:w.reason};break;case`reserved_key`:e={[w.key]:`'${w.key}' is reserved`};break;case`unknown_key`:e={[w.key]:`'${w.key}' is not a recognized key`};break;case`duplicate_target`:e={[w.key]:`'${w.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${w.expected.join(`, `)}; got: ${w.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${w.bytes} > ${w.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${w.reason}`};break;case`invalid_path`:e={[w.path.map(String).join(`.`)||`__path__`]:w.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(w)})`}}q(r,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(T&&te.length>0){if(tF(a,c,u,d,void 0,Zn({clientName:f,clientVersion:p,label:m}),y),hS(),er(_),ee){let e=await Jt(a);if(e?.kind===`failure`){Xt(r,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Zt(r,`frontmatter-patch`);return}}Wt(a,`frontmatter-patch`)}k?.setFocus(c,{agentName:u,currentDoc:a,writeKind:`write`,ts:Date.now()}),le?.();let ne=zt(a),re=Vt();re===0&&iX().add(1,{"shadow.writer":`agent`,"agent.type":Zh(f)});let ie=$t(x);mn(a,b.dc.document.getText(`source`).toString());let E=await tn();E.add(a);let D=iH(b.dc.document.getText(`source`).toString(),a,E,pn);Y(r,200,zee,{timestamp:C,subscriberCount:ne,systemSubscriberCount:re,appliedKeys:te,...v?{summary:v}:{},...ie?{warning:ie,warnings:[ie]}:{},brokenLinks:D},{handler:`frontmatter-patch`})}catch(e){if(e instanceof ZT){q(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e,requestId:CC(n)},`[frontmatter-patch] handler failed`),q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Or(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 Mr=J(oo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!kZ(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let r=It(n);if(fC(r)||pC(r)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`document-read`});return}let i=o.documents.get(r);if(i){Y(t,200,Nn,{docName:r,content:i.getText(`source`).toString(),lifecycle:Or(i)},{handler:`document-read`});return}if(!H(nZ(l,`file`,r))){q(t,404,`urn:ok:error:doc-not-found`,`Document not found: ${r}.`,{handler:`document-read`});return}let a=await o.openDirectConnection(r);try{let e=a.document;if(!e){q(t,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}Y(t,200,Nn,{docName:r,content:e.getText(`source`).toString(),lifecycle:Or(e)},{handler:`document-read`})}finally{await a.disconnect()}}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Pr=J(oo,async(e,t)=>{try{Ce&&await Ce.catch(e=>{Z.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=n.searchParams.get(`dir`),i=n.searchParams.get(`showAll`)===`true`,a=n.searchParams.get(`showOk`)===`true`,o=n.searchParams.get(`depth`)===`1`?1:1/0;if(r)try{IX(l,r)}catch{q(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(i&&P&&KX(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=OC(t,`document-list`),i=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=zX(),n=qX({contentDir:l,contentFilter:P,dirFilter:r,maxEntries:t,maxDepth:o,showOk:a,signal:e.signal}),s=0,c=await n.next();for(;!c.done;)await i(`${JSON.stringify(c.value)}\n`),s+=1,c=await n.next();let{truncated:u}=c.value;u&&Z.info({handler:`document-list`,maxEntries:t,count:s},`[document-list][showAll] stream truncated at entry cap`),await i(`${JSON.stringify({type:`complete`,truncated:u,count:s})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):Z.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(i&&P){let e=`showAll:${o===1?`d1:`:``}${a?`ok:`:``}${r??``}`,n=Xe.get(e);if(!n){let t=new AbortController,i=(async()=>{let e=[],n=zX(),{truncated:i}=await JX({contentDir:l,contentFilter:P,dirFilter:r,documents:e,maxEntries:n,maxDepth:o,showOk:a,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),i&&Z.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:i}})();n={promise:i,controller:t,waiters:0};let s=n;Xe.set(e,s),i.finally(()=>{Xe.get(e)===s&&Xe.delete(e)})}let i=n;i.waiters+=1;let s=!1,c=()=>{t.writableEnded||s||(s=!0,--i.waiters,i.waiters<=0&&(i.controller.abort(),Xe.get(e)===i&&Xe.delete(e)))};t.on(`close`,c);try{let{documents:e,truncated:n}=await i.promise;if(s)return;Y(t,200,co,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(s)return;q(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,c)}return}let s=f(),c=m(),u=v?.()??new Map,d=[];for(let[e,t]of u)r&&!e.startsWith(`${r}/`)&&e!==r||d.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let p=[];try{let e=gt(s);rt?.signature!==e&&(rt={signature:e,assets:cM({contentDir:l,fileIndex:s,readMarkdown:e=>{try{return U(e,`utf-8`)}catch{return null}},isExcluded:P?e=>P.isPathIgnored(e):void 0})}),p=rt?.assets??[]}catch(e){rt=null,Z.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),d.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of c){if(t.kind===`markdown`){if(r&&!e.startsWith(`${r}/`)&&e!==r)continue;let n=sC(e);d.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(r&&!i.startsWith(`${r}/`)&&i!==r)continue;let a=Tj(B(l,t.canonicalPath));d.push({kind:`document`,docName:i,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}continue}if((!r||e===r||e.startsWith(`${r}/`))&&!h.has(e)){let n=LX(e);d.push({kind:`file`,docName:e,path:e,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let n of t.aliases){if(!(!r||n===r||n.startsWith(`${r}/`))||h.has(n))continue;let i=Tj(B(l,t.canonicalPath)),a=LX(n);d.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}}let g=x?.()??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=u.get(n),i=t?Tj(B(l,t.canonicalPath)):n;for(let a of r)e(a)&&d.push({kind:`folder`,path:a,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:i})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of u)n(e,n=>{d.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:Tj(B(l,t.canonicalPath))})});for(let[e,t]of c)n(e,n=>{let r=Tj(B(l,t.canonicalPath));if(t.kind===`markdown`)d.push({kind:`document`,docName:n,docExt:sC(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=LX(n);d.push({kind:`file`,docName:n,path:n,docExt:`.${i}`,assetExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r})}})}d.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),Y(t,200,co,{documents:d},{handler:`document-list`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),Fr=J(oo,async(e,t)=>{if(!oe){q(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){q(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!kZ(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}Y(t,200,ote,{docName:n,backlinks:(await oe.getBacklinks(n)).map(e=>({source:e.source,anchor:e.anchor,title:wt(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){un(t,e,{handler:`backlinks`,failureTitle:`Failed to read backlinks.`})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),zr=J(oo,async(e,t)=>{try{let e=Cd(A??l),n=CO({projectDir:e}),r=new Set(iV(l).map(e=>e.name)),i=new Set(aV(Bs).map(e=>e.name));Y(t,200,Ri,{...n,skills:n.skills.filter(t=>ro(t.provenance,e)&&!(t.provenance.scope===`project`?r.has(t.name):i.has(t.name)))},{handler:`skills-installed`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to enumerate installed skills.`,{handler:`skills-installed`,cause:e})}},{handler:`skills-installed`,method:`GET`,skipBodyParse:!0}),Vr=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`q`)?.trim()??``;if(n.length<2){q(t,400,`urn:ok:error:invalid-request`,`Search query must be at least 2 characters.`,{handler:`skills-search`});return}try{let e=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(n)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(e.ok){Y(t,200,Le,{results:zD(await e.json()),backend:`skills.sh`,degraded:!1},{handler:`skills-search`});return}Z.warn({status:e.status},`skills.sh search unavailable — falling back to GitHub topic search`)}catch(e){Z.warn({err:e},`skills.sh search failed — falling back to GitHub topic search`)}try{let e=encodeURIComponent(`${n} topic:agent-skills`),r=await fetch(`https://api.github.com/search/repositories?q=${e}&per_page=30`,{signal:AbortSignal.timeout(8e3),headers:{Accept:`application/vnd.github+json`}});if(!r.ok){Z.warn({status:r.status},`GitHub skill search fallback returned non-ok`),q(t,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,detail:`GitHub fallback returned ${r.status}.`});return}Y(t,200,Le,{results:$oe(await r.json()),backend:`github-fallback`,degraded:!0},{handler:`skills-search`})}catch(e){q(t,502,`urn:ok:error:internal-server-error`,`Skill discovery is temporarily unavailable.`,{handler:`skills-search`,cause:e})}},{handler:`skills-search`,method:`GET`,skipBodyParse:!0}),Wr=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=Number(n.searchParams.get(`limit`)),i=Number.isFinite(r)&&r>0?Math.min(Math.floor(r),60):24;try{let e=await ZJ(i);Y(t,200,Le,{results:e,backend:`skills.sh`,degraded:e.length===0},{handler:`skills-popular`})}catch(e){q(t,502,`urn:ok:error:internal-server-error`,`Popular skills are temporarily unavailable.`,{handler:`skills-popular`,cause:e})}},{handler:`skills-popular`,method:`GET`,skipBodyParse:!0}),Kr=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`source`)?.trim()??``,i=n.searchParams.get(`name`)?.trim()??``;if(!r||!i){q(t,400,`urn:ok:error:invalid-request`,`source and name are required.`,{handler:`skills-detail`});return}let a=nte(r,i);if(!a){q(t,400,`urn:ok:error:invalid-request`,`Unrecognized skill source.`,{handler:`skills-detail`});return}let{skillsUrl:o,sourceKind:s,sourceUrl:c}=a,l={},u=!1;try{let e=await fetch(o,{signal:AbortSignal.timeout(8e3)});e.ok&&(u=!0,l=Qoe(await e.text()))}catch(e){Z.warn({err:e,skillsUrl:o},`skills.sh detail fetch failed — degrading to repo link`)}Y(t,200,hee,{title:l.title??i,description:l.description??``,image:l.image??null,skillsUrl:u?o:null,sourceKind:s,sourceUrl:c},{handler:`skills-detail`})},{handler:`skills-detail`,method:`GET`,skipBodyParse:!0}),qr=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`source`)?.trim()??``,i=n.searchParams.get(`name`)?.trim()??``;if(!r){q(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-preview`});return}let a=null;try{a=await HD(r,i||void 0)}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not resolve source.`,{handler:`skills-preview`,cause:e});return}throw e}let o=a?.spec??ED(r);if(!o){q(t,400,`urn:ok:error:invalid-request`,`Unrecognized preview source.`,{handler:`skills-preview`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if($Y(t,o,`skills-preview`))return;let s;try{let e=await OD(o);s=e.cleanup;let n=RD(e.dir);if(n.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-preview`});return}let a=n[0];if(i){let e=n.find(e=>e.name===i)??n.find(e=>FD(e.dir)?.name===i);if(!e){q(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skills-preview`,detail:`"${i}" not among: ${n.map(e=>e.name).join(`, `)}.`});return}a=e}let c=ID(a.dir);if(c){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle is too large.`,{handler:`skills-preview`,detail:c});return}let l=LD(a.dir);if(!l){q(t,404,`urn:ok:error:not-found`,`SKILL.md unreadable in source.`,{handler:`skills-preview`});return}let u=uO(r),d=dO(e.dir);Y(t,200,nt,{name:l.name,description:l.description,skillMd:l.skillMd,files:l.files.map(e=>({relPath:e.relPath,content:e.content})),plugin:u??void 0,pluginBundle:d??void 0},{handler:`skills-preview`})}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-preview`,cause:e});return}q(t,502,`urn:ok:error:internal-server-error`,`Preview is unavailable.`,{handler:`skills-preview`,cause:e})}finally{s?.()}},{handler:`skills-preview`,method:`GET`,skipBodyParse:!0}),Jr=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`source`)?.trim()??``;if(!n){q(t,400,`urn:ok:error:invalid-request`,`source is required.`,{handler:`skills-discover`});return}let r=VD(n);if(r){try{Y(t,200,lt,{skills:await Boe(`https://${r.hostname}`)},{handler:`skills-discover`})}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}throw e}return}let i=ED(n);if(!i){q(t,400,`urn:ok:error:invalid-request`,`Unrecognized source.`,{handler:`skills-discover`,detail:`Expected owner/repo, a git URL, a website source, or a local path.`});return}if($Y(t,i,`skills-discover`))return;let a;try{let e=await OD(i);a=e.cleanup,Y(t,200,lt,{skills:RD(e.dir).map(e=>{let t=FD(e.dir);return{name:t?.name??e.name,description:t?.description??null}})},{handler:`skills-discover`})}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-discover`,cause:e});return}q(t,502,`urn:ok:error:internal-server-error`,`Discovery is unavailable.`,{handler:`skills-discover`,cause:e})}finally{a?.()}},{handler:`skills-discover`,method:`GET`,skipBodyParse:!0}),$r=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`ref`)?.trim()??``,i=n.searchParams.get(`from`)?.trim()??``,a=n.searchParams.get(`scope`)?.trim()===`global`?`global`:`project`;if(!r||!Ie.test(r)||r.length>64){q(t,400,`urn:ok:error:invalid-request`,`A valid ref is required.`,{handler:`skills-resolve-ref`});return}try{let e=e=>Y(t,200,fee,e,{handler:`skills-resolve-ref`});for(let t of[a,a===`project`?`global`:`project`]){let n=Hs(t,r);if(n!==null){e({kind:`local`,scope:t,name:r,dir:B(t===`project`?l:Bs,n).split(Al).join(`/`)});return}}let n=a===`project`?A:Bs,o=i&&n?Mc(z(n,...kD)).skills[i]:void 0;if(o?.source){let t=(await HD(o.source,r))?.spec??ED(o.source),n=t&&!(t.kind===`git`&&!gG(t.url));if(t&&n){let n;try{let i=await OD(t);if(n=i.cleanup,RD(i.dir).map(e=>FD(e.dir)?.name??e.name).includes(r)){e({kind:`import`,source:o.source,ref:r,via:`source`});return}}catch(e){Z.debug({err:e,ref:r,from:i,source:o.source},`resolve-ref: source rung unreachable, falling through to publisher`)}finally{n?.()}}}if(o?.publisher)try{let t=await fetch(`https://skills.sh/api/search?q=${encodeURIComponent(r)}&limit=30`,{signal:AbortSignal.timeout(8e3)});if(t.ok){let n=zD(await t.json()).filter(e=>e.name===r&&e.publisher===o.publisher);if(n.length===1){let t=n[0];if(t){e({kind:`import`,source:t.source,ref:r,via:`publisher`});return}}}}catch(e){Z.debug({err:e,ref:r,publisher:o.publisher},`resolve-ref: skills.sh unavailable, no publisher resolution`)}e({kind:`none`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Could not resolve the reference.`,{handler:`skills-resolve-ref`,cause:e instanceof Error?e:Error(String(e))})}},{handler:`skills-resolve-ref`,method:`GET`,skipBodyParse:!0}),ei=J(oo,async(e,t)=>{if(!oe){q(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){q(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let r=n.split(`,`).map(e=>e.trim()).filter(e=>e&&kZ(e));Y(t,200,Zee,{counts:await oe.getBacklinkCounts(r)},{handler:`backlink-counts`})}catch(e){un(t,e,{handler:`backlink-counts`,failureTitle:`Failed to read backlink counts.`})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),ti=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`prefix`),i=n.searchParams.get(`docNames`);if(r===null&&i===null){q(t,400,`urn:ok:error:invalid-request`,`Missing docNames or prefix parameter.`,{handler:`comment-counts`});return}let a={};if(r!==null){let e=r.trim();if(e!==``&&!kZ(e)){q(t,400,`urn:ok:error:invalid-request`,`Invalid prefix parameter.`,{handler:`comment-counts`});return}a=Object.fromEntries(await St.countThreads({prefix:e}))}else{let e=(i??``).split(`,`).map(e=>e.trim()).filter(e=>e!==``&&kZ(e));a=Object.fromEntries(await St.countThreads({docNames:e}))}Y(t,200,Ar,{counts:a},{handler:`comment-counts`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read comment counts.`,{handler:`comment-counts`,cause:e})}},{handler:`comment-counts`,method:`GET`,skipBodyParse:!0}),oi=J(oo,async(e,t)=>{if(!oe){q(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){q(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!kZ(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=await tn();Y(t,200,Qe,{docName:n,forwardLinks:(await oe.getForwardLinkEntries(n)).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Ot(e.target,r),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){un(t,e,{handler:`forward-links`,failureTitle:`Failed to read forward links.`})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),si=J(oo,async(e,t)=>{if(!oe){q(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&&!kZ(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){q(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){q(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:a,links:o}=await oe.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=await oe.getLinkGraph());let s=await tn();Y(t,200,ete,{nodes:a.map(e=>{if(e.kind===`doc`){let t=Pt(e.docName,s);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Ot(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){un(t,e,{handler:`link-graph`,failureTitle:`Failed to read link graph.`})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),ci=J(oo,async(e,t)=>{if(!oe){q(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(!TH(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}Y(t,200,ha,{orphans:(await oe.getOrphans([...f().keys()],n)).map(e=>({docName:e,title:wt(e)}))},{handler:`orphans`})}catch(e){un(t,e,{handler:`orphans`,failureTitle:`Failed to read orphan pages.`})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),fi=J(oo,async(e,t)=>{if(!oe){q(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20,a=await tn();Y(t,200,Sr,{hubs:(await oe.getHubs(i)).map(e=>({docName:e.docName,title:Ot(e.docName,a),count:e.count}))},{handler:`hubs`})}catch(e){un(t,e,{handler:`hubs`,failureTitle:`Failed to read hub pages.`})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),mi=J(oo,async(e,t)=>{if(!oe){q(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||!kZ(e))){q(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>It(e)))]:void 0;Y(t,200,Ti,{deadLinks:(await oe.getDeadLinks(await tn(),r)).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:wt(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){un(t,e,{handler:`dead-links`,failureTitle:`Failed to read dead links.`})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),hi=J(vt,async(n,r,i)=>{try{let{find:n,replace:a,offset:c}=i,u=eZ(i.docName,r,`agent-patch`);if(u===null)return;let d=It(u),{agentId:f,agentName:p,colorSeed:m,clientName:h,clientVersion:g,label:_}=Xn(i);if(sX(n)){oX().add(1,{result:`rejected`}),q(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(fC(d)||pC(d)){q(r,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`agent-patch`});return}let v=fj(i.summary),y=await s.getSession(d,f,{displayName:p,colorSeed:m,clientName:h}),b=UH(t,o,d,l,e.resolveEmbed,pe?.()),x=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,S;{let{frontmatter:e,body:t}=eo(y.dc.document.getText(`source`).toString()),r=_r(e,t),i=c==null?r.indexOf(n):r.slice(c,c+n.length)===n?c:-1;if(i!==-1&&i>=e.length){let e=r.slice(0,i)+a+r.slice(i+n.length);S=await LT(y.dc.document,eo(e).body,`patch`,x)}}let C=new Date().toISOString(),w=!1,T=!1,ee=!1,te,ne;try{let e=Br(h),t=Nr[e]??Gi(m??f);if(ce?.setPresence(f,{displayName:p,icon:e,color:t,currentDoc:d,mode:`writing`,ts:Date.now()}),ne=uj(y.dc.document.getText(`source`),f,y.origin,m,h),y.dc.document.transact(()=>{let{frontmatter:e,body:t}=eo(y.dc.document.getText(`source`).toString()),r=_r(e,t),i=c==null?r.indexOf(n):r.slice(c,c+n.length)===n?c:-1;if(i===-1){c==null?w=!0:T=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":d,findLength:n.length,replaceLength:a.length,hadOffset:c!=null})),Cie();return}if(i<e.length){ee=!0;return}let{body:o}=eo(r.slice(0,i)+a+r.slice(i+n.length)),s=HT(y.dc.document);te=VT(y.dc.document,o,`patch`,x,S,zT(y));let l=to(s,HT(y.dc.document))??void 0;y.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Patched (${p}): ${n.slice(0,50)}`,...l===void 0?{}:{changedBlocks:l}})},y.origin),te!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":d,position:`patch`,intendedBytes:te.intendedBytes,actualBytes:te.actualBytes,byteDelta:te.byteDelta,"agent.id":f,"agent.client_name":h})),!w&&!T&&!ee){let{stored:e}=Qn(v);tF(d,f,p,m,void 0,Zn({clientName:h,clientVersion:g,label:_}),e),hS(),er(v),vX(`agent-patch`,te)}}finally{ne?.(),ce?.touchMode(f,`idle`)}if(T){q(r,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(w){q(r,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ee){oX().add(1,{result:`rejected`}),q(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let re=await Jt(d);if(re?.kind===`failure`){Xt(r,re.failure,`agent-patch`);return}if(re?.kind===`divergence`){Zt(r,`agent-patch`);return}Wt(d,`agent-patch`),k?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`edit`,ts:Date.now()}),le?.();let ie=zt(d),E=Vt();E===0&&iX().add(1,{"shadow.writer":`agent`,"agent.type":Zh(h)});let{response:D}=Qn(v),ae=y.dc.document.getText(`source`).toString();mn(d,ae);let O=await mR(ae,d),oe=await tn();oe.add(d);let se=iH(ae,d,oe,pn),ue=$t(b),de=te===void 0?void 0:LC(te),fe=[...de?[de]:[],...ue?[ue]:[],...O??[],...await lu(y.dc.document.getText(`source`).toString(),d)];Y(r,200,nee,{timestamp:C,subscriberCount:ie,systemSubscriberCount:E,...D?{summary:D}:{},...de?{warning:de}:ue?{warning:ue}:{},...fe.length>0?{warnings:fe}:{},brokenLinks:se},{handler:`agent-patch`})}catch(e){if(e instanceof NC){PC(r,e,`agent-patch`);return}if(e instanceof RC){BC(r,e,`agent-patch`);return}if(e instanceof ZT){q(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e,requestId:CC(n)},`[agent-patch] handler failed`),q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),gi=J(oee,async(t,n,r)=>{try{let t=eZ(r.docName,n,`agent-undo`);if(t===null)return;let i=It(t),{agentId:a,agentName:o,colorSeed:c,clientName:l,clientVersion:u,label:d}=Xn(r);if(fC(i)||pC(i)){q(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=r,p,m;if(r.scope===`count`?(p=`count`,m=r.count):p=r.scope===`session`||r.scope===`file`?`session`:`last`,!s.hasSession(i,f)){q(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let h=await s.getSession(i,f),g=!1;try{let t=Br(l),n=Nr[t]??Gi(c??a);ce?.setPresence(a,{displayName:o,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),g=GT(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,m),g&&tF(i,f,o,c,void 0,Zn({clientName:l,clientVersion:u,label:d}))}finally{ce?.touchMode(a,`idle`)}if(g){let e=await Jt(i);if(e?.kind===`failure`){Xt(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Zt(n,`agent-undo`);return}Ut(i,`agent-undo`)}k?.setFocus(f,{agentName:f,currentDoc:i,writeKind:`undo`,ts:Date.now()}),Y(n,200,En,{docName:i,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof NC){PC(n,e,`agent-undo`);return}Z.error({err:e,requestId:CC(t)},`[agent-undo] handler failed`),q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Si=J(oo,async(e,t)=>{try{let n=Jh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}Y(t,200,ln,Qae(s,n),{handler:`agent-activity`})}catch(n){Z.error({err:n,requestId:CC(e)},`[agent-activity] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Ci=J(oo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=Jh(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),a=n.searchParams.get(`keptCount`);if(r===null){q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){q(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!kZ(i)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let o=It(i);if(fC(o)||pC(o)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!a||Number.isNaN(Number(a))){q(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(a);if(!Number.isInteger(c)||c<0){q(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=s.getLiveSession(o,r);if(!l){q(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){q(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}=Yae(u.undoStack,c,d,o);Y(t,200,_n,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){Z.error({err:n,requestId:CC(e)},`[agent-burst-diff] handler failed`),q(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}),wi=J(oo,async(e,t)=>{try{await re?.(),Y(t,200,tee,{},{handler:`test-flush-git`})}catch(n){Z.error({err:n,requestId:CC(e)},`[test-flush-git] flush failed`),q(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}),Ai=J(oo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=It(n.searchParams.get(`docName`)??`test-doc`),i;try{i=Dj(r,l)}catch(e){Z.error({err:e,docName:r},`[test-reset] safeContentPath rejected docName`),q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(r),o.closeConnections(r);let a=`onStoreDocument-${r}`;o.debouncer.isDebounced(a)&&await o.debouncer.executeNow(a);let c=o.documents.get(r);if(c&&await(Se??o.unloadDocument.bind(o))(c),tu(i,``,`utf-8`),await oe?.testOnly?.resetDocumentForTest(r),n.searchParams.get(`reset-okignore`)!==`false`)try{let e=V(l,`.okignore`),t=o.documents.get(Pe);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},aN)}H(e)&&tu(e,``,`utf-8`),P&&await P.rebuildIgnorePatterns()}catch(e){Z.warn({err:e},`[test-reset] okignore reset partial failure`)}se?.(`files`),Y(t,200,Dt,{},{handler:`test-reset`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),ji=J(oo,async(e,t)=>{try{if(!oe?.testOnly){q(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await oe.testOnly.rescanBacklinksForTest(),Y(t,200,bee,{},{handler:`test-rescan-backlinks`})}catch(e){q(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}),Mi=J(oo,async(e,t)=>{try{if(!S){q(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await S(),se?.(`files`),Y(t,200,Dee,{},{handler:`test-rescan-files`})}catch(e){q(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}),Ni=J(ea,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=Xn(n),o=ne?.current;if(!o){q(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){q(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=E?.()??`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 MS(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[HS],l=!0}let d=O??`.`,f=fj(typeof n.summary==`string`?n.summary:void 0),p=await ZS(o,d,c,u,f.kind===`value`?f.value:void 0,l?{includeUpstream:!1}:void 0);L(`history`).info({checkpointRef:p.checkpointRef},`checkpoint`);try{await Rq(o,bq(o.gitDir))}catch(e){Z.warn({err:e},`[rename-log] post-saveVersion GC failed`)}Y(t,200,vi,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(n){Z.error({err:n,requestId:CC(e)},`[save-version] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),Fi=J(oo,async(e,t)=>{let n=ne?.current;if(!n){q(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}try{let e=performance.now();await re?.();let t=performance.now()-e;t>1e3&&Z.warn({durationMs:Math.round(t)},`[history] pre-read commit flush slow`)}catch(e){Z.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`)??E?.()??`main`;if(!i&&a===null){q(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)){q(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=bs(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}=tt.run(u,()=>ZY(n,e.folderRel,O??`.`,{branch:o,limit:s,offset:l}));f&&MY(`folder`),Y(t,200,Hr,{...await d},{handler:`history`});return}let s=O??`.`,c=wX(i,s);if(`error`in c){q(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}=tt.run(_,()=>XY(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&MY(`doc`);let a=await e,c=Date.now()-v;L(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),Y(t,200,Hr,{...a},{handler:`history`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Li(e,t,n){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=ne?.current;if(!r){q(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=O??`.`,o=wX(i,a);if(`error`in o){q(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=jS(r),c=E?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await Uq(r,i,n,c,bq(r.gitDir),e=>TX(e,a),wq());if(e===null){q(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`);Y(t,200,ri,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let zi=J(Ui,async(t,n,r)=>{let i=fM(r,me);if(i.kind===`invalid-summary`){q(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let a=o.documents.get(r.docName);if(a&&AC(a)){PC(n,new NC({file:lC(r.docName)}),`rollback`);return}let s=ne?.current;if(!s){q(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=r,u=O??`.`,d=wX(c,u);if(`error`in d){q(n,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=jS(s),p=Date.now();try{let t=bq(s.gitDir),r=wq(),a=await Uq(s,c,l,E?.()??`main`,t,e=>TX(e,u),r);if(a===null){q(n,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let d=await f.raw(`show`,`${l}:${a}`),m=new Date().toISOString();await KS(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=o.documents.get(c);if(!h){q(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let g=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:c}:void 0,_=await pw(d,g),v;h.transact(()=>{Zx(h,d,g,_),v=IC(h.getText(`source`).toString(),d,`rollback`)},xX),v!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:v.intendedBytes,actualBytes:v.actualBytes,byteDelta:v.byteDelta,"actor.kind":i.kind,...i.kind===`agent`||i.kind===`principal`?{"actor.writer_id":i.writerId}:{}})),vX(`rollback`,v);let y;switch(i.kind){case`agent`:{let e=l.slice(0,8),t=i.summary.kind===`value`,n=t?i.summary:fj(`Restored to ${e}`),r=Qn(n);y=t||!r.response?r.response:$n(r.response),tF(c,i.writerId,i.displayName,i.colorSeed,vd(c,l),i.actor,r.stored),hS(),er(n,!t);break}case`principal`:{let e=Qn(i.summary);y=e.response,tF(c,i.writerId,i.displayName,i.colorSeed,vd(c,l),i.actor,e.stored),er(i.summary,!1);break}case`anonymous`:Z.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(i.kind)}`)}lX().add(1,{kind:`rollback`,attribution_kind:i.kind});let b=await Jt(c);if(b?.kind===`failure`){Xt(n,b.failure,`rollback`);return}if(b?.kind===`divergence`){Zt(n,`rollback`);return}Ut(c,`rollback`);let x=Date.now()-p;L(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),i.kind===`agent`&&k?.setFocus(i.writerId,{agentName:i.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:LC(v);Y(n,200,He,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){q(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Bi=J(oo,async(e,t)=>{try{Y(t,200,xo,wS(),{handler:`metrics-reconciliation`})}catch(n){Z.error({err:n,requestId:CC(e)},`[metrics-reconciliation] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:n})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),Hi=J(oo,async(e,t)=>{try{Y(t,200,kn,aee(),{handler:`metrics-parse-health`})}catch(n){Z.error({err:n,requestId:CC(e)},`[metrics-parse-health] handler failed`),q(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}),Wi=J(oo,async(e,n)=>{try{Ce&&await Ce.catch(e=>{Z.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=ae?.(),i=gH();Y(n,200,vee,{serverInstanceId:d,currentBranch:e,...r===void 0?{}:{currentDiskAckSVs:r},...i===void 0?{}:{boot:i}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),Qi=M({agents:j(M({id:F(),name:F(),version:F(),description:F().optional(),license:F().optional(),iconUrl:F().optional(),website:F().optional(),source:we([`registry`,`custom`]),supported:D(),featured:D(),harness:M({cli:we([`claude`,`codex`,`cursor`,`opencode`,`pi`]),availability:we([`present`,`not-found`,`unknown`])}).optional()})),stale:D(),maxThreads:N()}),ta=J(oo,async(e,t)=>{if(_e===void 0){q(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=kd(),{agents:n,stale:r}=await _e.getCatalog(),i=await ye?.()??[],a=await be();Y(t,200,Qi,{agents:[...n.map(t=>{let n=ij[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:Ed.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){q(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function ia(e,t){if(!pj(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=me?.()??null;if(!n){q(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}Y(t,200,See,n,{handler:`principal`})}async function aa(e,t){if(!pj(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=ce?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);Y(t,200,see,{presence:r},{handler:`metrics-agent-presence`})}catch(n){Z.error({err:n,requestId:CC(e)},`[metrics-agent-presence] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:n})}}async function da(e,t){if(!pj(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-effects`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-effects`,extraHeaders:{Allow:`GET`}});return}let n;try{let e=[];for(let[t,r]of o.documents){if(fC(t)||pC(t)||!r.share.has(`agent-effects`))continue;n=t;let i=r.getMap(`agent-effects`);if(i.size===0)continue;let a=[...i.values()].map(e=>{let t=0,n=0;for(let r of e.delta)typeof r.insert==`string`?t+=r.insert.length:r.insert!==void 0&&(t+=1),typeof r.delete==`number`&&(n+=r.delete);return{sessionId:e.sessionId,agentType:e.agent_type,ts:e.timestamp,insertedChars:t,deletedChars:n}}).sort((e,t)=>e.ts-t.ts);e.push({"doc.name":t,entries:a})}e.sort((e,t)=>e[`doc.name`].localeCompare(t[`doc.name`])),Y(t,200,Lt,{effects:e},{handler:`metrics-agent-effects`})}catch(e){Z.error({err:e,"doc.name":n},`[metrics-agent-effects] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-effects`,cause:e})}}async function fa(e,t){if(!pj(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-watcher-recent`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-watcher-recent`,extraHeaders:{Allow:`GET`}});return}try{Y(t,200,Je,{decisions:cU().map(e=>({ts:e.ts,decision:e.decision,kind:e.kind,"doc.name":e.path,pathRole:e.pathRole}))},{handler:`metrics-watcher-recent`})}catch(n){Z.error({err:n,requestId:CC(e)},`[metrics-watcher-recent] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-watcher-recent`,cause:n})}}async function pa(e,t){if(!pj(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=oF.read();Y(t,200,hr,{entries:n,count:n.length,detection:ece(n[0])},{handler:`embed-detect`})}async function ma(e,t){if(!pj(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=V(l),r=n,a=!0;try{r=W(n)}catch(e){let r=Is(e);if(r===`ENOENT`)Z.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),a=!1;else{Z.warn({path:n,err:e},`[workspace] realpath failed for contentDir`),q(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}Y(t,200,ui,{contentDir:r,pathSeparator:Al,symlinkResolved:a},{handler:`workspace`})}let ga=J(oo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){q(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let r=lM(n),i=El(n).slice(1).toLowerCase();if(!r||!c.has(i)){q(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let a=W(l),o=V(a,n),s;try{s=W(o)}catch{q(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!Oj(s,a)){q(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let u;try{u=$l(s)}catch{q(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!u.isFile()){q(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let d=sM(a,s);if(d!==n.split(`\\`).join(`/`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(P?.isPathIgnored(d)){q(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let f=te.has(i),p={"Content-Type":r,"Content-Length":String(u.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":ee.has(i)||f?`inline`:`attachment`,"Cache-Control":`no-store`};i===`svg`?p[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:f&&(p[`Content-Security-Policy`]=T),t.writeHead(200,p);try{await ju(Bl(s),t)}catch(e){Z.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){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),_a=1048576,va=J(oo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){q(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let r=W(l),i=V(r,n),a;try{a=W(i)}catch(e){q(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!Oj(a,r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let o;try{o=$l(a)}catch(e){q(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!o.isFile()){q(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(sM(r,a)!==n.split(`\\`).join(`/`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(o.size>_a){q(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${_a}-byte text-viewer cap.`,{handler:`asset-text`});return}let s=(await pu(a)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(s)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),ya=J(oo,async(e,t)=>{try{if(!ne?.current){Y(t,200,ba,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=V(ne.current.gitDir,`rescue`);if(H(r))try{let t=Jl(r).filter(e=>eC(e));for(let i of t){let t=V(r,i),a=$l(t);if(e-a.mtimeMs>864e5){try{eu(t)}catch(e){Z.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:nC(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){Z.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=E?.()??`main`,t=await JS(ne.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){Z.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}Y(t,200,ba,n,{handler:`rescue-list`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),xa=J($ee,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let r=n.path;if(!eC(r)){q(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(`\\`)){q(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let i=V(l),a=V(i,r);if(!Ej(a,i)){q(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let o=nC(r);if(fC(o)||pC(o)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`});return}if(XX(r)||Zi(o)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let s=typeof n.template==`string`?n.template.trim():``,c=``,u;if(s.length>0){if(!/^[A-Za-z0-9_-]+$/.test(s)){q(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let n=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)):``,a=sP(i,n),o=a.find(e=>e.name===s);if(!o){let e=a.length===0?`(none)`:a.map(e=>`"${e.name}" (${e.scope})`).join(`, `);q(t,400,`urn:ok:error:invalid-request`,`Template "${s}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let l=V(i,o.path),d;try{d=U(l,`utf-8`)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=pr(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;c=WP(f,{date:KP(),user:p}),u=o.scope}Ul(R(a),{recursive:!0});try{tu(a,c,{encoding:`utf-8`,flag:`wx`})}catch(e){if(sZ(e)){q(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let d=nC(r);switch(Te?.delete(d),P&&P.incrementMdDir(R(d)),$H(a,tU(c)),e.kind){case`agent`:case`principal`:tF(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)}`)}h?.({kind:`create`,path:a,docName:d,content:c}),await an(d,c,`create-page`),se?.(`files`),u!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:s,templateScope:u,docName:d})),Y(t,200,ho,{docName:d},{handler:`create-page`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),Ca=J(pi,async(e,t,n)=>{try{if(fM(n,me).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!YX(e)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(XX(e)){q(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(P?.isDirExcluded(e)){q(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let r=nZ(l,`folder`,e);if(H(r)){q(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Jo(r,{recursive:!0}),ut(e),se?.(`files`),Y(t,200,Nee,{path:e},{handler:`create-folder`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),wa=J(In,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:r}=n,i=n.path,a=r===`file`?nC(i):i;if(!YX(i)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(XX(i)||r===`file`&&(fC(a)||pC(a))||r===`folder`&&ZX(i)){q(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}r===`file`&&vZ(l,i);let s=nZ(l,r,i);if(!H(s)){if(r===`file`){let e=nZ(l,`folder`,i);if(H(e)&&$l(e).isDirectory()){q(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}}q(t,404,`urn:ok:error:doc-not-found`,`${r} does not exist.`,{handler:`duplicate-path`});return}let c=$l(s);if(r===`file`&&!c.isFile()||r===`folder`&&!c.isDirectory()){q(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}let u=r===`file`?[fZ(l,i)]:Wn(nZ(l,`folder`,i)),d=ue?.(),f=new Set(d?d.getConflicts().map(e=>e.file):[]);for(let e of u){let n=e,r=o.documents.get(n),i=lC(n),a=r!==void 0&&AC(r),s=f.has(i);if(a||s){PC(t,new NC({file:i}),`duplicate-path`);return}}let p,m=[];if(r===`file`){let e=El(s);if(p=mZ(l,a).docName,fC(p)||pC(p)||P?.isExcluded(`${p}${e}`)){q(t,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let n=pZ(l,p,e),r=U(s,`utf-8`),i=R(n),o=H(i);try{Jo(i,{recursive:!0}),rs(n,r,{encoding:`utf-8`,flag:`wx`})}catch(e){if(sZ(e)){q(t,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!o)try{Yo(i)}catch(e){let t=Is(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&Z.warn({destinationDir:i,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let c=!1;try{oC(p,e),Te?.delete(p),P&&(P.incrementMdDir(R(p)),c=!0),$H(n,tU(r)),h?.({kind:`create`,path:n,docName:p,content:r}),m=[p]}catch(e){try{Qo(n,{force:!0})}catch(e){Z.warn({destinationPath:n,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw dC(p),P&&c&&P.decrementMdDir(R(p)),h?.({kind:`delete`,path:n,docName:p}),e}await an(p,r,`duplicate-path-file`)}else{if(p=hZ(l,i).folderPath,P?.isDirExcluded(p)){q(t,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=nZ(l,`folder`,p),n=[];try{Zo(s,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(sZ(e)){q(t,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}let r=[];try{for(let e of _Z(l,p))ut(e);let e=gZ(l,p);m=e.map(e=>e.docName);for(let t of e){let e={docName:t.docName,fullPath:t.fullPath,extensionRegistered:!1,dirCountIncremented:!1,fileIndexRegistered:!1};n.push(e);let i=El(t.fullPath);oC(nC(t.docName),i),e.extensionRegistered=!0,Te?.delete(t.docName),P&&(P.incrementMdDir(R(t.docName)),e.dirCountIncremented=!0),$H(t.fullPath,tU(t.content)),e.fileIndexRegistered=!0,h?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),r.push({kind:`upsert`,documentName:t.docName,markdown:t.content})}}catch(t){for(let e of n.reverse()){if(e.fileIndexRegistered)try{h?.({kind:`delete`,path:e.fullPath,docName:e.docName})}catch(t){Z.warn({docName:e.docName,err:t},`[duplicate-path] failed to roll back copied file-index row`)}e.dirCountIncremented&&P?.decrementMdDir(R(e.docName)),e.extensionRegistered&&dC(nC(e.docName))}dt(p);try{Qo(e,{recursive:!0,force:!0})}catch(t){Z.warn({destinationPath:e,err:t},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}await rn(r,`duplicate-path-folder`)}switch(e.kind){case`agent`:case`principal`:for(let t of m)tF(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)}`)}se?.(`files`),Y(t,200,et,{kind:r,path:p,duplicatedDocNames:m},{handler:`duplicate-path`})}catch(e){if(e instanceof oZ){q(t,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let n=cZ(e);if(n){q(t,n.status,n.type,n.title,{handler:`duplicate-path`,cause:e});return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Ta=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){q(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!kZ(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=xt(n);if(!r){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!H(r)){q(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}Y(t,200,_ee,{docName:n,headings:OZ(U(r,`utf-8`))},{handler:`page-headings`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Ea=J(st,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:r,fromPath:i,toPath:a}=n;if(!YX(i)||!YX(a)){q(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(r===`file`&&(fC(i)||fC(a)||pC(i)||pC(a))){q(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(XX(i)||XX(a)){q(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(i===a){Y(t,200,fn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let s=r===`asset`&&eC(i)&&eC(a)?`file`:r;if(s===`asset`){let n;try{n=eC(i)&&!eC(a)?await Jn(i,a):await qn(i,a)}catch(e){if(e instanceof NC){PC(t,e,`rename-path`);return}let{status:n,type:r,error:i}=Sn(e);q(t,n,r,i,{handler:`rename-path`,cause:e});return}n.renamedAssets.length>0&&_t();let r;if(n.renamedAssets.length>0&&n.rewrittenDocs.length>0){let t=`Renamed asset ${i} → ${a}`;r=tr(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{Z.debug({kind:`asset`,fromPath:i,toPath:a,affectedDocs:n.rewrittenDocs.length,affectedAssets:n.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(lX().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),ie)try{await ie()}catch(e){Z.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}Y(t,200,fn,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}s===`file`&&vZ(l,i);let c=s===`file`?[fZ(l,i)]:Wn(nZ(l,`folder`,i)),u=ue?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of c){let n=e,r=o.documents.get(n),i=lC(n),a=r!==void 0&&AC(r),s=d.has(i);if(a||s){PC(t,new NC({file:i}),`rename-path`);return}}if(P){let e=eC(i)?El(i):sC(i);if(s===`file`?P.isExcluded(eC(a)?a:`${a}${e}`):P.isDirExcluded(a)){q(t,400,`urn:ok:error:invalid-request`,`Destination ${s===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let f=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,p;try{p=await Yn(i,a,s,f?{actor:f}:{})}catch(e){if(e instanceof SI){q(t,409,`urn:ok:error:doc-already-exists`,bn(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(p.renamed.length===0&&p.renamedAssets.length===0){Y(t,200,fn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&_t();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=tr(e,`Renamed ${i} → ${a}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:yd(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{Z.debug({kind:r,fromPath:i,toPath:a,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),lX().add(1,{kind:`rename-${s}`,attribution_kind:e.kind}),ie)try{await ie()}catch(e){Z.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}Y(t,200,fn,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=Sn(e);q(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Da=J(Pee,async(e,t,n)=>{try{Xn(n);let{kind:e,path:r}=n;if(!YX(r)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let i=e===`asset`?Un(r):{path:r,ambiguous:!1};if(i.ambiguous){q(t,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let a=i.path,s=e===`asset`&&eC(a)?`file`:e;if(s===`file`&&vZ(l,a),XX(a)){q(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let c=s===`asset`?nZ(l,`folder`,a):nZ(l,s,a);if(!H(c)){q(t,404,`urn:ok:error:doc-not-found`,`${s} does not exist.`,{handler:`delete-path`});return}let u=$l(c);if(s===`file`&&!u.isFile()||s===`asset`&&!u.isFile()||s===`folder`&&!u.isDirectory()){q(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${s}.`,{handler:`delete-path`});return}let d=s===`asset`?[]:s===`file`?[fZ(l,a)]:Wn(nZ(l,`folder`,a)),f=ue?.(),p=new Set(f?f.getConflicts().map(e=>e.file):[]);for(let e of d){let n=e,r=o.documents.get(n),i=lC(n),a=r!==void 0&&AC(r),s=p.has(i);if(a||s){PC(t,new NC({file:i}),`delete-path`);return}}if(await wn(d,`deleted-upstream`),Te)for(let e of d)fC(e)||pC(e)||(Te.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));s===`file`||s===`asset`?Uo(c):(Qo(c,{recursive:!0,force:!1}),dt(a)),_t();for(let e of d)h?.({kind:`delete`,path:V(l,lC(e)),docName:e});await dn(d,`delete-path`),se?.(`files`),Y(t,200,ite,{deletedDocNames:d},{handler:`delete-path`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),ka=J(Ii,async(e,t,n)=>Lo(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":Xo(n.path),"ok.cleanup.path.role":ts(n.path)}},async()=>{try{if(fM(n,me).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:r}=n;if(!YX(r)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&eC(r)?`file`:e,a=nC(r);i===`file`&&vZ(l,r);let o=i===`folder`&&ZX(r);if(i===`file`&&(fC(a)||pC(a))||o||XX(r)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(i===`asset`){_t(),se?.(`files`),Y(t,200,nn,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let s=f(),c=i===`file`?s.has(a)?[a]:[]:QX(s,i,r);if(_t(),c.length===0){Y(t,200,nn,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await wn(c,`deleted-upstream`),Te)for(let e of c)fC(e)||pC(e)||(Te.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of c)h?.({kind:`delete`,path:V(l,lC(e)),docName:e});i===`folder`&&dt(r),await dn(c,`trash-cleanup`),se?.(`files`),Y(t,200,nn,{deletedDocNames:c},{handler:`trash-cleanup`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Aa=J(oo,async(e,t)=>{try{let e=f(),n=[];for(let[t,r]of e){let e=sC(t),i,a;if(r.title!==void 0)i=r.title,a=r.icon;else{i=t;try{let n=U(V(l,`${t}${e}`),`utf-8`);i=xR(n,t),a=SR(n)}catch(e){Z.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:i,docExt:e,size:r.size,modified:r.modified,icon:a})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Y(t,200,mt,{pages:n},{handler:`pages`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),ja=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){q(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!kZ(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(fC(n)||pC(n)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${n}' is a reserved document name.`,{handler:`suggest-links`});return}Y(t,200,Uee,await wY({hocuspocus:o,fileIndex:f(),docName:n}),{handler:`suggest-links`})}catch(e){if(e instanceof rY){q(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Fa(e,t){if(e.method!==`POST`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let n;try{n=await FX(e,A??l)}catch(e){if(e instanceof yV){q(t,bV(e.reason),e.reason,SV(e.reason),{handler:`upload-asset`,cause:e});return}q(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:r,tempPath:i,sha:o,byteLength:s,parentDocName:c,placement:u}=n,d=()=>{if(H(i))try{eu(i)}catch{}},f=vM(Gt,{parentDocName:c,placement:u||void 0},t,{handler:`upload-asset`});if(!f.ok){d();return}let{parentDocName:m,placement:h}=f.value,{agentId:g,agentName:v}=Xn(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(s===0){d(),q(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(m.includes(`\0`)||m.includes(`..`)||m.startsWith(`/`)){d(),q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let y=V(l),b;try{b=h===`parent-dir`?`./`:p?.()??`./`}catch(e){d(),Z.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),q(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!a(b)){d(),q(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let x=AX(m,_(b),y);if(!Oj(x,y)){d(),q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{tZ(x,y)}catch(e){if(d(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}Z.error({err:e,destDir:x},`[upload] failed to validate destination directory`),q(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{Ul(x,{recursive:!0})}catch(e){if(!sZ(e)){d();let n=xV(e);q(t,bV(n),n,SV(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=W(x),n;try{n=W(y)}catch{n=y}if(!Oj(e,n)){d(),q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(Is(e)!==`ENOENT`){d(),q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let S=jX(i,4100),C=await XA(S),w=C?.mime,T=C?.ext;if(!w){let e=S.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(w=`image/svg+xml`,T=`svg`)}{let n=await PX(x,o,s);if(n){d();let r=Tj(B(l,V(x,n)));Z.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:g,agentName:v,dedup:!0,mime:w??null,size:s,destPath:r,httpStatus:200},`[upload] dedup hit`),Y(t,200,Ct,{src:n,path:r,deduped:!0},{handler:`upload-asset`});return}}let ee;if(!r||r===`upload`||EX.test(r)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=r?El(r).slice(1):``,n=T??t??``;ee=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else ee=kX(r);try{let n=DV(i,x,ee),r=Tj(B(l,V(x,n)));Z.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:g,agentName:v,dedup:!1,mime:w??null,size:s,destPath:r,httpStatus:200},`[upload] write ok`),Y(t,200,Ct,{src:n,path:r,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof yV?n.reason:`urn:ok:error:storage-error`;Z.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:CC(e),agentId:g,agentName:v,filename:ee,size:s,reason:r,httpStatus:bV(r),err:n},`[upload] write failed`),q(t,bV(r),r,SV(r),{handler:`upload-asset`,cause:n})}}let Ia=`/api/local-op/clone`,La=`/api/local-op/ok-init`,Ra=600*1e3,za={stdio:[`ignore`,`ignore`,`pipe`]},Ba={stdio:[`ignore`,`pipe`,`pipe`]},Va={stdio:`ignore`},Ha=`local-op-clone`,Wa=J(Ge,Ga,{handler:Ha,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ha})});async function Ga(e,t,n){let{url:r,dir:i,branch:a}=n;if(!gG(r)){q(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Ha,cause:Error(`url=${r}`)});return}if(!bG(i)){q(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Ha,cause:Error(`dir=${i}`)});return}if(!Ye.tryAcquire(Ia)){q(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Ha,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=OC(t,Ha),s=null,c=cK({cliArgs:de,url:r,dir:i,branch:a,timeoutMs:Ra,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&Z.warn({stderr:iz(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=NG(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(iz(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 Ka(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}):Z.error({err:e,handler:Ha},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Ye.release(Ia)}})(),t.on(`close`,()=>{c.cancel()})}async function Ka(e,t){let n=V(_G(e)),r=rN(n),i=gV(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=de,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=xl(a,s(e),NF({...za,cwd:n,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),i=[];t.stderr?.on(`data`,t=>{i.push(t),Z.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,Z.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 Nu(500);let t=gV(r);if(t&&t.port>0)return{port:t.port};if(o!==null){let t=Buffer.concat(i).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${l?`spawn failed: ${l}`:c?`killed by ${c}`:`code ${o}`})${t?` — ${t}`:``}`,exited:!0}}}let d=Buffer.concat(i).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${d?` — ${d}`:``}`,exited:!1}},l=As(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=As(r);if(e&&e.port>0){let e=await c(`ui`);return`port`in e?e:{error:`${d.error}; connect fallback failed: ${e.error}`}}}return`port`in d?d:{error:d.error}}let qa=`local-op-ok-init`,Ja=J(sa,async(e,t,n)=>{let{projectPath:r}=n;if(!Dl(r)){q(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:qa,cause:Error(`projectPath=${r}`)});return}let i;try{i=W(r)}catch(e){Y(t,200,Ma,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:qa});return}if(!bG(i)){q(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:qa,cause:Error(`projectPath=${r}`)});return}let a=ed(i).kind;if(a!==`directory`&&a!==`linked`){Z.warn({project:wl(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${wl(i)} result=not-a-git-worktree kind=${a}`),Y(t,200,Ma,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:qa});return}if(IU(i)){Z.warn({project:wl(i),result:`already-initialized`},`[ok-init] action=init project=${wl(i)} result=already-initialized`),Y(t,200,Ma,{ok:!0,projectPath:i},{handler:qa});return}if(!Ye.tryAcquire(La)){q(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:qa,extraHeaders:{"Retry-After":`2`}});return}try{await _s(async()=>{pW(i)}),Z.warn({project:wl(i),result:`success`},`[ok-init] action=init project=${wl(i)} result=success`),Y(t,200,Ma,{ok:!0,projectPath:i},{handler:qa})}catch(e){let n=e instanceof Error?e.message:String(e);Z.warn({project:wl(i),result:`failed`,reason:n},`[ok-init] action=init project=${wl(i)} result=failed reason=${n}`),Y(t,200,Ma,{ok:!1,reason:`init-failed`,message:n},{handler:qa})}finally{Ye.release(La)}},{handler:qa,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:qa})}),Za=`/api/local-op/auth/login`,Qa=`/api/local-op/auth/status`,no=`/api/local-op/auth/repos`,io=`/api/local-op/auth/signout`,so=`/api/local-op/auth/pat`,lo=`/api/local-op/auth/gh-login`,uo=fe??15e3,fo=960*1e3,po=()=>BR(A??l),go={current:null},_o={current:null};function bo(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!Ye.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})),q(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=OC(t,n),l=e=>{if(!(t.writableEnded||t.destroyed))try{t.write(e)}catch{}},u=setInterval(()=>{l(`${JSON.stringify({type:`ping`})}\n`)},uo);u.unref();let d=()=>{u!==null&&(clearInterval(u),u=null)},f=s(e=>{if(e.type===`error`){c(500,`urn:ok:error:auth-failed`,o,{cause:e.message?Error(e.message):void 0});return}bX(e,ue),l(`${JSON.stringify(e)}\n`)});i.current=f;let p=()=>{d(),i.current===f&&console.warn(JSON.stringify({event:`ok-local-op:auth-stream-detached`,channel:`auth`,transport:`http`,handler:n}))};t.on(`close`,p),f.done.finally(()=>{if(d(),t.off(`close`,p),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===f&&(i.current=null,Ye.release(r))})}let So=`local-op-auth-login`,To=J(Ht,Do,{handler:So,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:So})});async function Do(e,t,n){let r=n.host??po();bo({res:t,handler:So,guardKey:Za,inFlight:go,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>DG({cliArgs:de,host:r,timeoutMs:fo,onEvent:e})})}let Oo=`local-op-auth-gh-login`,ko=J(Ht,async(e,t,n)=>{let r=n.host??po(),i=await gK();if(i===null){q(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:Oo});return}bo({res:t,handler:Oo,guardKey:lo,inFlight:_o,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>yK({host:r,ghPath:i,timeoutMs:fo,onEvent:e})})},{handler:Oo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Oo})}),Ao=`local-op-auth-cancel`,jo=J(Yt,tW(async(e,t,n)=>{let r=n.channel===`gh-login`?{inFlight:_o,guardKey:lo}:{inFlight:go,guardKey:Za},i=r.inFlight.current;i&&(i.cancel(),r.inFlight.current=null,Ye.release(r.guardKey)),Y(t,200,Oa,{},{handler:Ao})},{handler:Ao,title:`Failed to cancel the sign-in.`}),{handler:Ao,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ao})}),No=`local-op-auth-status`,Po=J(Ht,async(e,t,n)=>{let r=n.host??po();if(!Ye.tryAcquire(Qa)){q(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:No,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=de,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=xl(e,i,NF({...Ba,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,r.kill(`SIGTERM`)},3e4),s=[];r.stdout.on(`data`,e=>s.push(e)),r.on(`close`,()=>{if(clearTimeout(o),a){n(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(s).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
|
|
1213
1213
|
`).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}let s=await gK()!==null;o===null?Y(t,200,Cn,{authenticated:!1,ghAvailable:s},{handler:No}):Y(t,200,Cn,{...o,ghAvailable:s},{handler:No})}catch(e){q(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:No,cause:e})}finally{Ye.release(Qa)}},{handler:No,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:No})}),Fo=`local-op-auth-pat`,Io=J(or,async(e,t,n)=>{let r=n.host??po();if(!Ye.tryAcquire(so)){q(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:Fo,extraHeaders:{"Retry-After":`5`}});return}try{let e=await OG({cliArgs:de,host:r,token:n.token});e.ok?(yX(ue),Y(t,200,Aee,{host:e.host,login:e.login},{handler:Fo})):q(t,400,`urn:ok:error:auth-failed`,e.error,{handler:Fo})}catch(e){q(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:Fo,cause:e})}finally{Ye.release(so)}},{handler:Fo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Fo})}),Ro=`local-op-auth-repos`,zo=J(Ht,Bo,{handler:Ro,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ro})});async function Bo(e,t,n){let r=n.host??po();if(!Ye.tryAcquire(no)){q(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Ro,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=OC(t,Ro),[a,...o]=de,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=xl(a,s,NF({...Ba,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},Ra);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
|
|
1214
1214
|
`);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{Z.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(),Ye.release(no))}),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()),Ye.release(no))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),Ye.release(no))})}let Ho=`local-op-auth-signout`,Go=J(Ht,async(e,t,n)=>{let r=n.host??po();if(!Ye.tryAcquire(io)){q(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]=de,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=xl(e,i,NF({...Va,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),Y(t,200,Oa,{},{handler:Ho})}catch(e){q(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Ho,cause:e})}finally{Ye.release(io)}},{handler:Ho,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ho})}),Ko=`/api/local-op/auth/set-identity`,qo=`local-op-auth-set-identity`,$o=J(dr,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!A){q(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:qo});return}if(!Ye.tryAcquire(Ko)){q(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:qo,extraHeaders:{"Retry-After":`5`}});return}try{eW(A,r,i),ue?.()?.refreshIdentity().catch(()=>{}),Y(t,200,Oa,{},{handler:qo})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:qo,cause:e})}finally{Ye.release(Ko)}},{handler:qo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:qo})});async function es(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ue?.();if(!e){Y(t,200,Sa,{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(),Y(t,200,Sa,e.getStatus(),{handler:`sync-status`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let ns=J(na,async(e,t,n)=>{let r=ue?.();if(!r){q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;Y(t,202,bi,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?ue?.()?!0:(q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function is(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ue?.();Y(t,200,Yee,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let as=J(Gr,async(e,t,n)=>{let r=ue?.();if(!r){q(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),Y(t,200,ai,{},{handler:`sync-resolve-conflict`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?ue?.()?!0:(q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function os(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!A){q(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){q(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=nC(i),s=o.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=ue?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){q(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=gs({baseDir:A,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),a=nC(i),s=o.documents.get(a),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Ee?Ee(a):null;t!==null&&(c=t,l=!0)}else{dV(z(A,i),A);try{c=U(z(A,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;Y(t,200,Xi,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),a=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=nC(i),t=o.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=Ee?Ee(e):null;t!==null&&!CX(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Z.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}Y(t,200,Xi,{file:i,base:a,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function ls(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=uJ(a);if(a!==null&&a!==``&&o===void 0){q(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{Y(t,200,Lr,{plan:await EJ({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof Qq){q(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof $q){q(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}q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let ds=J(Tr,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){q(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=uJ(a);if(typeof a==`string`&&a.length>0&&o===void 0){q(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{Y(t,200,Iee,{result:await xJ(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function fs(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}Y(t,200,Gee,{packs:fJ()},{handler:`seed-packs`})}}let ps=J(Hee,async(e,t,n)=>{if(n.out!==void 0&&!bG(n.out)){q(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{Y(t,200,Oi,await oB({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function hs(e,t){if(r(e,t,{handler:`installed-agents`}))try{await Ice(e,t,bt.probeAll)}catch(n){t.headersSent||(Z.error({err:n,requestId:CC(e)},`[installed-agents] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let vs=J(oo,async(e,t)=>{if(!oe){q(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{Y(t,200,Tt,{tags:await oe.getAllTags()},{handler:`tags-list`})}catch(e){un(t,e,{handler:`tags-list`,failureTitle:`Failed to read tags.`})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function ys(e,t,n){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!oe){q(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{q(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){q(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=(await oe.getDocsForTagWithMatches(r)).map(({docName:e,matchingTags:t})=>({docName:e,title:wt(e),matchingTags:t,snippet:null}));Y(t,200,Eee,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){un(t,e,{handler:`tags-for-name`,failureTitle:`Failed to read tag membership.`})}}function bs(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return q(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=V(l),o=i===``?a:V(a,i);return o!==a&&!o.startsWith(`${a}${Al}`)?(q(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let xs=/^[A-Za-z0-9_-]+$/;function Ss(e,t,n=`template`){return!e||!xs.test(e)?(q(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Cs(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:V(e,i);if(a!==e&&!a.startsWith(`${e}${Al}`))continue;let o=V(a,`.ok`,`templates`,`${n}.md`);if(H(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Ts(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 Es=nW({GET:J(oo,async(e,t)=>{try{let n=bs(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await wP(n.folderRel,{projectDir:n.resolvedContentDir}),i=V(V(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(H(i))try{let e=(0,nj.parse)(await pu(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);Z.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}Y(t,200,sr,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:J(jee,async(e,t,n)=>{try{if(Re){q(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=bs(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=kse({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;q(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`&&(ar(e,ir(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await lr(`folder-config-put`))}Y(t,200,fr,{applied:i},{handler:`folder-config-put`})}catch(e){q(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 Ds(e,t,n,r){if(!t)return!1;let i=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,a=o.documents.get(i);return a&&AC(a)?(PC(r,new NC({file:`${i}.md`}),n),!0):!1}function Os(e,t,n){let r=o.documents.get(e);return r&&AC(r)?(PC(n,new NC({file:`${e}.md`}),t),!0):!1}let ks=J(oo,tW(async(e,t)=>{let n=cP(V(l));Y(t,200,Qr,{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}),js=e=>{let{body:t}=eo(e);return{frontmatter:Rt(e)??{},body:t}},Ms=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`template-get`))return;let i=bs(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Cs(o,a,r);if(!s){q(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=$a(await pu(c,`utf-8`)),f=d.identity,p=d.starterContent;Y(t,200,Bee,{template:{name:r,folder:l,scope:u,path:B(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Ns=J(xn,async(e,t,n)=>{try{if(Re){q(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Ss(r,t,`template-put`))return;let i=bs(n.folder,t,`folder`,`template-put`);if(!i||Ds(i.folderRel,r,`template-put`,t))return;let a=JP({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Ts(n.frontmatter)});if(!a.ok){q(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=V(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!H(o),l=B(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=ac(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=Xn(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Xx(h.dc.document,a.content,`agent`)},h.origin);let g=await Jt(u);if(g?.kind===`failure`){Xt(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){Zt(t,`template-put`);return}ar(e,ir(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await lr(`template-put`),Y(t,200,Ne,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ps=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ss(r,t,`template-delete`))return;let i=bs(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=Us(n,me);if(a.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Ds(i.folderRel,r,`template-delete`,t))return;await wn([ac(i.folderRel,r)],`deleted-upstream`);let o=Bse({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;q(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(ar(a,ir(`template`,i.folderRel,r),`template-delete: ${o.path}`),await lr(`template-delete`)),Y(t,200,qt,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Fs=nW({GET:Ms,PUT:Ns,POST:J(kee,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Ss(n.fromName,t,`template-move`)||!Ss(n.toName,t,`template-move`))return;let r=bs(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=bs(n.toFolder,t,`folder`,`template-move`);if(!i||Ds(r.folderRel,n.fromName,`template-move`,t))return;await wn([ac(r.folderRel,n.fromName)],`renamed`);let a=await Vse({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await EZ(A,e,t);return n||TZ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Cs(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){q(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}q(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`){q(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;q(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=pr(U(V(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=zse({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Ts(n.frontmatter)});t.ok||(o=t.error)}}if(ar(e,ir(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await lr(`template-move`),se?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;q(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}Y(t,200,ur,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:Ps},{handler:`template`}),Ls=J(Bt,async(e,t,n)=>{try{if(Re){q(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!kZ(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=It(r);if(fC(i)||pC(i)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let a=nZ(l,`file`,i);if(!H(a)){q(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let c=o.documents.get(i);if(n.deleteSource){let e=ue?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=c!==void 0&&AC(c),a=n.has(r);if(i||a){PC(t,new NC({file:r}),`template-import`);return}}let u=``;if(c)u=c.getText(`source`).toString();else{let e=await o.openDirectConnection(i);try{let n=e.document;if(!n){q(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=rZ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Ss(d,t,`template-import`))return;let f=bs(n.targetFolder,t,`folder`,`template-import`);if(!f||Ds(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=eo(u),g=mo(p),_={};try{g.trim()&&(_=(0,nj.parse)(g))}catch{}let v=n.title||_?.title||xR(u,d),y=_?.description||``,b=Array.isArray(_?.tags)?_.tags:[],x={..._};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,nj.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=JP({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){q(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=V(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!H(w),ee=B(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),te=ac(f.folderRel,d),{agentId:ne,agentName:re,colorSeed:ie,clientName:E}=Xn(n),D=await s.getSession(te,ne,{displayName:re,colorSeed:ie,clientName:E});D.dc.document.transact(()=>{Xx(D.dc.document,C.content,`agent`)},D.origin);let ae=await Jt(te);if(ae?.kind===`failure`){Xt(t,ae.failure,`template-import`);return}if(ae?.kind===`divergence`){Zt(t,`template-import`);return}ar(e,ir(`template`,f.folderRel,d),`template-import: ${ee}`),n.deleteSource&&(await wn([i],`deleted-upstream`),Te&&Te.setDeleted(i),Uo(a),h?.({kind:`delete`,path:a,docName:i})),await lr(`template-import`),se?.(`files`),Y(t,200,Mee,{path:ee,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Rs(e,t,n){return!e||e.length>64||!Ie.test(e)?(q(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 zs(e,t,n){let r=hn.safeParse(e??`project`);return r.success?r.data:(q(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Bs=he??au();function Vs(e){return V(e===`global`?Bs:l,`.ok`,`skills`)}function Hs(e,t,n){let r=V(Vs(e),t);if(e===`global`){if(n!==void 0){let e=aV(Bs).find(e=>e.name===t&&e.hosts.includes(n));return e?V(Bs,e.dir):null}let e=sV(Bs,t);return e===null?H(z(r,`SKILL.md`))?r:null:e}let i=iV(l).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?V(l,i.dir):n===void 0&&H(z(r,`SKILL.md`))?r:null}function Us(e,t){let n=e.searchParams;return fM({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},t)}function Ws(e){return(e===`.ok`||e.startsWith(`.ok/`))&&e!==`.ok/skills`}function Gs(e,t){let n=e===`project`?A:Bs;if(!n)return`symlink`;try{return Mc(z(n,...kD)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function Ks(e){let t=e===`project`?A:Bs;return t?z(t,...kD):null}function qs(e,t,n,r={}){let i=Ks(e);return i?eY(i,e=>{let i=e.skills[t];if(!i)return e;let a={...e.skills};return delete a[t],a[n]={...i,...r},{...e,skills:a}}):Promise.resolve()}async function Js(e,t,n){let r=Ks(e),i=Ks(t);if(!r||!i)return!1;let a=QJ(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await eY(i,e=>({...e,skills:{...e.skills,[n]:o}})),await eY(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function Ys(e,t,n){let r=Ks(e);return r?eY(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function Xs(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];q(e,r,i,t.error,{handler:n,detail:t.code})}function Zs(e,t,n){let r=e===`project`?A:Bs;return(r?VJ(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Qs(e){let t=Hs(`project`,e);return t?B(l,t).split(Al).join(`/`):`${Pa}/${e}`}let $s=lz.project;function ec(e,t,n){let r=[],i=null,a=[...Et.map(e=>({id:e,root:Mt[e]??``})),{id:`agents`,root:`.agents/skills`}];for(let{id:o,root:s}of a){if(!s)continue;let a=V(e,...s.split(`/`),t);H(V(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=V(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:B(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function tc(e){let t=fO(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function nc(e,t){if(!dz(t))return null;let n=ec(e,t);if(!n)return null;let r=LD(n.dir)?.contentHash??``,i;try{i=$l(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:ao,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function rc(e,t,n){let r=ec(e,t);if(!r)return null;let i;try{let{frontmatter:e}=js(U(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=nc(e,t);return{name:t,...i===void 0?{}:{description:i},scope:n,path:r.relPath,absolutePath:r.skillMd,installed:r.hosts.length>0,hosts:r.hosts,managed:!0,...a?{origin:tc(a)}:{}}}function ic(e,t,n){return dz(e)?(q(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function ac(e,t){return`${Er}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function oc(e){return e===`navigation`||e===`relevance`?e:void 0}function sc(e,t){return B(t===`global`?Bs:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function cc(e){return e===`global`?Bs:A}async function lc(e,t,n){let r=await cI(e,t);if(!H(V(Vs(n),t,`SKILL.md`))){let i=(n===`project`?iV(l):aV(Bs)).find(e=>e.name===t);if(i){let a=n===`project`?l:Bs,o=V(a,i.dir),s=V(a,`.agents`,`skills`),c=z(s,t);if(H(s)&&!H(z(c,`SKILL.md`))){let e=!1;try{e=W(o)===W(c)}catch{e=!1}e||Zo(o,c,{recursive:!0,dereference:!0})}return EB({canonicalAbs:H(z(c,`SKILL.md`))?c:o,canonicalHash:i.contentHash,name:t,cwd:e,targets:[...Et],roots:hB(n)}),r!==null}}return DB(t,e,Et,hB(n)),r!==null}function uc(e,t){let n=[];if(!H(e))return{skills:n,truncated:!1};let r;try{r=Jl(e,{withFileTypes:!0})}catch(r){return L(`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()||!Ie.test(a.name))continue;if(n.length>=500){i=!0;break}let r=V(e,a.name,`SKILL.md`);if(!H(r))continue;let o;try{let{frontmatter:e}=js(U(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:sc(r,t),absolutePath:r})}return{skills:n,truncated:i}}let dc=J(oo,tW(async(e,t)=>{let n=Vs(`project`),r=uc(n,`project`),i=uc(Vs(`global`),`global`),a=[...Et],o=Qz(Bs).map(e=>e.editorId),s=A?aI(A).skills:{},c=aI(Bs).skills,u=A?jD(H(z(A,...kD))?U(z(A,...kD),`utf-8`):``)??null:null,d=tc,f=(e,t,r)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=r?u?.skills[e.name]:void 0,o=a?d(a):void 0,s=a?.localHash!==void 0&&Nc(n,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),p=A?HJ(A):{},m=(e,t,n)=>{let r=[];for(let i of t??[]){let t=V(e,i.path);if(n!==void 0&&t===V(n))continue;let a=!1;try{a=Hl(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(W(t)===W(n))continue}catch{}r.push(i.path)}}return{drift:r}},h=A?qB(l,`project`):{},g=QB(h,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=ZB(`project`),y=ZB(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=A?iV(l).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?u?.skills[e.name]??nc(l,e.name):void 0,r=n?d(n):void 0,i=n?.localHash!==void 0&&e.contentHash!==n.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:V(l,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:a,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(h).length>0?{hostAliases:h}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let n=b(t?p[e.name]:void 0,g).filter(e=>!_(e.path,v));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=m(A,b(t?p[e.name]:void 0,g),V(l,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...Zs(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...dz(e.name)?{managed:!0}:{}}}):[],C=HJ(Bs),w=Mc(z(Bs,...kD)),T=qB(Bs,`global`),ee=QB(T,`global`),te=new Set(aV(Bs).map(e=>e.name));i.skills=i.skills.filter(e=>!te.has(e.name));let ne=new Set,re=aV(Bs).map(e=>{let t=!ne.has(e.name);ne.add(e.name);let n=t?C[e.name]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:V(Bs,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:o,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(T).length>0?{hostAliases:T}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=m(Bs,b(n,ee),V(Bs,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=b(n,ee).filter(e=>!_(e.path,y));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...Zs(`global`,e.name,e)===`link`?{linkMode:!0}:{},...dz(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??nc(Bs,e.name);return n?{origin:d(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),ie=new Set(S.map(e=>e.name)),E=A&&!r.skills.some(e=>e.name===$s)&&!ie.has($s)?rc(A,$s,`project`):null,D=new Set(re.map(e=>e.name)),ae=mz.map(e=>lz[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!D.has(e)).map(e=>rc(Bs,e,`global`)).filter(e=>e!==null),O=new Set(S.map(e=>e.name));Y(t,200,eee,{skills:[...f(r,s,!0).filter(e=>!O.has(e.name)),...S,...f(i,c,!1),...re,...E?[E]:[],...ae],truncated:r.truncated||i.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),fc=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Rs(r,t,`skill-get`))return;let i=zs(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(dz(r)){let e=i===`global`?Bs:A,a=e?ec(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=js(await pu(a.skillMd,`utf-8`));Y(t,200,yi,{skill:{name:r,scope:i,path:a.relPath,frontmatter:{name:typeof e.name==`string`?e.name:r,description:typeof e.description==`string`?e.description:``},body:n,files:kB(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=Hs(i,r,a);if(o===null){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:a===void 0?`Skill "${r}" not found in ${i} scope.`:`No skill "${r}" (${i}) in ${a}.`});return}let s=V(o,`SKILL.md`),{frontmatter:c,body:l}=js(await pu(s,`utf-8`));Y(t,200,yi,{skill:{name:r,scope:i,path:sc(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:kB(o)}},{handler:`skill-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function pc(e,t){if(!(!oe||vC(e))){if(P)try{await P.rebuildIgnorePatterns()}catch{}await an(e,t,`skill-put`)}}let mc=J(ft,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Rs(n.name,t,`skill-put`)||ic(n.name,t,`skill-put`))return;let r=jP({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){q(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?l:Bs,a=Hs(n.scope,n.name);if(a===null){let a=$B(i,n.scope),o=MP({skillsRoot:V(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){q(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:o.error.code,cause:Error(o.error.message)});return}n.scope===`project`&&(ar(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await lr(`skill-put`)),await pc(n.scope===`project`?`${a}/${n.name}/SKILL`:vr(`global`,n.name),r.content),se?.(`files`),Y(t,200,at,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=B(i,a).split(Al).join(`/`),c=`${o}/SKILL.md`,u=n.scope===`project`?`${o}/SKILL`:vr(n.scope,n.name);if(Os(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=Xn(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Xx(h.dc.document,r.content,`agent`)},h.origin);let g=await Jt(u);if(g?.kind===`failure`){Xt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){Zt(t,`skill-put`);return}n.scope===`project`&&(ar(e,ir(`skill`,``,n.name),`skill-edit: ${c}`),await lr(`skill-put`)),await pc(u,r.content),se?.(`files`),Y(t,200,at,{path:c,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function hc(e,t){let n=e===`project`?l:Bs,r=Hs(e,t);return{root:r===null?Vs(e):R(r),dirRel:r===null?`.ok/skills/${t}`:B(n,r).split(Al).join(`/`),realDir:r}}function gc(e,t){let n=e===`project`?l:Bs,r=(e===`project`?iV(l):aV(Bs)).find(e=>e.name===t);r&&EB({canonicalAbs:V(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>ua(e)),roots:hB(e)})}let _c=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Rs(r,t,`skill-delete`))return;let i=zs(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=hc(i,r),s=Us(n,me);if(s.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await wn(i===`project`?[...new Set([`${o}/SKILL`,vr(i,r)])]:[vr(i,r)],`deleted-upstream`),gc(i,r);let c=LP({skillsRoot:a,name:r}),l=Vs(i);if(c.ok&&l!==a&&H(V(l,r,`SKILL.md`))){let e=LP({skillsRoot:l,name:r});e.ok||Z.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;q(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`&&(ar(s,o,`skill-delete: ${o}`),await lr(`skill-delete`)),se?.(`files`));let u=cc(i);u&&await lc(u,r,i),Y(t,200,Vee,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),vc=J(Pn,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Rs(n.fromName,t,`skill-move`)||!Rs(n.toName,t,`skill-move`)||ic(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=hc(n.scope,n.fromName);if(Hs(n.scope,n.toName)!==null){q(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=cc(n.scope),o=a?aI(a).skills[n.fromName]:void 0,s=n.scope===`project`?l:Bs,c=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.fromName),u=c?R(c.dir):null,d=u===null?[]:Object.entries(qB(s,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?sB(o.hosts):[],...c?sB(c.hosts):[],...sB(d)])];await wn(n.scope===`project`?[...new Set([`${i}/SKILL`,vr(n.scope,n.fromName)])]:[vr(n.scope,n.fromName)],`renamed`),gc(n.scope,n.fromName);let p=await Nse({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await EZ(A,e,t);return n||TZ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){q(t,409,`urn:ok:error:doc-already-exists`,p.error.message,{handler:`skill-move`,detail:p.error.code});return}let e=p.error.code===`MOVE_FAILED`?500:400;q(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:p.error.code,cause:Error(p.error.message)});return}let m=null,h=V(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=js(U(h,`utf-8`));g=e.body,typeof e.frontmatter.description==`string`&&(_=e.frontmatter.description)}catch{}let v=typeof n.body==`string`?n.body:g,y=n.frontmatter===void 0?_:n.frontmatter.description,b=MP({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=uV({base:n.scope===`project`?l:Bs,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){L(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}if(n.scope===`project`&&!m)try{await P?.rebuildIgnorePatterns(),await Dc(r,n.fromName,n.toName),await Oc(x,n.toName)}catch(e){L(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let S=sc(V(r,n.fromName),n.scope),C=sc(V(r,n.toName),n.scope);n.scope===`project`&&(ar(e,ir(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await lr(`skill-move`));let w=Nc(r,n.toName),T=n.scope===`project`?await Pc(Fc(e),C):void 0;if(await qs(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await cI(a,n.fromName),DB(n.fromName,a,f,hB(n.scope));let e=V(r,n.toName);if(f.length>0){let t=xB(e,n.toName,a,f,Gs(n.scope,n.toName),hB(n.scope));await sI(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??fB(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(se?.(`files`),m){let e=m.code===`WRITE_ERROR`;q(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:m.code,cause:Error(m.message)});return}Y(t,200,gee,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),yc=J(Fee,async(e,t,n)=>{let{name:r,home:i}=n;if(!Rs(r,t,`skill-edit-external`))return;let a;try{a=W(i)}catch{q(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!$l(a).isDirectory()||!H(V(a,`SKILL.md`))){q(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}GH(r,a),Y(t,200,Wee,{docName:Rr(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),bc=J($e,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move-scope`});return}let{name:r,fromScope:i,toScope:a}=n;if(!Rs(r,t,`skill-move-scope`))return;if(i===a){q(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!A){q(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:s,realDir:c}=hc(i,r),u=V(o,r),d=(()=>{try{return W(u)}catch{return u}})(),f=a===`project`?l:Bs,p=V(f,$B(f,a)),m=V(p,r);if(c===null||!H(u)){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(V(c)===V(m)||H(m)&&W(c)===W(m)){q(t,409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{handler:`skill-move-scope`,detail:`SAME_STORAGE`});return}if(Hs(a,r)!==null||H(m)){q(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let h=cc(i),g=cc(a),_=h?aI(h).skills[r]:void 0,v=i===`project`?l:Bs,y=(i===`project`?iV(l):aV(Bs)).find(e=>e.name===r),b=y?R(y.dir):null,x=b===null?[]:Object.entries(qB(v,i)).filter(([,e])=>e===b).map(([e])=>e),S=[...new Set([..._?sB(_.hosts):[],...y?sB(y.hosts):[],...sB(x)])];await wn([...new Set([...i===`project`?[`${s}/SKILL`]:[],vr(i,r),vr(a,r)])],`renamed`),Jo(p,{recursive:!0}),Zo(d,m,{recursive:!0,dereference:!0}),gc(i,r);let C=LP({skillsRoot:o,name:r});if(C.ok&&d!==u){let e=B((()=>{try{return W(v)}catch{return v}})(),d);e!==``&&!e.startsWith(`..`)&&!Dl(e)&&Qo(d,{recursive:!0,force:!0})}if(!C.ok){LP({skillsRoot:p,name:r}),q(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:C.error.code,cause:Error(C.error.message)});return}let w=await Js(i,a,r);if(h&&await lc(h,r,i),g&&S.length>0){let e=xB(m,r,g,S,Gs(a,n.name),hB(a));await sI(g,r,{..._,scope:a,hosts:e,scripts:_?.scripts??fB(m,r).hasScripts,installedAt:_?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(ar(e,i===`project`?s:B(l,m).split(Al).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await lr(`skill-move-scope`)),w){let t=Nc(p,r),n=a===`project`?await Pc(Fc(e),B(l,m).split(Al).join(`/`)):void 0;await Ys(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!H(z(m,`SKILL.md`))){q(t,500,`urn:ok:error:internal-server-error`,`The move did not leave a readable skill at the destination; nothing was reported as moved.`,{handler:`skill-move-scope`,detail:B(f,m).split(Al).join(`/`)});return}se?.(`files`),Y(t,200,tte,{scope:a,path:B(f,m).split(Al).join(`/`)},{handler:`skill-move-scope`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),xc=J(Ei,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!Rs(n.name,t,`skill-duplicate`)||!Rs(n.toName,t,`skill-duplicate`)||ic(n.toName,t,`skill-duplicate`))return;let r=Hs(n.scope,n.name);if(r===null||!H(z(r,`SKILL.md`))){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?l:Bs,a=V(i,$B(i,n.scope)),o=V(a,n.toName);if(Hs(n.scope,n.toName)!==null||H(o)){q(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let s=LD(r);if(!s){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}Jo(a,{recursive:!0}),Zo(r,o,{recursive:!0,dereference:!0});let{fenced:c,body:u}=ct(s.skillMd),d=ht(c,{name:n.toName});if(!d.ok){LP({skillsRoot:a,name:n.toName}),q(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:d.error.kind});return}try{rs(z(o,`SKILL.md`),`${d.nextFenced}${u}`)}catch(e){throw LP({skillsRoot:a,name:n.toName}),e}if(n.scope===`project`){let t=B(l,o).split(Al).join(`/`);ar(e,ir(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await lr(`skill-duplicate`)}se?.(`files`),Y(t,200,Cr,{name:n.toName},{handler:`skill-duplicate`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),Sc=nW({GET:fc,PUT:mc,POST:vc,DELETE:_c},{handler:`skill`});function Cc(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<1||t.some(e=>e===`..`)||t.length===1&&t[0].toLowerCase()===`skill.md`?null:t[0]===`references`&&t.length>=2?`reference`:t[0]===`scripts`&&t.length>=2?`script`:`file`}function wc(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Tc(e,t){let n=t.replace(/\.md$/i,``);return`${xi(e).replace(/\/SKILL$/,``)}/${n}`}function Ec(e,t){let n=V(e,t,`references`);if(!H(n))return[];let r=[],i=(e,t)=>{for(let n of Jl(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(V(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function Dc(e,t,n){if(!oe){L(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=U(n,`utf-8`)}catch(i){L(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=B(l,e).split(Al).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),V(e,n,`SKILL.md`));for(let r of Ec(e,n))i(o(t,r),o(n,r),V(e,n,r));await oe.recordDirectMutations(r)}async function Oc(e,t){if(!oe||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await oe.recordDirectMutations(n)}let kc=nW({GET:J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Rs(r,t,`skill-file-get`))return;let i=zs(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=dz(r)?i===`global`?Bs:A:void 0,s=n.searchParams.get(`host`)??void 0,c=o?ec(o,r,s):null;if(a===``||a.includes(`\0`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:Cc(a))??`reference`,u=s,d=o?c?.dir??null:Hs(i,r,u);if(d===null&&u!==void 0){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${r}" (${i}) in ${u}.`});return}let f=d??V(Vs(i),r),p=V(f,a);if(p!==f&&!p.startsWith(`${f}${Al}`)){q(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let m=p,h=a;if(!H(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?nr.map(t=>`${e[1]}${t}`).find(e=>e!==a&&H(V(f,e))):void 0;if(n===void 0){q(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}h=n,m=V(f,n)}let g=await pu(m);if(g.includes(0)){q(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}Y(t,200,Ji,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:J(Jee,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Rs(n.name,t,`skill-file-put`)||ic(n.name,t,`skill-file-put`))return;let r=Cc(n.path);if(r===null){q(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must name a file inside the skill dir, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){q(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=Hs(n.scope,n.name);if(i===null||!H(z(i,`SKILL.md`))){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=B(n.scope===`project`?l:Bs,i).split(Al).join(`/`),o=n.path.replace(/\\/g,`/`),c=wc(n.scope,r,o),u;if(c){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(Os(e,`skill-file-put`,t))return;if(u=!H(V(i,o)),u&&PP(i)>=50){q(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:c,colorSeed:l,clientName:d}=Xn(n),f=await s.getSession(e,r,{displayName:c,colorSeed:l,clientName:d});f.dc.document.transact(()=>{Xx(f.dc.document,n.content,`agent`)},f.origin);let p=await Jt(e);if(p?.kind===`failure`){Xt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){Zt(t,`skill-file-put`);return}}else{let e=FP({skillsRoot:R(i),name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;q(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}u=e.created}n.scope===`project`&&(ar(e,ir(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),await lr(`skill-file-put`)),se?.(`files`),Y(t,200,Ur,{path:o,created:u,kind:r,content:c},{handler:`skill-file-put`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!Rs(i,t,`skill-file-delete`)||ic(i,t,`skill-file-delete`))return;let a=zs(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=Cc(o);if(s===null){q(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let c=Us(n,me);if(c.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=Hs(a,i),d=u===null?Vs(a):R(u);if(wc(a,s,o)){let e=o.replace(/\.md$/i,``);await wn([u===null?Tc(i,o):`${B(l,u).split(Al).join(`/`)}/${e}`],`deleted-upstream`)}let f=IP({skillsRoot:d,name:i,relPath:o});if(!f.ok){let e=f.error.code===`UNLINK_FAILED`?500:400;q(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:f.error.code,cause:Error(f.error.message)});return}f.existed&&a===`project`&&(ar(c,ir(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${B(l,u).split(Al).join(`/`)}/${o}`}`),await lr(`skill-file-delete`)),f.existed&&se?.(`files`),Y(t,200,Ir,{path:o,existed:f.existed,kind:s},{handler:`skill-file-delete`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),Ac=J(ii,async(e,t,n)=>{try{if(!Rs(n.name,t,`skill-file-rename`)||ic(n.name,t,`skill-file-rename`))return;let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let r=n.from.replace(/\\/g,`/`),i=n.to.replace(/\\/g,`/`),a=Cc(r),o=Cc(i);if(a===null||o===null){q(t,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:a===null?r:i});return}let s=Hs(n.scope,n.name);if(s===null){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let c=R(s),u=wc(n.scope,a,r),d=wc(n.scope,o,i),f=B(l,s).split(Al).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&Os(p,`skill-file-rename`,t))return;p!==null&&await wn([p],`deleted-upstream`);let h=Mse({skillsRoot:c,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;q(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,h.error.message,{handler:`skill-file-rename`,detail:h.error.code});return}if(oe){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:U(V(c,n.name,i),`utf-8`)})}catch{e.push({kind:`delete`,documentName:p})}else if(p!==null)e.push({kind:`delete`,documentName:p});else if(m!==null)try{e.push({kind:`upsert`,documentName:m,markdown:U(V(c,n.name,i),`utf-8`)})}catch{}await rn(e,`skill-file-rename`)}n.scope===`project`&&(ar(e,ir(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await lr(`skill-file-rename`)),se?.(`files`),Y(t,200,Ree,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){Z.error({err:e},`[skill-file-rename] failed`),t.headersSent||q(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function jc(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let Mc=QJ;function Nc(e,t){return LD(V(e,t))?.contentHash}async function Pc(e,t){let n=ne?.current;if(!(!n||!e))try{let r=jS(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
|
|
1215
|
-
`).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await lr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Fc=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ic(e){try{let t=cc(e.scope);if(!t)return;let n=mB(t);if(n.length===0)return;let r=xB(V(e.skillsRoot,e.name),e.name,t,n,`copy`,hB(e.scope));if(r.length===0)return;await sI(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){Z.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Lc(e,t){if(t.ok){Y(e,200,gr,t.body,{handler:`skill-import`});return}q(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}async function Rc(e){let{acquiredDir:t,scope:n,sourceLabel:r,ref:i,publisher:a,upstreamSkill:o,actor:s}=e;if(!A)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`No project root resolved.`,detail:`NO_PROJECT_ROOT`};let c=ID(t);if(c)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:c};let u=LD(t);if(!u)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let d=tX(u);if(d)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:d};let f=z(n===`project`?A:Bs,...kD),p=Mc(f),m=n===`project`?l:Bs,h=$B(m,n),g=V(m,h),_=qoe(p,u.contentHash);if(_&&Hs(n,_)!==null)return{ok:!0,body:{name:_,path:`${_}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:r,ref:i,contentHash:u.contentHash,publisher:a},warnings:[]}};let v=kX(u.name),y=e=>Hs(n,e)!==null||H(V(g,e,`SKILL.md`)),b=y(v),x=v;if(b){x=`${v}-imported`;let e=2;for(;y(x);)x=`${v}-imported-${e}`,e+=1}let S=js(u.skillMd).body,C=MP({skillsRoot:g,name:x,body:S,frontmatter:{name:x,description:u.description}});if(!C.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write imported skill.`,detail:C.error.code,cause:Error(C.error.message)};let w=[...C.warnings];for(let e of u.files){let t=FP({skillsRoot:g,name:x,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:eX});if(!t.ok){let n=LP({skillsRoot:g,name:x});return{ok:!1,status:n.ok?400:500,urn:n.ok?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,title:`Failed to write the complete imported skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(n.ok?t.error.message:`${t.error.message}; rollback: ${n.error.message}`)}}}n===`project`&&(ar(s,`${h}/${x}/SKILL`,`skill-import: ${r} -> ${h}/${x}/SKILL.md`),await lr(`skill-import`));let T=Nc(g,x),ee=uO(r),te=n===`project`?await Pc(Fc(s),`${h}/${x}`):void 0;if(await eY(f,e=>MD(e,x,{source:r,...ee?{pluginProvider:ee.provider}:{},ref:i,contentHash:u.contentHash,files:u.files.map(e=>e.relPath),...T===void 0?{}:{localHash:T},...te===void 0?{}:{baselineRef:te},publisher:a,importedAt:new Date().toISOString(),...o===void 0?{}:{skill:o}})),e.skipProjection!==!0)try{let e=mB(m);if(e.length>0){let t=V(g,x),r=hB(n),i=e.filter(e=>{let n=gB(m,e,x,r);return n!==null&&n!==t&&H(n)}),a=i.filter(e=>{let t=gB(m,e,x,r);try{return t!==null&&Hl(t).isSymbolicLink()}catch{return!1}});CB({canonicalAbs:t,canonicalHash:LD(t)?.contentHash??``,canonicalRootRel:h,name:x,cwd:m,targets:e,mode:Zs(n,x,{hosts:[`<source>`,...i],linkedHosts:a}),roots:hB(n)})}}catch(e){L(`skill-import`).warn({err:e,skill:x},`post-import editor fan-out failed (import kept)`)}return se?.(`files`),{ok:!0,body:{name:x,path:`${h}/${x}/SKILL.md`,created:C.created,alreadyImported:!1,...b?{collisionRenamedFrom:u.name}:{},provenance:{source:r,ref:i,contentHash:u.contentHash,publisher:a},warnings:w}}}let zc=J(di,async(e,t,n)=>{let r=()=>{};try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await HD(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??ED(d);if(!p){q(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if($Y(t,p,`skill-import`))return;let m=await OD(p);r=m.cleanup,s=m.ref;let h=RD(m.dir);if(h.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>FD(e.dir)?.name===f);if(!e){q(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){q(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??jc(d)}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Rc({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});n.marketplace===!0&&d.ok&&Yz({source:u,skills:[d.body.name]},kz()),Lc(t,d)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Bc=J(qe,async(e,t,n)=>{let r=()=>{};try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l;try{let e=await HD(i,n.skills[0]),u=e?.source??i,d=e?.spec??ED(u);if(!d){q(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if($Y(t,d,`skills-import-bulk`))return;if(l=e?.publisher??jc(u),d.kind===`well-known`)a=d,o=await wD(d.origin);else{let e=await OD(d);r=e.cleanup,c=e.ref,s=RD(e.dir)}}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let u=[];for(let t of new Set(n.skills)){let r,d,f=()=>{};if(a!==null)try{let e=await OD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,d=t}catch(e){u.push({requested:t,status:e instanceof vD?`not-found`:`failed`,warnings:[],...e instanceof vD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>LD(e.dir)?.name===t);if(!e){u.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,d=e.name}try{let a=await Rc({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:d,actor:e,skipProjection:n.install===!1});if(!a.ok){L(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}u.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){L(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}Y(t,200,wee,{results:u,imported:u.filter(e=>e.status===`imported`).length,alreadyImported:u.filter(e=>e.status===`already-imported`).length,failed:u.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),Vc=8*1024*1024,Hc=32*1024*1024;function Uc(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=V(e,n);return r!==e&&!r.startsWith(e+Al)?null:r}function Wc(e){return new Promise((t,n)=>{let r;try{r=(0,VO.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:Vc}})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>Hc){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function Gc(e,t){return new Promise((n,r)=>{(0,rj.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=Uc(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){Jo(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>Vc){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>Hc){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{Jo(R(n),{recursive:!0}),rs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function Kc(e,t){let n=Wl(z(cu(),`ok-skill-upload-`)),r=()=>{try{Qo(n,{recursive:!0,force:!0})}catch{}};try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){q(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=zs(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=fM({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},me);if(o.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Wc(e)}catch(e){q(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){q(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Gc(c.data,n)}catch(e){q(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Uc(n,e.relPath);if(!r){q(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}Jo(R(r),{recursive:!0}),rs(r,e.data)}let u=RD(n);if(u.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){q(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];Lc(t,await Rc({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let qc=J(Qee,async(e,t,n)=>{try{let e=Vs(n.scope);if(!Rs(n.name,t,`skill-install`))return;if(n.scope===`project`&&!A){q(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=cc(n.scope),i=V(e,n.name),a=n.scope===`project`?l:Bs,o=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name),s=o?V(a,o.dir):i;if(!H(s)){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Jt(n.scope===`project`?`${B(a,s).split(Al).join(`/`)}/SKILL`:vr(n.scope,n.name));let c=fB(s,n.name);if(!c.ok){q(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){let e=[];if(!o){q(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let r=n.scope===`project`?Mt:Gn,i=n.fork.editor===`agents`?`.agents/skills`:r[n.fork.editor]??null;if(i===null){q(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:n.fork.editor});return}let s=V(a,i,n.name),c=V(a,o.dir),u=LD(s);if(u===null||s===c){q(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return}if(u.contentHash===o.contentHash){q(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return}let d=new Date().toISOString().replace(/[:.]/g,`-`),f=(e,t)=>{try{let r=V(Bs,`.ok`,`edit-backups`,`forks`,`${n.name}-${t}-${d}`);Jo(V(r,`..`),{recursive:!0}),Zo(e,r,{recursive:!0})}catch(e){Z.warn({name:n.name,err:e},`[skill-fork] stash failed`)}};if(n.fork.action===`align`)f(s,n.fork.editor),Qo(s,{recursive:!0,force:!0}),CB({canonicalAbs:c,canonicalHash:o.contentHash,canonicalRootRel:R(o.dir),name:n.name,cwd:a,targets:[n.fork.editor].filter(ua),roots:hB(n.scope)});else if(n.fork.action===`make-source`){let e=o.hosts.filter(ua);f(c,`source`),EB({canonicalAbs:c,canonicalHash:o.contentHash,name:n.name,cwd:a,targets:e,roots:hB(n.scope)}),Qo(c,{recursive:!0,force:!0});let t=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name);t&&CB({canonicalAbs:V(a,t.dir),canonicalHash:t.contentHash,canonicalRootRel:R(t.dir),name:n.name,cwd:a,targets:e,roots:hB(n.scope)})}else{let r=n.fork.toName;if(!Ie.test(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:r});return}if((n.scope===`project`?iV(l):aV(Bs)).some(e=>e.name===r)){q(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:r});return}let o=V(a,i,r);Vo(s,o);let c=V(o,`SKILL.md`);try{let{fenced:t,body:n}=ct(U(c,`utf-8`)),i=ht(t,{name:r});i.ok?rs(c,`${i.nextFenced}${n}`):(Z.warn({name:r,reason:i.error.kind},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md still declares the old name — edit the frontmatter to match.`))}catch(t){Z.warn({name:r,err:t},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md could not be updated — edit the frontmatter to match.`)}}se?.(`files`),Y(t,200,jr,{name:n.name,hosts:o.hosts.filter(ua),scripts:!1,warnings:e,warningCodes:e.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){q(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=e=>e.replace(/\\/g,`/`).replace(/^~\//,``),r=o.hosts[0];if(r!==void 0&&(n.remove??[]).some(t=>e(t)===r)){q(t,400,`urn:ok:error:invalid-request`,`"${r}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`});return}let i=new Set(o.hosts.filter(e=>ua(e)));for(let t of n.add??[])ua(t)?i.add(t):p.push(e(t));let s=qB(a,n.scope),c=[],l=[];for(let e of n.add??[])if(ua(e)&&s[e]!==void 0&&!H(V(a,s[e],n.name,`SKILL.md`))){let t=e===`agents`?`.agents/skills`:(n.scope===`project`?Mt:Gn)[e]??null;t!==null&&l.push(t)}for(let t of n.remove??[])if(ua(t)){if(!i.has(t)&&s[t]!==void 0&&H(V(a,s[t],n.name,`SKILL.md`))){let e=t===`agents`?`.agents/skills`:(n.scope===`project`?Mt:Gn)[t]??null;e!==null&&c.push(e)}i.delete(t)}else m.push(e(t));for(let{subRoot:e,exclude:r}of[...l.map(e=>({subRoot:e,exclude:void 0})),...c.map(e=>({subRoot:e,exclude:[n.name]}))]){let n=IJ({base:a,folderRel:e,...r===void 0?{}:{exclude:r}});if(n.ok&&await RJ(a,e,{expect:`own`}),!n.ok){q(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e} following its pool (${n.reason}).`,{handler:`skill-install`,detail:n.reason});return}}f=[...i]}if(u&&!o){let e=u,i=wB({canonicalAbs:s,canonicalHash:LD(s)?.contentHash??``,name:n.name,cwd:a,newTarget:e,roots:hB(n.scope)});if(!i.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:i.reason});return}await cI(r,n.name),await LJ(a,n.name,e),se?.(`files`);let o=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name);Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:B(a,i.newAbs).split(Al).join(`/`)},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?A:Bs;if(!e){q(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.place.dir.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),i=V(e,r),a=`${r}/${n.name}`,l=MB(e,a),u=V(e),d=Ws(r);if(r===``||l===null||!l.startsWith(u+Al)||d){q(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}if(l===V(s)){Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:a},{handler:`skill-install`});return}if(H(l)){q(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}Jo(i,{recursive:!0}),n.place.mode===`link`?Wo(B(i,V(s)),l,`dir`):Zo(s,l,{recursive:!0,dereference:!0});let f=a;await WJ(e,n.name,{path:f,mode:n.place.mode,...n.place.mode===`copy`?{hash:LD(s)?.contentHash}:{}}),se?.(`files`),Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:f},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?A:Bs;if(!e){q(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.unplace.path.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``);if(!HJ(e)[n.name]?.find(e=>e.path===r)){q(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r});return}let i=MB(e,r);if(i===null){q(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}let a=LD(s)?.contentHash??``;switch(SB(i,V(s),a)){case`different`:q(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r});return;case`canonical-dir`:q(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r});return;case`absent`:break;default:Qo(i,{recursive:!0,force:!0})}await UJ(e,n.name,r),se?.(`files`),Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){q(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?A:Bs,l=hB(n.scope),u=ua(e)?e===`agents`?`.agents/skills`:l[e]:e.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),d=u===null||u===``?null:MB(a??r,`${u}/${n.name}`);if(u===null||u===``||d===null){q(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return}let f=V(s),p=o.contentHash,m=SB(d,f,p);if(m===`canonical-dir`){q(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return}if(m===`different`){q(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return}if(m===`absent`){q(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return}let h=i===`link`&&m===`link-to-canonical`||i===`copy`&&m===`same-copy`;if(h&&await WJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}}),!h){let e=R(d);Qo(d,{recursive:!0,force:!0}),Jo(e,{recursive:!0}),i===`link`?Wo(B(e,f),d,`dir`):Zo(f,d,{recursive:!0,dereference:!0}),await WJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}})}se?.(`files`),Y(t,200,jr,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?Et.filter(e=>f?.some(t=>t===e)):[...Et]:f===void 0?mB(r):Et.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),c.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),c.warnings.length>0&&(g.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],v=n.scope===`project`?A:Bs,y=d===void 0?Zs(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=o.hosts[0],i=u,d=ua(i),f;if(!d){let e=i.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),a=Ws(e),o=V(r,e,n.name);if(e===``||a||!o.startsWith(V(r)+Al)){q(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:i});return}f=o}let p;if(e!==void 0&&i!==e){let e=B(a,V(s)).split(Al).join(`/`),c=wB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:d?i:`agents`,...f===void 0?{}:{destDirAbs:f},leaveLinkBehind:!0,roots:hB(n.scope)});if(!c.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}p=B(a,c.newAbs).split(Al).join(`/`),await WJ(v??r,n.name,{path:e,mode:`link`});for(let e of HJ(v??r)[n.name]??[]){let t=V(v??r,e.path);if(t===c.newAbs)continue;try{if(!Hl(t).isSymbolicLink())continue}catch{continue}let n=null;try{n=W(t)}catch{n=null}(n===null||n===V(s))&&(Qo(t,{recursive:!0,force:!0}),Wo(B(R(t),c.newAbs),t,`dir`))}await WJ(v??r,n.name,{path:p,mode:`copy`}),await LJ(v??r,n.name,i)}se?.(`files`);let m=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name);Y(t,200,jr,{name:n.name,hosts:m?[...m.hosts]:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[],...p===void 0?{}:{sourceMovedTo:p}},{handler:`skill-install`});return}let b=o.hosts.filter(e=>ua(e)),x=o.hosts[0],S;if(f!==void 0&&x!==void 0&&!x.includes(`/`)&&i.length>0&&!i.includes(x)){let e=i[0],c=wB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:e,roots:hB(n.scope)});if(!c.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}s=c.newAbs,S=B(a,c.newAbs).split(Al).join(`/`),await WJ(v??r,n.name,{path:S,mode:`copy`}),await LJ(v??r,n.name,e)}let C=S?S.split(`/`).slice(0,-1).join(`/`):e;EB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,targets:f===void 0?[]:b.filter(e=>!i.includes(e)),roots:hB(n.scope)});let w=CB({canonicalAbs:s,canonicalHash:o.contentHash,canonicalRootRel:C,name:n.name,cwd:r,targets:i,mode:y,convertLinks:d===!1,roots:hB(n.scope)});for(let e of w.conflicted)g.push(`A different skill named "${n.name}" already exists in the ${e} skills folder — left untouched.`),_.push(`name-conflict`);if(d!==void 0&&v&&p.length>0){let e=new Set(p.map(e=>`${e}/${n.name}`));for(let t of(HJ(v)[n.name]??[]).filter(t=>e.has(t.path))){let e=V(v,t.path);if(e===V(s))continue;let r=SB(e,V(s),o.contentHash);d===!0&&r===`same-copy`?(Qo(e,{recursive:!0,force:!0}),Wo(B(R(e),V(s)),e,`dir`),await WJ(v,n.name,{path:t.path,mode:`link`})):d===!1&&r===`link-to-canonical`&&(Qo(e,{recursive:!0,force:!0}),Zo(V(s),e,{recursive:!0,dereference:!0}),await WJ(v,n.name,{path:t.path,mode:`copy`,hash:o.contentHash}))}}for(let t of w.hosts){let i=t===`agents`?`.agents/skills`:Mt[t];if(i===null||i===e)continue;let a=V(r,i,n.name),s=!1;try{s=Hl(a).isSymbolicLink()}catch{continue}if(s){y===`link`&&await WJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`link`});continue}let c=H(z(a,`SKILL.md`))?LD(a)?.contentHash:void 0;c!==void 0&&c===o.contentHash&&await WJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`copy`,hash:c})}if((p.length>0||m.length>0)&&v){let e=V(s);for(let t of p){let r=Ws(t),i=V(v,t),a=MB(v,`${t}/${n.name}`);if(t===``||r||a===null||a===e){g.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=SB(a,e,o.contentHash);if(s===`different`){g.push(`A different "${n.name}" already exists at ${t} — left untouched.`),_.push(`name-conflict`);continue}s===`absent`&&(Jo(i,{recursive:!0}),y===`link`?Wo(B(i,e),a,`dir`):Zo(e,a,{recursive:!0,dereference:!0})),await WJ(v,n.name,{path:`${t}/${n.name}`,mode:y,...y===`copy`?{hash:o.contentHash}:{}})}for(let t of m){let r=`${t}/${n.name}`,i=HJ(v)[n.name]?.find(e=>e.path===r),a=MB(v,r);if(a===null){g.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=SB(a,e,o.contentHash);if(s===`different`){g.push(`The copy at ${r} has been hand-edited (a fork) — refused, never deleted. Remove it manually if you mean it.`),_.push(`place-fork-refused`);continue}s!==`absent`&&s!==`canonical-dir`&&Qo(a,{recursive:!0,force:!0}),i&&await UJ(v,n.name,r)}}let T=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name),ee=T?[...T.hosts]:w.hosts;se?.(`files`),Y(t,200,jr,{name:n.name,hosts:ee,scripts:c.hasScripts,warnings:g,warningCodes:_,...S===void 0?{}:{sourceMovedTo:S}},{handler:`skill-install`});return}let v=sB(aI(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&DB(n.name,r,v,hB(n.scope));let y=z(r,...kD),b=H(y)?U(y,`utf-8`):null,x=b===null?null:jD(b);b!==null&&x===null&&Z.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=xB(s,n.name,r,h,C,hB(n.scope));w.length===0?await cI(r,n.name):await sI(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),se?.(`files`),Y(t,200,jr,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Jc=J(Dn,async(e,t,n)=>{try{if(!Rs(n.name,t,`skill-uninstall`))return;let e=cc(n.scope);if(!e){q(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 lc(e,n.name,n.scope);se?.(`files`),Y(t,200,yo,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Yc=nW({GET:J(oo,async(e,t)=>{try{let e=mB(A??``),n=(e,t)=>{let n=zJ(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};Y(t,200,yt,{targets:e,configured:!1,folders:[...A?jJ(l,XB(l,`project`)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...jJ(Bs,XB(Bs,`global`)).map(e=>({...e,scope:`global`,...n(Bs,e)}))]},{handler:`skill-targets-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(ree,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:Bs;if(e.scope===`project`&&!A){q(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await BJ(r,i.join(`/`)),se?.(`files`),Y(t,200,Qt,{targets:mB(A??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(XB(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){q(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?FJ({base:r,folderRel:e.root,targetRootRel:a}):IJ({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){q(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await RJ(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),se?.(`files`),Y(t,200,Qt,{targets:mB(A??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),Xc=J(Be,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Rs(n.name,t,`skill-restore`)||ic(n.name,t,`skill-restore`))return;if(n.scope===`global`){q(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=ne?.current;if(!r){q(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await JJ({shadow:r,contentDir:l,contentRoot:O??`.`,name:n.name,version:n.version,skillDirRel:Qs(n.name)});if(!i.ok){Xs(t,i,`skill-restore`);return}let a=[],o=fB(V(l,Qs(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),ar(e,ir(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await lr(`skill-restore`),se?.(`files`),Y(t,200,Pi,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Zc=J(pee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Rs(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Bs:l,{root:a,dirRel:o,realDir:s}=hc(n.scope,n.name),c=!o.startsWith(`${Pa}/`);if(s===null||!H(V(i,o,`SKILL.md`))){q(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=z(n.scope===`global`?Bs:A,...kD),d=Mc(u).skills[n.name];if(!d){let e=Koe(n.name,LD(V(a,n.name))?.contentHash??``,new Date().toISOString())??nc(i,n.name);e&&(d=e)}if(!d){q(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await eY(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),Y(t,200,Vi,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=await HD(d.source,d.skill??n.name),i=e?.source??pO(d.source,d.pluginProvider),a=e?.skill??d.skill,o=e?.spec??ED(i);if(!o){q(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if($Y(t,o,`skill-reimport`))return;let s=await OD(o);r=s.cleanup,f=s.ref;let c=RD(s.dir),l=(a?c.find(e=>e.name===a):void 0)??c.find(e=>e.name===n.name)??c.find(e=>LD(e.dir)?.name===n.name)??(c.length===1?c[0]:void 0);if(!l){q(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:c.map(e=>e.name).join(`, `)});return}let u=ID(l.dir);if(u){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:u});return}p=LD(l.dir)}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=tX(p);if(h){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=LD(V(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){Y(t,200,Vi,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=js(p.skillMd).body;if(n.dryRun){let e=LD(V(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&A)try{let e=gs({baseDir:A,timeout:{block:15e3}}),t=B(A,V(a,n.name)).split(Al).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}Y(t,200,Vi,{name:n.name,updated:!0,source:d.source,localBody:js(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await wn(e,`deleted-upstream`)}let x=MP({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){q(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=FP({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:eX});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=IP({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(ar(e,ir(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await lr(`skill-reimport`));let C=Nc(a,n.name),w=n.scope===`project`?await Pc(Fc(e),o):void 0;await eY(u,e=>MD(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!c&&n.scope===`project`&&await Ic({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),se?.(`files`),Y(t,200,Vi,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Qc=J(lee,async(e,t,n)=>{try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Rs(n.name,t,`skill-revert`)||ic(n.name,t,`skill-revert`))return;if(n.scope===`global`){q(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=z(A,...kD),i=Mc(r).skills[n.name];if(!i?.baselineRef){q(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=ne?.current;if(!a){q(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await JJ({shadow:a,contentDir:l,contentRoot:O??`.`,name:n.name,version:i.baselineRef,skillDirRel:Qs(n.name)});if(!o.ok){Xs(t,o,`skill-revert`);return}ar(e,ir(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await lr(`skill-revert`);let s=V(l,Qs(n.name),`..`),c=Nc(s,n.name);await eY(r,e=>MD(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Vs(`project`)&&await Ic({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),se?.(`files`),Y(t,200,sn,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function $c(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])=>We({kind:`folder`,path:e,modifiedTs:t}))}function el(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 tl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function nl(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 rl(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function il(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function al(e,t,n,r){let i=r.documents.filter(e=>!Xa(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Oe?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Oe.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Oe.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=ke?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Oe.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function ol(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`?el(e.document.content,t):void 0}}async function sl(e){let t=performance.now();if(gl())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await _l(),i=await al(e.query,e.intent,e.semanticParam,n),a=xee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>ol(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},uce({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 cl(){let e=[],t=new Set;for(let n of iV(l)){let r=V(l,n.dir,`SKILL.md`);try{let i=$l(r);e.push({name:n.name,absolutePath:r,docPath:`${n.dir}/SKILL`,mtimeMs:i.mtimeMs,size:i.size}),t.add(n.name)}catch{}}let n=Vs(`project`);if(!H(n))return e;let r;try{r=Jl(n,{withFileTypes:!0})}catch{return e}for(let i of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!i.isDirectory()||!Ie.test(i.name)||t.has(i.name))continue;let r=V(n,i.name,`SKILL.md`);try{let t=$l(r);e.push({name:i.name,absolutePath:r,docPath:`${Pa}/${i.name}/SKILL`,mtimeMs:t.mtimeMs,size:t.size})}catch{}}return e}function ll(){let e=[];for(let t of cl()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=js(U(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(We({kind:`page`,path:t.docPath,title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function ul(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let dl=new Map;async function fl(){let e=[],t=[],n=new Set;for(let[r,i]of m()){if(fC(r)||pC(r)||ra(r)?.kind===`skill`||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(We({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=ul(i),o=dl.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await pu(i.canonicalPath,`utf-8`)}catch(e){l=!0,Z.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=xR(s,r)}catch(e){Z.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=We({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||dl.set(r,{key:a,doc:u}),e.push(u)}for(let e of dl.keys())n.has(e)||dl.delete(e);let r=VX(),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),L(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),hX().add(1)),{documents:[...e,...ll(),...i,...$c([...e,...i])],truncated:a}}function pl(){return cl().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function ml(){return g?`gen:${g()}|skills${pl()}`:`${[...m()].filter(([e])=>!fC(e)&&!pC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${ul(t)}`).join(``)}|skills${pl()}`}let hl=Ce===void 0;Ce?.then(()=>{hl=!0},e=>{hl=!0,Z.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function gl(){return!hl}async function _l(){let e=`${l}${A??``}`,t=ml(),n=DZ.get(e);if(n?.fingerprint===t&&n.corpus)return{corpus:n.corpus,truncated:n.truncated??!1};if(n?.fingerprint===t&&n.pending)return n.pending;let r=n?.corpus,i=n?.pending,a=(async()=>{let e=i?await i.then(e=>e.corpus,()=>void 0):r,{documents:t,truncated:n}=await fl();if(!e)return _X().add(1,{mode:`cold`}),{corpus:cte(t),truncated:n};let a=kt(e,t);if(a.rebuilt){_X().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;L(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else _X().add(1,{mode:`incremental`}),L(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();DZ.set(e,{fingerprint:t,pending:a});try{let n=await a;return DZ.get(e)?.pending===a&&DZ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw DZ.get(e)?.pending===a&&DZ.delete(e),t}}function vl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{_l().catch(e=>{Z.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}vl();let yl=nW({GET:J(oo,tW(async(e,t)=>{let n=ws(e),r=n.get(`limit`),i=n.get(`query`)??``,a=tl(n.get(`intent`)),o=oc(n.get(`ranking`)),s=nl(n.get(`scope`)??n.get(`scopes`)),c=rl(n.get(`semantic`)),l=il(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}Y(t,200,Ua,await sl({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:J(Xr,tW(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=tl(n.intent),a=oc(n.ranking),o=nl(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=rl(n.semantic),l=il(n.source);if(r.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}Y(t,200,Ua,await sl({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`}),bl=J(oo,tW(async(e,t)=>{Y(t,200,ste,{...await Wz(au())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Sl(e,t){if(r(e,t,{handler:`handoff`}))try{await Uce(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:bt.probeWithCache})}catch(n){t.headersSent||(Z.error({err:n,requestId:CC(e)},`[handoff] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Cl(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await VF(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Z.error({err:n,requestId:CC(e)},`[spawn-cursor] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Tl=J(cr,async(e,t,n)=>{try{if(!A){AR(`no-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`no-remote`},{handler:ER});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!DR(e,n.kind)){AR(`invalid-path`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`invalid-path`},{handler:ER});return}let r=FR(A);if(r===null){if(zR(A).kind===`no-remote`){AR(`no-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`no-remote`},{handler:ER});return}AR(`detached-head`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`detached-head`},{handler:ER});return}let i=zR(A);if(i.kind===`no-remote`){AR(`no-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`no-remote`},{handler:ER});return}if(i.kind===`non-github`){AR(`non-github-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`non-github-remote`},{handler:ER});return}if(!UR(A,r)){AR(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),Y(t,200,yn,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:ER});return}let a=yZ(A,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&L(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=OR(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=kR(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Vu(s)}`,u=await MR(A,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);AR(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),Y(t,200,yn,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:ER})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:ER,cause:e})}},{handler:ER,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ER})}),Ol=J(oo,async(e,t)=>{try{if(!A){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:VU});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(!Yi(r)){q(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:VU});return}if(!zU(i,a)){q(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:VU});return}Y(t,200,iee,await BU(A,r,i,a),{handler:VU})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:VU,cause:e})}},{handler:VU,method:`GET`,skipBodyParse:!0}),kl=J(Di,async(e,t,n)=>{try{if(!A){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:az});return}if(!zU(n.path,n.kind)){q(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:az});return}let e=yZ(A,l);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;Y(t,200,wr,await cz(A,n.branch,r,n.kind),{handler:az})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:az,cause:e})}},{handler:az,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:az})}),jl=J(rr,async(e,t,n)=>{if(fM(n,me).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:KU});return}if(!A){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:KU});return}try{Y(t,200,Oee,await _s(()=>JU(A,n.branch,{fastForward:n.fastForward===!0})),{handler:KU})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:KU,cause:e})}},{handler:KU,method:`POST`});async function Ml(e){let[t,...n]=de,r=[...n,...e];return await new Promise((e,n)=>{let i=xl(t,r,NF({...Ba,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},qR),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${qR}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=iz(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Z.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 Nl=J(oo,async(e,t)=>{if(!Ye.tryAcquire(`/api/share/publish/owners`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:WR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ml([`share`,`owners`,`--json`]),n=ZR(XR(e));rz(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),Y(t,200,qee,n,{handler:WR})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:WR,cause:e})}finally{Ye.release(`/api/share/publish/owners`)}},{handler:WR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:WR})}),Pl=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!YR(r)||!JR(i)){q(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:GR});return}if(!Ye.tryAcquire(`/api/share/publish/name-check`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:GR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ml([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=$R(XR(e));rz(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),Y(t,200,Zr,n,{handler:GR})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:GR,cause:e})}finally{Ye.release(`/api/share/publish/name-check`)}},{handler:GR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:GR})}),Fl=J(la,async(e,t,n)=>{if(!A){rz(`publish-create`,`no-project`),Y(t,200,Na,{ok:!1,error:`no-project`},{handler:KR});return}if(!YR(n.owner)||!JR(n.name)){q(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:KR});return}if(!Ye.tryAcquire(`/api/share/publish`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:KR,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,A,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Ml(e),i=nz(XR(r));rz(`publish-create`,i.ok?`ok`:i.error),i.ok&&ue?.()?.refreshRemote().catch(()=>{}),Y(t,200,Na,i,{handler:KR})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:KR,cause:e})}finally{Ye.release(`/api/share/publish`)}},{handler:KR,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:KR})}),Il=J(cee,async(e,t,n)=>{try{let e=L(`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{}Y(t,200,uee,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Ll=A?rN(A):null;async function Rl(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:dM(e.headers),previewUrl:null,port:Ll?As(Ll)?.port??0:0,singleFile:Re};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}Y(t,200,lte,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function zl(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Ue?.()??{diagnostics:[]};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}Y(t,200,ge,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Vl=`local-op-embeddings-set-key`,Gl=`local-op-embeddings-clear-key`,Kl=`/api/local-op/embeddings`;function ql(){let e=Ae?.();return{projectDir:A??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Yl=J(Yr,async(e,t,n)=>{if(!Ye.tryAcquire(Kl)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Vl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=ql();await new DF(I).setForProject(e,r,n.key),Oe?.reloadCredential(),Y(t,200,Fe,{keyPresent:!0},{handler:Vl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Vl,cause:e})}finally{Ye.release(Kl)}},{handler:Vl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Vl})}),Xl=J(oo,async(e,t)=>{if(!Ye.tryAcquire(Kl)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Gl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=ql();await new DF(I).clearForProject(e,n),Oe?.reloadCredential(),Y(t,200,Fe,{keyPresent:!1},{handler:Gl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Gl,cause:e})}finally{Ye.release(Kl)}},{handler:Gl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Gl})}),Zl=`local-op-embeddings-test`,Ql=`/api/local-op/embeddings/test`,nu=J(oo,async(e,t)=>{if(!Ye.tryAcquire(Ql)){q(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Zl,extraHeaders:{"Retry-After":`5`}});return}try{let e=Ae?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await bF(new DF(I),A??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await yce({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};Y(t,200,Kee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Zl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Zl,cause:e})}finally{Ye.release(Ql)}},{handler:Zl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zl})}),ru=J(oo,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Oe){let t=Oe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Ae?.()?.baseUrl??`https://api.openai.com/v1`,o=await bF(new DF(I),A??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of f())!fC(e)&&!pC(e)&&!Xa(e)&&(p+=1);Y(t,200,ca,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),iu=0;function ou(){iu+=1,se?.(`lint-config`)}let su=()=>`${iu} ${t.getActiveBranch()}`;async function lu(e,t){let n=je?.()??Ze;try{let r=await oa(e,FL(l,n,{docName:t,projectDir:A??l,onProblem:e=>Z.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Me?.()??`warning`;if(oe&&a!==`off`&&!vC(t)){await on(t,e,`lint-validation`);let r=nR({projectDir:A??l,contentDir:l,baseConfig:n,derivedDocumentIndex:oe,linksValidation:a,admittedDocNames:tn,docFilePathFor:e=>uZ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:uZ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Z.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function uu(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=RL({projectDir:A??l,contentDir:l});return sL(t.schemas,n)}let du=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!kZ(n))){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=je?.()??Ze,i=[],a=ML(l,n??void 0,e=>i.push(e)),o=PL(A??l,NL(r,a),e=>i.push(e));n===null&&i.push(...uu(o)),Y(t,200,_i,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){q(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}),fu=J(ate,async(e,t,n)=>{let r;try{r=eR(V(l),n.ruleId,n.value)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){q(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}ou();try{let e=je?.()??Ze,n=[],r=ML(l,void 0,e=>n.push(e)),i=PL(A??l,NL(e,r),e=>n.push(e));n.push(...uu(i)),Y(t,200,_i,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){q(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`}),mu=J(ni,async(e,t,n)=>{let r;try{let e=V(A??l),t=n.parentPath??[];r=n.delete?JL(e,n.file):n.field!==void 0&&n.removeField?KL(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?qL(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?UL(e,n.file,n.field,n.constraint,t):WL(e,n.file)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){q(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&se?.(`files`),ou();try{let e=je?.()??Ze,n=[],r=ML(l,void 0,e=>n.push(e)),i=PL(A??l,NL(e,r),e=>n.push(e));n.push(...uu(i)),Y(t,200,_i,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),hu=J(oo,async(e,t)=>{try{let e=V(A??l),{schemas:n,truncated:r}=kle(e),i=new Set(n),a=!1;if(P!==void 0){let t=qX({contentDir:l,contentFilter:P,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Ki(a)){let t=B(e,V(l,a));!t.startsWith(`..`)&&!Dl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));Y(t,200,Lee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),gu=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=o.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},_u=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!kZ(n)){q(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=uZ(l,n);if(r===null){q(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=je?.()??Ze,a=[],o=await LL({projectDir:A??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:gu});Y(t,200,li,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof OI){q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),vu=new rL,yu=AJ();function bu(e,t,n){let r=`${n} ${su()} ${t??``}`;return yu.run(r,()=>rR(e,{targetPath:t})).promise}function xu(e,t){q(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Su=J(oo,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&&!YX(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=je?.()??Ze;Y(t,200,$i,await zL({projectDir:A??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:gu,cache:vu,auditGeneration:su}),{handler:`lint-audit`})}catch(e){if(e instanceof IL){xu(t,`lint-audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),wu=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!YX(i)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!YX(o)){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=uZ(l,o)??`${o}.md`}let s=je?.()??Ze,c=await bu(nR({projectDir:A??l,contentDir:l,baseConfig:s,liveSourceFor:gu,derivedDocumentIndex:oe??null,linksValidation:Me?.(),admittedDocNames:tn,docFilePathFor:e=>uZ(l,e),cache:vu,auditGeneration:su}),i,rL.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){Y(t,200,kr,tR(c),{handler:`audit`});return}Y(t,200,rte,c,{handler:`audit`})}catch(e){if(e instanceof IL){xu(t,`audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),Tu=J(mr,async(t,n,r)=>{try{let t=eZ(r.docName,n,`lint-fix`);if(t===null)return;let i=It(t),a=fM(r,me);if(a.kind===`invalid-summary`){q(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(fC(i)||pC(i)){q(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=uZ(l,i);if(f===null){q(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}tZ(V(l,f),l);let p=je?.()??Ze,{stored:m}=Qn(a.summary),h=await s.getSession(i,o,{displayName:c,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Xle({projectDir:A??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Br(d),n=Nr[t]??Gi(u??o);ce?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{VT(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,zT(h))},h.origin),a.kind!==`anonymous`&&tF(i,o,c,u,void 0,a.kind===`agent`?Zn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{ce?.touchMode(o,`idle`)}let t=await Jt(i);if(t?.kind===`failure`){Xt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Zt(n,`lint-fix`);return}Wt(i,`lint-fix`);try{b=await oa(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Z.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;Y(n,200,Xee,{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 OI){q(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof NC){PC(n,e,`lint-fix`);return}if(e instanceof RC){BC(n,e,`lint-fix`);return}if(e instanceof ZT){q(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e},`[lint-fix] handler failed`),q(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Eu=`link-preview`,Du=new lG({cacheDir:Re?null:V(A??l,`.ok`,`local`,`link-previews`)}),Ou=null,ku=()=>(Ou??=Du.init(),Ou),Au=ze??eG;async function Mu(e){let t=await Au(e);return t.ok?{ok:!0,metadata:await aG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Au})}:{ok:!1,reason:t.reason}}let Pu=()=>{try{return Ve?.()===!0}catch{return!1}},Fu=J(qi,async(e,t,n)=>{try{if(!Pu()){Z.debug({outcome:`disabled`},`[link-preview] request outcome`),Y(t,200,Ya,{ok:!1,reason:`disabled`},{handler:Eu});return}await ku();let e=!1,r=await Du.load(n.url,()=>(e=!0,Mu(n.url)));Du.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Z.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),Y(t,200,Ya,i,{handler:Eu})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Eu,cause:e})}},{handler:Eu,method:`POST`,preBodyGate:(e,t)=>{let n=fG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?q(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Eu}):q(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Eu}),!1)}}),Iu=GM({service:St,getPrincipal:me,onChanged:()=>se?.(`comments`)}),Lu={"/api/config":Rl,"/api/config/diagnostics":zl,"/api/comments":nW({GET:Iu.list,POST:Iu.create},{handler:`comments`}),"/api/comment":nW({GET:Iu.read,POST:Iu.mutate,DELETE:Iu.remove},{handler:`comment`}),"/api/asset":ga,"/api/asset-text":va,"/api/document":Mr,"/api/documents":Pr,"/api/backlinks":Fr,"/api/backlink-counts":ei,"/api/comment-counts":ti,"/api/link-preview":Fu,"/api/forward-links":oi,"/api/link-graph":si,"/api/dead-links":mi,"/api/orphans":ci,"/api/hubs":fi,"/api/tags":vs,"/api/pages":Aa,"/api/folder-config":Es,"/api/template":Fs,"/api/template/import":Ls,"/api/templates":ks,"/api/skill":Sc,"/api/skill-file":kc,"/api/skill-file/rename":Ac,"/api/skills":dc,"/api/skills/installed":zr,"/api/skills/search":Vr,"/api/skills/popular":Wr,"/api/skills/detail":Kr,"/api/skills/preview":qr,"/api/skills/discover":Jr,"/api/skills/resolve-ref":$r,"/api/skill/import":zc,"/api/skills/import-bulk":Bc,"/api/skill/edit-external":yc,"/api/skill/duplicate":xc,"/api/skill/move-scope":bc,"/api/skill-upload":Kc,"/api/skill/install":qc,"/api/skill/uninstall":Jc,"/api/skill/restore":Xc,"/api/skill/reimport":Zc,"/api/skill/revert":Qc,"/api/skill-targets":Yc,"/api/search":yl,"/api/semantic-status":ru,"/api/lint/config":du,"/api/lint/markdownlint-config":fu,"/api/lint/frontmatter-schema":mu,"/api/lint/frontmatter-schemas":hu,"/api/lint":_u,"/api/lint/audit":Su,"/api/lint/fix":Tu,"/api/audit":wu,"/api/suggest-links":ja,"/api/page-headings":Ta,"/api/create-page":xa,"/api/create-folder":Ca,"/api/duplicate-path":wa,"/api/rename-path":Ea,"/api/delete-path":Da,"/api/trash/cleanup":ka,"/api/upload":Fa,"/api/agent-write":yr,"/api/agent-write-md":br,"/api/agent-write-batch":xr,"/api/frontmatter-patch":Dr,"/api/agent-patch":hi,"/api/agent-undo":gi,"/api/agent-activity":Si,"/api/agent-burst-diff":Ci,"/api/save-version":Ni,"/api/history":Fi,"/api/rollback":zi,"/api/metrics/reconciliation":Bi,"/api/metrics/parse-health":Hi,"/api/metrics/agent-presence":aa,"/api/metrics/agent-effects":da,"/api/metrics/watcher-recent":fa,"/api/__embed-detect":pa,"/api/server-info":Wi,"/api/acp/catalog":ta,"/api/share/construct-url":Tl,"/api/share/target-status":kl,"/api/git/branch-info":Ol,"/api/git/checkout":jl,"/api/share/publish/owners":Nl,"/api/share/publish/name-check":Pl,"/api/share/publish":Fl,"/api/principal":ia,"/api/rescue":ya,"/api/workspace":ma,"/api/sync/status":es,"/api/sync/trigger":ns,"/api/sync/conflicts":is,"/api/sync/conflict-content":os,"/api/sync/resolve-conflict":as,"/api/local-op/clone":Wa,"/api/local-op/ok-init":Ja,"/api/local-op/auth/login":To,"/api/local-op/auth/status":Po,"/api/local-op/auth/pat":Io,"/api/local-op/auth/gh-login":ko,"/api/local-op/auth/cancel":jo,"/api/local-op/auth/repos":zo,"/api/local-op/auth/signout":Go,"/api/local-op/auth/set-identity":$o,"/api/local-op/embeddings/set-key":Yl,"/api/local-op/embeddings/clear-key":Xl,"/api/local-op/embeddings/test":nu,"/api/installed-agents":hs,"/api/spawn-cursor":Cl,"/api/handoff":Sl,"/api/install-skill":ps,"/api/skill/install-state":bl,"/api/seed/plan":ls,"/api/seed/apply":ds,"/api/seed/packs":fs,"/api/client-logs":Il};w&&(Lu[`/api/test-reset`]=Ai,Lu[`/api/test-flush-git`]=wi,Lu[`/api/test-rescan-backlinks`]=ji,Lu[`/api/test-rescan-files`]=Mi);let Ru=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),zu=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let r=e.url?.split(`?`)[0];if(!r)return;let a=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};Xse({ts:Date.now(),url:r,method:e.method??``,ua:a(`user-agent`),origin:a(`origin`),referer:a(`referer`),host:a(`host`),remote:e.socket?.remoteAddress,secChUa:a(`sec-ch-ua`),secChUaMobile:a(`sec-ch-ua-mobile`),secChUaPlatform:a(`sec-ch-ua-platform`),secFetchSite:a(`sec-fetch-site`),secFetchDest:a(`sec-fetch-dest`),secFetchMode:a(`sec-fetch-mode`),secFetchUser:a(`sec-fetch-user`)});let o=e.method??`GET`,s=r;r.startsWith(`/api/history/`)?s=`/api/history/:sha`:r.startsWith(`/api/tags/`)?s=`/api/tags/:name`:Lu[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?Vae(e):void 0;if(c!==void 0&&(Hae(e,c),typeof t.setHeader==`function`&&t.setHeader(xC,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Z.info({event:`api.access`,requestId:c,method:o,route:s,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${o} ${s} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(r.startsWith(`/api/`)){let r=e.headers.origin;if(r!==void 0&&!wj(r,n)){q(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(r!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,r),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${xC}, ${Ln.protocol}, ${Ln.runtime}, ${Ln.kind}`),t.setHeader(`Access-Control-Expose-Headers`,xC)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Ru.has(r)||zu.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!pj(n)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Re&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!pj(n)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=wo.extract(Eo.active(),e.headers),u=dte(),d=Date.now();await Eo.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:ute.SERVER,attributes:{[us]:o,[ss]:s,[cs]:r,[pte]:`http`,[fte]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=Lu[r],a=!1;if(i)a=!0,await i(e,t);else if(r.startsWith(`/api/history/`)){let n=decodeURIComponent(r.slice(13));n&&(a=!0,await Li(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await ys(e,t,n))}a||q(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${o} ${r}`});let s=t.statusCode;n.setAttribute(ms,s),s>=500&&n.setStatus({code:Co.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:Co.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s,cause:e}),e}finally{n.end();let e=(Date.now()-d)/1e3;nX().record(e,{[us]:o,[ss]:s,[ms]:t.statusCode})}}))}}}function MZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function NZ(e){let t;try{t=Jl(e.contentDir,{withFileTypes:!0})}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&tC(n.name,c)&&e.basenameIndex.add(n.name)}async function PZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await mu(i,{withFileTypes:!0})}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=z(i,o.name),s=Tj(B(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await fu(a)}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await hu(a)}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Ej(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await gu(i)}catch(t){let n=MZ(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()&&tC(a,u)&&!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()&&tC(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const FZ=M({principalId:F().optional(),tabSessionId:F().optional(),expectedServerInstanceId:F().optional(),expectedBranch:F().optional(),expectedDocLineageEpoch:F().optional(),clientProtocolVersion:N().optional(),clientRuntimeVersion:F().optional(),clientKind:F().optional()}).loose(),IZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function LZ(e){return IZ.includes(e)}function RZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function zZ(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!LZ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var BZ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=RZ(e,this.payload)}};function VZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=FZ.safeParse(t);return n.success?n.data:void 0}var HZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const UZ=L(`conflict-storage`);var WZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=z(rN(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!H(this.storePath)){this.conflicts=[];return}try{let e=U(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){UZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){UZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=R(this.storePath);H(e)||Ul(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return tu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return UZ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-uBCwtyAf.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(!Ej(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);dV(r,t),rs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),UZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await aS(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){UZ.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}),UZ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=V(this.projectDir),a=V(i,e.file);if(!Ej(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(dV(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-uBCwtyAf.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);dV(a,i),rs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);rs(a,n,`utf-8`);break;case`delete`:H(a)&&Uo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function GZ(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 KZ(e,t){let n=rN(e);try{Ul(n,{recursive:!0}),tu(z(n,er),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=ds(e);Ul(R(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`};tu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const qZ=new Map;let JZ=!1;function YZ(e,t){try{let n=GZ(e,t);for(let e of qZ.keys())KZ(e,n)}catch{}}function XZ(e){qZ.set(e,(qZ.get(e)??0)+1),JZ||(JZ=!0,process.on(`uncaughtExceptionMonitor`,YZ));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=qZ.get(e)??0;n<=1?qZ.delete(e):qZ.set(e,n-1)}}}function ZZ(e){let t=e.scheduler??Ba,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 QZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $Z(e){if(!H(e))return{};let t;try{t=(0,nj.parse)(U(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(!QZ(t))return{};let n=t.telemetry;if(!QZ(n))return{};let r=n.localSink;return QZ(r)?r:{}}function eQ(e){return typeof e==`boolean`?e:void 0}function tQ(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function nQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function rQ(e){if(QZ(e))return tQ(e.maxBytes)}function iQ(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=$Z(Fo(`project`,e.projectDir)),n=$Z(Fo(`project-local`,e.projectDir));if((eQ(n.enabled)??eQ(t.enabled)??!0)===!1)return null;let r=rQ(n.spans)??rQ(t.spans)??52428800,i=rQ(n.logs)??rQ(t.logs)??26214400,a=nQ(n.attributeDenylist)??nQ(t.attributeDenylist)??Ee;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var aQ;(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})(aQ||={});var oQ;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(oQ||={});const sQ=aQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),cQ=e=>{switch(typeof e){case`undefined`:return sQ.undefined;case`string`:return sQ.string;case`number`:return Number.isNaN(e)?sQ.nan:sQ.number;case`boolean`:return sQ.boolean;case`function`:return sQ.function;case`bigint`:return sQ.bigint;case`symbol`:return sQ.symbol;case`object`:return Array.isArray(e)?sQ.array:e===null?sQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?sQ.promise:typeof Map<`u`&&e instanceof Map?sQ.map:typeof Set<`u`&&e instanceof Set?sQ.set:typeof Date<`u`&&e instanceof Date?sQ.date:sQ.object;default:return sQ.unknown}},Q=aQ.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 lQ=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,aQ.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()}};lQ.create=e=>new lQ(e);const uQ=(e,t)=>{let n;switch(e.code){case Q.invalid_type:n=e.received===sQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Q.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,aQ.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:n=`Unrecognized key(s) in object: ${aQ.joinValues(e.keys,`, `)}`;break;case Q.invalid_union:n=`Invalid input`;break;case Q.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${aQ.joinValues(e.options)}`;break;case Q.invalid_enum_value:n=`Invalid enum value. Expected ${aQ.joinValues(e.options)}, received '${e.received}'`;break;case Q.invalid_arguments:n=`Invalid function arguments`;break;case Q.invalid_return_type:n=`Invalid function return type`;break;case Q.invalid_date:n=`Invalid date`;break;case Q.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}"`:aQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Q.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 Q.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 Q.custom:n=`Invalid input`;break;case Q.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Q.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Q.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,aQ.assertNever(e)}return{message:n}};let dQ=uQ;function fQ(){return dQ}const pQ=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 mQ(e,t){let n=fQ(),r=pQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===uQ?void 0:uQ].filter(e=>!!e)});e.common.issues.push(r)}var hQ=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 gQ;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 gQ;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 gQ=Object.freeze({status:`aborted`}),_Q=e=>({status:`dirty`,value:e}),vQ=e=>({status:`valid`,value:e}),yQ=e=>e.status===`aborted`,bQ=e=>e.status===`dirty`,xQ=e=>e.status===`valid`,SQ=e=>typeof Promise<`u`&&e instanceof Promise;var CQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(CQ||={});var wQ=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 TQ=(e,t)=>{if(xQ(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 lQ(e.common.issues);return this._error=t,this._error}}};function EQ(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 DQ=class{get description(){return this._def.description}_getType(e){return cQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hQ,ctx:{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(SQ(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:cQ(e)};return TQ(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:cQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return xQ(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=>xQ(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:cQ(e)},r=this._parse({data:e,path:n.path,parent:n});return TQ(n,await(SQ(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:Q.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 k$({schema:this,typeName:$.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 A$.create(this,this._def)}nullable(){return j$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return u$.create(this)}promise(){return O$.create(this,this._def)}or(e){return p$.create([this,e],this._def)}and(e){return _$.create(this,e,this._def)}transform(e){return new k$({...EQ(this._def),schema:this,typeName:$.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new M$({...EQ(this._def),innerType:this,defaultValue:t,typeName:$.ZodDefault})}brand(){return new F$({typeName:$.ZodBranded,type:this,...EQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new N$({...EQ(this._def),innerType:this,catchValue:t,typeName:$.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return I$.create(this,e)}readonly(){return L$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const OQ=/^c[^\s-]{8,}$/i,kQ=/^[0-9a-z]+$/,AQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jQ=/^[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,MQ=/^[a-z0-9_-]{21}$/i,NQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,PQ=/^[-+]?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)?)??$/,FQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let IQ;const LQ=/^(?:(?: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])$/,RQ=/^(?:(?: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])$/,zQ=/^(([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]))$/,BQ=/^(([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])$/,VQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,HQ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,UQ=`((\\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])))`,WQ=RegExp(`^${UQ}$`);function GQ(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 KQ(e){return RegExp(`^${GQ(e)}$`)}function qQ(e){let t=`${UQ}T${GQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function JQ(e,t){return!!((t===`v4`||!t)&&LQ.test(e)||(t===`v6`||!t)&&zQ.test(e))}function YQ(e,t){if(!NQ.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 XQ(e,t){return!!((t===`v4`||!t)&&RQ.test(e)||(t===`v6`||!t)&&BQ.test(e))}var ZQ=class e extends DQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==sQ.string){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.string,received:t.parsedType}),gQ}let t=new hQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.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),mQ(n,{code:Q.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?mQ(n,{code:Q.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&mQ(n,{code:Q.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)FQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`email`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)IQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),IQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`emoji`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)jQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`uuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)MQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`nanoid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)OQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`cuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)kQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`cuid2`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)AQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`ulid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),mQ(n,{validation:`url`,code:Q.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),mQ(n,{validation:`regex`,code:Q.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),mQ(n,{code:Q.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),mQ(n,{code:Q.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?qQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?WQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?KQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?PQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`duration`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?JQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`ip`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?YQ(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`jwt`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?XQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`cidr`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?VQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`base64`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?HQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`base64url`,code:Q.invalid_string,message:r.message}),t.dirty()):aQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Q.invalid_string,...CQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...CQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...CQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...CQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...CQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...CQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...CQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...CQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...CQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...CQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...CQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...CQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...CQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...CQ.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,...CQ.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,...CQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...CQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...CQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...CQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...CQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...CQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...CQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...CQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...CQ.errToObj(t)})}nonempty(e){return this.min(1,CQ.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}};ZQ.create=e=>new ZQ({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...EQ(e)});function QQ(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 $Q=class e extends DQ{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)!==sQ.number){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.number,received:t.parsedType}),gQ}let t,n=new hQ;for(let r of this._def.checks)r.kind===`int`?aQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),mQ(t,{code:Q.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),mQ(t,{code:Q.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),mQ(t,{code:Q.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?QQ(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),mQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),mQ(t,{code:Q.not_finite,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,CQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,CQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,CQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,CQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:CQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:CQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:CQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:CQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:CQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:CQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:CQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:CQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:CQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:CQ.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`&&aQ.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)}};$Q.create=e=>new $Q({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...EQ(e)});var e$=class e extends DQ{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)!==sQ.bigint)return this._getInvalidInput(e);let t,n=new hQ;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),mQ(t,{code:Q.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),mQ(t,{code:Q.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),mQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.bigint,received:t.parsedType}),gQ}gte(e,t){return this.setLimit(`min`,e,!0,CQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,CQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,CQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,CQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:CQ.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:CQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:CQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:CQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:CQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:CQ.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}};e$.create=e=>new e$({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...EQ(e)});var t$=class extends DQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==sQ.boolean){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.boolean,received:t.parsedType}),gQ}return vQ(e.data)}};t$.create=e=>new t$({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...EQ(e)});var n$=class e extends DQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==sQ.date){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.date,received:t.parsedType}),gQ}if(Number.isNaN(e.data.getTime()))return mQ(this._getOrReturnCtx(e),{code:Q.invalid_date}),gQ;let t=new hQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.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),mQ(n,{code:Q.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):aQ.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:CQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:CQ.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)}};n$.create=e=>new n$({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...EQ(e)});var r$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.symbol){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.symbol,received:t.parsedType}),gQ}return vQ(e.data)}};r$.create=e=>new r$({typeName:$.ZodSymbol,...EQ(e)});var i$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.undefined,received:t.parsedType}),gQ}return vQ(e.data)}};i$.create=e=>new i$({typeName:$.ZodUndefined,...EQ(e)});var a$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.null){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.null,received:t.parsedType}),gQ}return vQ(e.data)}};a$.create=e=>new a$({typeName:$.ZodNull,...EQ(e)});var o$=class extends DQ{constructor(){super(...arguments),this._any=!0}_parse(e){return vQ(e.data)}};o$.create=e=>new o$({typeName:$.ZodAny,...EQ(e)});var s$=class extends DQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return vQ(e.data)}};s$.create=e=>new s$({typeName:$.ZodUnknown,...EQ(e)});var c$=class extends DQ{_parse(e){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.never,received:t.parsedType}),gQ}};c$.create=e=>new c$({typeName:$.ZodNever,...EQ(e)});var l$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.void,received:t.parsedType}),gQ}return vQ(e.data)}};l$.create=e=>new l$({typeName:$.ZodVoid,...EQ(e)});var u$=class e extends DQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==sQ.array)return mQ(t,{code:Q.invalid_type,expected:sQ.array,received:t.parsedType}),gQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(mQ(t,{code:e?Q.too_big:Q.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&&(mQ(t,{code:Q.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&&(mQ(t,{code:Q.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 wQ(t,e,t.path,n)))).then(e=>hQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new wQ(t,e,t.path,n)));return hQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:CQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:CQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:CQ.toString(n)}})}nonempty(e){return this.min(1,e)}};u$.create=(e,t)=>new u$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...EQ(t)});function d$(e){if(e instanceof f$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=A$.create(d$(r))}return new f$({...e._def,shape:()=>t})}else if(e instanceof u$)return new u$({...e._def,type:d$(e.element)});else if(e instanceof A$)return A$.create(d$(e.unwrap()));else if(e instanceof j$)return j$.create(d$(e.unwrap()));else if(e instanceof v$)return v$.create(e.items.map(e=>d$(e)));else return e}var f$=class e extends DQ{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=aQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==sQ.object){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.object,received:t.parsedType}),gQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof c$&&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 wQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof c$){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&&(mQ(n,{code:Q.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 wQ(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=>hQ.mergeObjectSync(t,e)):hQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return CQ.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:CQ.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:$.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 aQ.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 aQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return d$(this)}partial(t){let n={};for(let e of aQ.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 aQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof A$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return T$(aQ.objectKeys(this.shape))}};f$.create=(e,t)=>new f$({shape:()=>e,unknownKeys:`strip`,catchall:c$.create(),typeName:$.ZodObject,...EQ(t)}),f$.strictCreate=(e,t)=>new f$({shape:()=>e,unknownKeys:`strict`,catchall:c$.create(),typeName:$.ZodObject,...EQ(t)}),f$.lazycreate=(e,t)=>new f$({shape:e,unknownKeys:`strip`,catchall:c$.create(),typeName:$.ZodObject,...EQ(t)});var p$=class extends DQ{_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 lQ(e.ctx.common.issues));return mQ(t,{code:Q.invalid_union,unionErrors:n}),gQ}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 lQ(e));return mQ(t,{code:Q.invalid_union,unionErrors:i}),gQ}}get options(){return this._def.options}};p$.create=(e,t)=>new p$({options:e,typeName:$.ZodUnion,...EQ(t)});const m$=e=>e instanceof C$?m$(e.schema):e instanceof k$?m$(e.innerType()):e instanceof w$?[e.value]:e instanceof E$?e.options:e instanceof D$?aQ.objectValues(e.enum):e instanceof M$?m$(e._def.innerType):e instanceof i$?[void 0]:e instanceof a$?[null]:e instanceof A$?[void 0,...m$(e.unwrap())]:e instanceof j$?[null,...m$(e.unwrap())]:e instanceof F$||e instanceof L$?m$(e.unwrap()):e instanceof N$?m$(e._def.innerType):[];var h$=class e extends DQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.object)return mQ(t,{code:Q.invalid_type,expected:sQ.object,received:t.parsedType}),gQ;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}):(mQ(t,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),gQ)}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=m$(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:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...EQ(r)})}};function g$(e,t){let n=cQ(e),r=cQ(t);if(e===t)return{valid:!0,data:e};if(n===sQ.object&&r===sQ.object){let n=aQ.objectKeys(t),r=aQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=g$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===sQ.array&&r===sQ.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=g$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===sQ.date&&r===sQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var _$=class extends DQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(yQ(e)||yQ(r))return gQ;let i=g$(e.value,r.value);return i.valid?((bQ(e)||bQ(r))&&t.dirty(),{status:t.value,value:i.data}):(mQ(n,{code:Q.invalid_intersection_types}),gQ)};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}))}};_$.create=(e,t,n)=>new _$({left:e,right:t,typeName:$.ZodIntersection,...EQ(n)});var v$=class e extends DQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.array)return mQ(n,{code:Q.invalid_type,expected:sQ.array,received:n.parsedType}),gQ;if(n.data.length<this._def.items.length)return mQ(n,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),gQ;!this._def.rest&&n.data.length>this._def.items.length&&(mQ(n,{code:Q.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 wQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>hQ.mergeArray(t,e)):hQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};v$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new v$({items:e,typeName:$.ZodTuple,rest:null,...EQ(t)})};var y$=class e extends DQ{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!==sQ.object)return mQ(n,{code:Q.invalid_type,expected:sQ.object,received:n.parsedType}),gQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new wQ(n,e,n.path,e)),value:a._parse(new wQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?hQ.mergeObjectAsync(t,r):hQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof DQ?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...EQ(r)}):new e({keyType:ZQ.create(),valueType:t,typeName:$.ZodRecord,...EQ(n)})}},b$=class extends DQ{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!==sQ.map)return mQ(n,{code:Q.invalid_type,expected:sQ.map,received:n.parsedType}),gQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new wQ(n,e,n.path,[a,`key`])),value:i._parse(new wQ(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 gQ;(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 gQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};b$.create=(e,t,n)=>new b$({valueType:t,keyType:e,typeName:$.ZodMap,...EQ(n)});var x$=class e extends DQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.set)return mQ(n,{code:Q.invalid_type,expected:sQ.set,received:n.parsedType}),gQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(mQ(n,{code:Q.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&&(mQ(n,{code:Q.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 gQ;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 wQ(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:CQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:CQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};x$.create=(e,t)=>new x$({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...EQ(t)});var S$=class e extends DQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.function)return mQ(t,{code:Q.invalid_type,expected:sQ.function,received:t.parsedType}),gQ;function n(e,n){return pQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fQ(),uQ].filter(e=>!!e),issueData:{code:Q.invalid_arguments,argumentsError:n}})}function r(e,n){return pQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fQ(),uQ].filter(e=>!!e),issueData:{code:Q.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof O$){let e=this;return vQ(async function(...t){let o=new lQ([]),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 vQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new lQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new lQ([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:v$.create(t).rest(s$.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||v$.create([]).rest(s$.create()),returns:n||s$.create(),typeName:$.ZodFunction,...EQ(r)})}},C$=class extends DQ{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})}};C$.create=(e,t)=>new C$({getter:e,typeName:$.ZodLazy,...EQ(t)});var w$=class extends DQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return mQ(t,{received:t.data,code:Q.invalid_literal,expected:this._def.value}),gQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};w$.create=(e,t)=>new w$({value:e,typeName:$.ZodLiteral,...EQ(t)});function T$(e,t){return new E$({values:e,typeName:$.ZodEnum,...EQ(t)})}var E$=class e extends DQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return mQ(t,{expected:aQ.joinValues(n),received:t.parsedType,code:Q.invalid_type}),gQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return mQ(t,{received:t.data,code:Q.invalid_enum_value,options:n}),gQ}return vQ(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})}};E$.create=T$;var D$=class extends DQ{_parse(e){let t=aQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==sQ.string&&n.parsedType!==sQ.number){let e=aQ.objectValues(t);return mQ(n,{expected:aQ.joinValues(e),received:n.parsedType,code:Q.invalid_type}),gQ}if(this._cache||=new Set(aQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=aQ.objectValues(t);return mQ(n,{received:n.data,code:Q.invalid_enum_value,options:e}),gQ}return vQ(e.data)}get enum(){return this._def.values}};D$.create=(e,t)=>new D$({values:e,typeName:$.ZodNativeEnum,...EQ(t)});var O$=class extends DQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==sQ.promise&&t.common.async===!1?(mQ(t,{code:Q.invalid_type,expected:sQ.promise,received:t.parsedType}),gQ):vQ((t.parsedType===sQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};O$.create=(e,t)=>new O$({type:e,typeName:$.ZodPromise,...EQ(t)});var k$=class extends DQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.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=>{mQ(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 gQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?gQ:r.status===`dirty`||t.value===`dirty`?_Q(r.value):r});{if(t.value===`aborted`)return gQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?gQ:r.status===`dirty`||t.value===`dirty`?_Q(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`?gQ:(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`?gQ:(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(!xQ(e))return gQ;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=>xQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):gQ);aQ.assertNever(r)}};k$.create=(e,t,n)=>new k$({schema:e,typeName:$.ZodEffects,effect:t,...EQ(n)}),k$.createWithPreprocess=(e,t,n)=>new k$({schema:t,effect:{type:`preprocess`,transform:e},typeName:$.ZodEffects,...EQ(n)});var A$=class extends DQ{_parse(e){return this._getType(e)===sQ.undefined?vQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};A$.create=(e,t)=>new A$({innerType:e,typeName:$.ZodOptional,...EQ(t)});var j$=class extends DQ{_parse(e){return this._getType(e)===sQ.null?vQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j$.create=(e,t)=>new j$({innerType:e,typeName:$.ZodNullable,...EQ(t)});var M$=class extends DQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===sQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};M$.create=(e,t)=>new M$({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...EQ(t)});var N$=class extends DQ{_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 SQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};N$.create=(e,t)=>new N$({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...EQ(t)});var P$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.nan){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.nan,received:t.parsedType}),gQ}return{status:`valid`,value:e.data}}};P$.create=e=>new P$({typeName:$.ZodNaN,...EQ(e)});var F$=class extends DQ{_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}},I$=class e extends DQ{_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`?gQ:e.status===`dirty`?(t.dirty(),_Q(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`?gQ: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:$.ZodPipeline})}},L$=class extends DQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(xQ(e)&&(e.value=Object.freeze(e.value)),e);return SQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:$.ZodReadonly,...EQ(t)}),f$.lazycreate;var $;(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`})($||={}),ZQ.create,$Q.create,P$.create,e$.create,t$.create,n$.create,r$.create,i$.create,a$.create,o$.create,s$.create,c$.create,l$.create,u$.create;const R$=f$.create;f$.strictCreate,p$.create,h$.create,_$.create,v$.create,y$.create,b$.create,x$.create,S$.create,C$.create,w$.create,E$.create,D$.create,O$.create,k$.create,A$.create,j$.create,k$.createWithPreprocess,I$.create;const z$=m(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);v.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>he(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>me(e,t,n),e.parseAsync=async(t,n)=>r(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>h(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)=>y(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),B$=m(`ZodMiniObject`,(e,t)=>{o.init(e,t),z$.init(e,t),l(e,`shape`,()=>t.shape)});function V$(e,t){return new B$({type:`object`,shape:e??{},...d(t)})}function H$(e){return!!e._zod}function U$(e){let t=Object.values(e);if(t.length===0)return V$({});let n=t.every(H$),r=t.every(e=>!H$(e));if(n)return V$(e);if(r)return R$(e);throw Error(`Mixed Zod versions detected in object shape.`)}function W$(e,t){return H$(e)?me(e,t):e.safeParse(t)}async function G$(e,t){return H$(e)?await h(e,t):await e.safeParseAsync(t)}function K$(e){if(!e)return;let t;if(t=H$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function q$(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 U$(e)}}if(H$(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 J$(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 Y$(e){return e.description}function X$(e){if(H$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Z$(e){if(H$(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 Q$=`2025-11-25`,$$=[Q$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],e1=`io.modelcontextprotocol/related-task`,t1=be(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),n1=I([F(),N().int()]),r1=F();ue({ttl:N().optional(),pollInterval:N().optional()});const eue=M({ttl:N().optional()}),tue=M({taskId:F()}),i1=ue({progressToken:n1.optional(),[e1]:tue.optional()}),a1=M({_meta:i1.optional()}),o1=a1.extend({task:eue.optional()}),nue=e=>o1.safeParse(e).success,s1=M({method:F(),params:a1.loose().optional()}),c1=M({_meta:i1.optional()}),l1=M({method:F(),params:c1.loose().optional()}),u1=ue({_meta:i1.optional()}),d1=I([F(),N().int()]),f1=M({jsonrpc:k(`2.0`),id:d1,...s1.shape}).strict(),p1=e=>f1.safeParse(e).success,m1=M({jsonrpc:k(`2.0`),...l1.shape}).strict(),rue=e=>m1.safeParse(e).success,h1=M({jsonrpc:k(`2.0`),id:d1,result:u1}).strict(),g1=e=>h1.safeParse(e).success;var _1;(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`})(_1||={});const v1=M({jsonrpc:k(`2.0`),id:d1.optional(),error:M({code:N().int(),message:F(),data:O().optional()})}).strict(),y1=e=>v1.safeParse(e).success,b1=I([f1,m1,h1,v1]);I([h1,v1]);const x1=u1.strict(),iue=c1.extend({requestId:d1.optional(),reason:F().optional()}),S1=l1.extend({method:k(`notifications/cancelled`),params:iue}),C1=M({icons:j(M({src:F(),mimeType:F().optional(),sizes:j(F()).optional(),theme:we([`light`,`dark`]).optional()})).optional()}),w1=M({name:F(),title:F().optional()}),T1=w1.extend({...w1.shape,...C1.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),aue=fe(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,_e(M({form:_e(M({applyDefaults:D().optional()}),E(F(),O())).optional(),url:t1.optional()}),E(F(),O()).optional())),oue=ue({list:t1.optional(),cancel:t1.optional(),requests:ue({sampling:ue({createMessage:t1.optional()}).optional(),elicitation:ue({create:t1.optional()}).optional()}).optional()}),sue=ue({list:t1.optional(),cancel:t1.optional(),requests:ue({tools:ue({call:t1.optional()}).optional()}).optional()}),cue=M({experimental:E(F(),t1).optional(),sampling:M({context:t1.optional(),tools:t1.optional()}).optional(),elicitation:aue.optional(),roots:M({listChanged:D().optional()}).optional(),tasks:oue.optional(),extensions:E(F(),t1).optional()}),lue=a1.extend({protocolVersion:F(),capabilities:cue,clientInfo:T1}),E1=s1.extend({method:k(`initialize`),params:lue}),D1=e=>E1.safeParse(e).success,uue=M({experimental:E(F(),t1).optional(),logging:t1.optional(),completions:t1.optional(),prompts:M({listChanged:D().optional()}).optional(),resources:M({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:M({listChanged:D().optional()}).optional(),tasks:sue.optional(),extensions:E(F(),t1).optional()}),due=u1.extend({protocolVersion:F(),capabilities:uue,serverInfo:T1,instructions:F().optional()}),O1=l1.extend({method:k(`notifications/initialized`),params:c1.optional()}),fue=e=>O1.safeParse(e).success,k1=s1.extend({method:k(`ping`),params:a1.optional()}),pue=M({progress:N(),total:A(N()),message:A(F())}),mue=M({...c1.shape,...pue.shape,progressToken:n1}),A1=l1.extend({method:k(`notifications/progress`),params:mue}),hue=a1.extend({cursor:r1.optional()}),j1=s1.extend({params:hue.optional()}),M1=u1.extend({nextCursor:r1.optional()}),gue=we([`working`,`input_required`,`completed`,`failed`,`cancelled`]),N1=M({taskId:F(),status:gue,ttl:I([N(),ye()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:A(N()),statusMessage:A(F())}),P1=u1.extend({task:N1}),_ue=c1.merge(N1),F1=l1.extend({method:k(`notifications/tasks/status`),params:_ue}),I1=s1.extend({method:k(`tasks/get`),params:a1.extend({taskId:F()})}),L1=u1.merge(N1),R1=s1.extend({method:k(`tasks/result`),params:a1.extend({taskId:F()})});u1.loose();const z1=j1.extend({method:k(`tasks/list`)}),B1=M1.extend({tasks:j(N1)}),V1=s1.extend({method:k(`tasks/cancel`),params:a1.extend({taskId:F()})}),vue=u1.merge(N1),H1=M({uri:F(),mimeType:A(F()),_meta:E(F(),O()).optional()}),U1=H1.extend({text:F()}),W1=F().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),G1=H1.extend({blob:W1}),K1=we([`user`,`assistant`]),q1=M({audience:j(K1).optional(),priority:N().min(0).max(1).optional(),lastModified:i({offset:!0}).optional()}),J1=M({...w1.shape,...C1.shape,uri:F(),description:A(F()),mimeType:A(F()),size:A(N()),annotations:q1.optional(),_meta:A(ue({}))}),yue=M({...w1.shape,...C1.shape,uriTemplate:F(),description:A(F()),mimeType:A(F()),annotations:q1.optional(),_meta:A(ue({}))}),Y1=j1.extend({method:k(`resources/list`)}),bue=M1.extend({resources:j(J1)}),X1=j1.extend({method:k(`resources/templates/list`)}),xue=M1.extend({resourceTemplates:j(yue)}),Z1=a1.extend({uri:F()}),Sue=Z1,Q1=s1.extend({method:k(`resources/read`),params:Sue}),Cue=u1.extend({contents:j(I([U1,G1]))}),wue=l1.extend({method:k(`notifications/resources/list_changed`),params:c1.optional()}),Tue=Z1,Eue=s1.extend({method:k(`resources/subscribe`),params:Tue}),Due=Z1,Oue=s1.extend({method:k(`resources/unsubscribe`),params:Due}),kue=c1.extend({uri:F()}),Aue=l1.extend({method:k(`notifications/resources/updated`),params:kue}),jue=M({name:F(),description:A(F()),required:A(D())}),Mue=M({...w1.shape,...C1.shape,description:A(F()),arguments:A(j(jue)),_meta:A(ue({}))}),$1=j1.extend({method:k(`prompts/list`)}),Nue=M1.extend({prompts:j(Mue)}),Pue=a1.extend({name:F(),arguments:E(F(),F()).optional()}),e0=s1.extend({method:k(`prompts/get`),params:Pue}),t0=M({type:k(`text`),text:F(),annotations:q1.optional(),_meta:E(F(),O()).optional()}),n0=M({type:k(`image`),data:W1,mimeType:F(),annotations:q1.optional(),_meta:E(F(),O()).optional()}),r0=M({type:k(`audio`),data:W1,mimeType:F(),annotations:q1.optional(),_meta:E(F(),O()).optional()}),Fue=M({type:k(`tool_use`),name:F(),id:F(),input:E(F(),O()),_meta:E(F(),O()).optional()}),Iue=M({type:k(`resource`),resource:I([U1,G1]),annotations:q1.optional(),_meta:E(F(),O()).optional()}),i0=I([t0,n0,r0,J1.extend({type:k(`resource_link`)}),Iue]),Lue=M({role:K1,content:i0}),Rue=u1.extend({description:F().optional(),messages:j(Lue)}),zue=l1.extend({method:k(`notifications/prompts/list_changed`),params:c1.optional()}),Bue=M({title:F().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Vue=M({taskSupport:we([`required`,`optional`,`forbidden`]).optional()}),a0=M({...w1.shape,...C1.shape,description:F().optional(),inputSchema:M({type:k(`object`),properties:E(F(),t1).optional(),required:j(F()).optional()}).catchall(O()),outputSchema:M({type:k(`object`),properties:E(F(),t1).optional(),required:j(F()).optional()}).catchall(O()).optional(),annotations:Bue.optional(),execution:Vue.optional(),_meta:E(F(),O()).optional()}),o0=j1.extend({method:k(`tools/list`)}),Hue=M1.extend({tools:j(a0)}),s0=u1.extend({content:j(i0).default([]),structuredContent:E(F(),O()).optional(),isError:D().optional()});s0.or(u1.extend({toolResult:O()}));const Uue=o1.extend({name:F(),arguments:E(F(),O()).optional()}),c0=s1.extend({method:k(`tools/call`),params:Uue}),Wue=l1.extend({method:k(`notifications/tools/list_changed`),params:c1.optional()});M({autoRefresh:D().default(!0),debounceMs:N().int().nonnegative().default(300)});const l0=we([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Gue=a1.extend({level:l0}),u0=s1.extend({method:k(`logging/setLevel`),params:Gue}),Kue=c1.extend({level:l0,logger:F().optional(),data:O()}),que=l1.extend({method:k(`notifications/message`),params:Kue}),Jue=M({hints:j(M({name:F().optional()})).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),Yue=M({mode:we([`auto`,`required`,`none`]).optional()}),Xue=M({type:k(`tool_result`),toolUseId:F().describe(`The unique identifier for the corresponding tool call.`),content:j(i0).default([]),structuredContent:M({}).loose().optional(),isError:D().optional(),_meta:E(F(),O()).optional()}),Zue=Se(`type`,[t0,n0,r0]),d0=Se(`type`,[t0,n0,r0,Fue,Xue]),Que=M({role:K1,content:I([d0,j(d0)]),_meta:E(F(),O()).optional()}),$ue=o1.extend({messages:j(Que),modelPreferences:Jue.optional(),systemPrompt:F().optional(),includeContext:we([`none`,`thisServer`,`allServers`]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:j(F()).optional(),metadata:t1.optional(),tools:j(a0).optional(),toolChoice:Yue.optional()}),ede=s1.extend({method:k(`sampling/createMessage`),params:$ue}),f0=u1.extend({model:F(),stopReason:A(we([`endTurn`,`stopSequence`,`maxTokens`]).or(F())),role:K1,content:Zue}),p0=u1.extend({model:F(),stopReason:A(we([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(F())),role:K1,content:I([d0,j(d0)])}),tde=M({type:k(`boolean`),title:F().optional(),description:F().optional(),default:D().optional()}),nde=M({type:k(`string`),title:F().optional(),description:F().optional(),minLength:N().optional(),maxLength:N().optional(),format:we([`email`,`uri`,`date`,`date-time`]).optional(),default:F().optional()}),rde=M({type:we([`number`,`integer`]),title:F().optional(),description:F().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),ide=M({type:k(`string`),title:F().optional(),description:F().optional(),enum:j(F()),default:F().optional()}),ade=M({type:k(`string`),title:F().optional(),description:F().optional(),oneOf:j(M({const:F(),title:F()})),default:F().optional()}),ode=I([I([M({type:k(`string`),title:F().optional(),description:F().optional(),enum:j(F()),enumNames:j(F()).optional(),default:F().optional()}),I([ide,ade]),I([M({type:k(`array`),title:F().optional(),description:F().optional(),minItems:N().optional(),maxItems:N().optional(),items:M({type:k(`string`),enum:j(F())}),default:j(F()).optional()}),M({type:k(`array`),title:F().optional(),description:F().optional(),minItems:N().optional(),maxItems:N().optional(),items:M({anyOf:j(M({const:F(),title:F()}))}),default:j(F()).optional()})])]),tde,nde,rde]),sde=I([o1.extend({mode:k(`form`).optional(),message:F(),requestedSchema:M({type:k(`object`),properties:E(F(),ode),required:j(F()).optional()})}),o1.extend({mode:k(`url`),message:F(),elicitationId:F(),url:F().url()})]),cde=s1.extend({method:k(`elicitation/create`),params:sde}),lde=c1.extend({elicitationId:F()}),ude=l1.extend({method:k(`notifications/elicitation/complete`),params:lde}),m0=u1.extend({action:we([`accept`,`decline`,`cancel`]),content:fe(e=>e===null?void 0:e,E(F(),I([F(),N(),D(),j(F())])).optional())}),dde=M({type:k(`ref/resource`),uri:F()}),fde=M({type:k(`ref/prompt`),name:F()}),pde=a1.extend({ref:I([fde,dde]),argument:M({name:F(),value:F()}),context:M({arguments:E(F(),F()).optional()}).optional()}),h0=s1.extend({method:k(`completion/complete`),params:pde});function mde(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function hde(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const gde=u1.extend({completion:ue({values:j(F()).max(100),total:A(N().int()),hasMore:A(D())})}),_de=M({uri:F().startsWith(`file://`),name:F().optional(),_meta:E(F(),O()).optional()}),vde=s1.extend({method:k(`roots/list`),params:a1.optional()}),g0=u1.extend({roots:j(_de)}),yde=l1.extend({method:k(`notifications/roots/list_changed`),params:c1.optional()});I([k1,E1,h0,u0,e0,$1,Y1,X1,Q1,Eue,Oue,c0,o0,I1,R1,z1,V1]),I([S1,A1,O1,yde,F1]),I([x1,f0,p0,m0,g0,L1,B1,P1]),I([k1,ede,cde,vde,I1,R1,z1,V1]),I([S1,A1,que,Aue,wue,Wue,zue,F1,ude]),I([x1,due,gde,Rue,Nue,bue,xue,Cue,s0,Hue,L1,B1,P1]);var _0=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===_1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new bde(e.elicitations,n)}return new e(t,n,r)}},bde=class extends _0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(_1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function v0(e){return e===`completed`||e===`failed`||e===`cancelled`}const xde=Symbol(`Let zodToJsonSchema decide on which parser to use`),y0={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`},Sde=e=>typeof e==`string`?{...y0,name:e}:{...y0,...e},Cde=e=>{let t=Sde(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 b0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function x0(e,t,n,r,i){e[t]=n,b0(e,t,r,i)}const S0=(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 C0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?S0(t,e.currentPath):t.join(`/`)}}function wde(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==$.ZodAny&&(n.items=I0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&x0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&x0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(x0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),x0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Tde(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?x0(n,`minimum`,r.value,r.message,t):x0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),x0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?x0(n,`maximum`,r.value,r.message,t):x0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),x0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:x0(n,`multipleOf`,r.value,r.message,t);break}return n}function Ede(){return{type:`boolean`}}function w0(e,t){return I0(e.type._def,t)}const Dde=(e,t)=>I0(e.innerType._def,t);function T0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>T0(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 Ode(e,t)}}const Ode=(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`:x0(n,`minimum`,r.value,r.message,t);break;case`max`:x0(n,`maximum`,r.value,r.message,t);break}return n};function kde(e,t){return{...I0(e.innerType._def,t),default:e.defaultValue()}}function Ade(e,t){return t.effectStrategy===`input`?I0(e.schema._def,t):C0(t)}function jde(e){return{type:`string`,enum:Array.from(e.values)}}const Mde=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Nde(e,t){let n=[I0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),I0(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(Mde(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 Pde(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 E0;const D0={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:()=>(E0===void 0&&(E0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),E0),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 O0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:x0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:x0(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`:A0(n,`email`,r.message,t);break;case`format:idn-email`:A0(n,`idn-email`,r.message,t);break;case`pattern:zod`:j0(n,D0.email,r.message,t);break}break;case`url`:A0(n,`uri`,r.message,t);break;case`uuid`:A0(n,`uuid`,r.message,t);break;case`regex`:j0(n,r.regex,r.message,t);break;case`cuid`:j0(n,D0.cuid,r.message,t);break;case`cuid2`:j0(n,D0.cuid2,r.message,t);break;case`startsWith`:j0(n,RegExp(`^${k0(r.value,t)}`),r.message,t);break;case`endsWith`:j0(n,RegExp(`${k0(r.value,t)}$`),r.message,t);break;case`datetime`:A0(n,`date-time`,r.message,t);break;case`date`:A0(n,`date`,r.message,t);break;case`time`:A0(n,`time`,r.message,t);break;case`duration`:A0(n,`duration`,r.message,t);break;case`length`:x0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),x0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:j0(n,RegExp(k0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&A0(n,`ipv4`,r.message,t),r.version!==`v4`&&A0(n,`ipv6`,r.message,t);break;case`base64url`:j0(n,D0.base64url,r.message,t);break;case`jwt`:j0(n,D0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&j0(n,D0.ipv4Cidr,r.message,t),r.version!==`v4`&&j0(n,D0.ipv6Cidr,r.message,t);break;case`emoji`:j0(n,D0.emoji(),r.message,t);break;case`ulid`:j0(n,D0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:A0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:x0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:j0(n,D0.base64,r.message,t);break}break;case`nanoid`:j0(n,D0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function k0(e,t){return t.patternStrategy===`escape`?Ide(e):e}const Fde=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Ide(e){let t=``;for(let n=0;n<e.length;n++)Fde.has(e[n])||(t+=`\\`),t+=e[n];return t}function A0(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}}})):x0(e,`format`,t,n,r)}function j0(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:M0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):x0(e,`pattern`,M0(t,r),n,r)}function M0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
1215
|
+
`).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await lr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Fc=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ic(e){try{let t=cc(e.scope);if(!t)return;let n=mB(t);if(n.length===0)return;let r=xB(V(e.skillsRoot,e.name),e.name,t,n,`copy`,hB(e.scope));if(r.length===0)return;await sI(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){Z.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Lc(e,t){if(t.ok){Y(e,200,gr,t.body,{handler:`skill-import`});return}q(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}async function Rc(e){let{acquiredDir:t,scope:n,sourceLabel:r,ref:i,publisher:a,upstreamSkill:o,actor:s}=e;if(!A)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`No project root resolved.`,detail:`NO_PROJECT_ROOT`};let c=ID(t);if(c)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:c};let u=LD(t);if(!u)return{ok:!1,status:422,urn:`urn:ok:error:invalid-request`,title:`Source has no readable skill.`};let d=tX(u);if(d)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Skill bundle exceeds import limits.`,detail:d};let f=z(n===`project`?A:Bs,...kD),p=Mc(f),m=n===`project`?l:Bs,h=$B(m,n),g=V(m,h),_=qoe(p,u.contentHash);if(_&&Hs(n,_)!==null)return{ok:!0,body:{name:_,path:`${_}/SKILL.md`,created:!1,alreadyImported:!0,provenance:{source:r,ref:i,contentHash:u.contentHash,publisher:a},warnings:[]}};let v=kX(u.name),y=e=>Hs(n,e)!==null||H(V(g,e,`SKILL.md`)),b=y(v),x=v;if(b){x=`${v}-imported`;let e=2;for(;y(x);)x=`${v}-imported-${e}`,e+=1}let S=js(u.skillMd).body,C=MP({skillsRoot:g,name:x,body:S,frontmatter:{name:x,description:u.description}});if(!C.ok)return{ok:!1,status:400,urn:`urn:ok:error:invalid-request`,title:`Failed to write imported skill.`,detail:C.error.code,cause:Error(C.error.message)};let w=[...C.warnings];for(let e of u.files){let t=FP({skillsRoot:g,name:x,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:eX});if(!t.ok){let n=LP({skillsRoot:g,name:x});return{ok:!1,status:n.ok?400:500,urn:n.ok?`urn:ok:error:invalid-request`:`urn:ok:error:internal-server-error`,title:`Failed to write the complete imported skill bundle.`,detail:`${e.relPath}: ${t.error.code}`,cause:Error(n.ok?t.error.message:`${t.error.message}; rollback: ${n.error.message}`)}}}n===`project`&&(ar(s,`${h}/${x}/SKILL`,`skill-import: ${r} -> ${h}/${x}/SKILL.md`),await lr(`skill-import`));let T=Nc(g,x),ee=uO(r),te=n===`project`?await Pc(Fc(s),`${h}/${x}`):void 0;if(await eY(f,e=>MD(e,x,{source:r,...ee?{pluginProvider:ee.provider}:{},ref:i,contentHash:u.contentHash,files:u.files.map(e=>e.relPath),...T===void 0?{}:{localHash:T},...te===void 0?{}:{baselineRef:te},publisher:a,importedAt:new Date().toISOString(),...o===void 0?{}:{skill:o}})),e.skipProjection!==!0)try{let e=mB(m);if(e.length>0){let t=V(g,x),r=hB(n),i=e.filter(e=>{let n=gB(m,e,x,r);return n!==null&&n!==t&&H(n)}),a=i.filter(e=>{let t=gB(m,e,x,r);try{return t!==null&&Hl(t).isSymbolicLink()}catch{return!1}});CB({canonicalAbs:t,canonicalHash:LD(t)?.contentHash??``,canonicalRootRel:h,name:x,cwd:m,targets:e,mode:Zs(n,x,{hosts:[`<source>`,...i],linkedHosts:a}),roots:hB(n)})}}catch(e){L(`skill-import`).warn({err:e,skill:x},`post-import editor fan-out failed (import kept)`)}return se?.(`files`),{ok:!0,body:{name:x,path:`${h}/${x}/SKILL.md`,created:C.created,alreadyImported:!1,...b?{collisionRenamedFrom:u.name}:{},provenance:{source:r,ref:i,contentHash:u.contentHash,publisher:a},warnings:w}}}let zc=J(di,async(e,t,n)=>{let r=()=>{};try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await HD(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??ED(d);if(!p){q(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if($Y(t,p,`skill-import`))return;let m=await OD(p);r=m.cleanup,s=m.ref;let h=RD(m.dir);if(h.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>FD(e.dir)?.name===f);if(!e){q(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){q(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??jc(d)}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Rc({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});n.marketplace===!0&&d.ok&&Yz({source:u,skills:[d.body.name]},kz()),Lc(t,d)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Bc=J(qe,async(e,t,n)=>{let r=()=>{};try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l;try{let e=await HD(i,n.skills[0]),u=e?.source??i,d=e?.spec??ED(u);if(!d){q(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if($Y(t,d,`skills-import-bulk`))return;if(l=e?.publisher??jc(u),d.kind===`well-known`)a=d,o=await wD(d.origin);else{let e=await OD(d);r=e.cleanup,c=e.ref,s=RD(e.dir)}}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let u=[];for(let t of new Set(n.skills)){let r,d,f=()=>{};if(a!==null)try{let e=await OD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,d=t}catch(e){u.push({requested:t,status:e instanceof vD?`not-found`:`failed`,warnings:[],...e instanceof vD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>LD(e.dir)?.name===t);if(!e){u.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,d=e.name}try{let a=await Rc({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:d,actor:e,skipProjection:n.install===!1});if(!a.ok){L(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}u.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){L(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),u.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}Y(t,200,wee,{results:u,imported:u.filter(e=>e.status===`imported`).length,alreadyImported:u.filter(e=>e.status===`already-imported`).length,failed:u.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),Vc=8*1024*1024,Hc=32*1024*1024;function Uc(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=V(e,n);return r!==e&&!r.startsWith(e+Al)?null:r}function Wc(e){return new Promise((t,n)=>{let r;try{r=(0,VO.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:Vc}})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>Hc){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function Gc(e,t){return new Promise((n,r)=>{(0,rj.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=Uc(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){Jo(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>Vc){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>Hc){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{Jo(R(n),{recursive:!0}),rs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function Kc(e,t){let n=Wl(z(cu(),`ok-skill-upload-`)),r=()=>{try{Qo(n,{recursive:!0,force:!0})}catch{}};try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){q(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=zs(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=fM({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},me);if(o.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Wc(e)}catch(e){q(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){q(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Gc(c.data,n)}catch(e){q(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Uc(n,e.relPath);if(!r){q(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}Jo(R(r),{recursive:!0}),rs(r,e.data)}let u=RD(n);if(u.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){q(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];Lc(t,await Rc({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let qc=J(Qee,async(e,t,n)=>{try{let e=Vs(n.scope);if(!Rs(n.name,t,`skill-install`))return;if(n.scope===`project`&&!A){q(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=cc(n.scope),i=V(e,n.name),a=n.scope===`project`?l:Bs,o=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name),s=o?V(a,o.dir):i;if(!H(s)){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Jt(n.scope===`project`?`${B(a,s).split(Al).join(`/`)}/SKILL`:vr(n.scope,n.name));let c=fB(s,n.name);if(!c.ok){q(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){let e=[];if(!o){q(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let r=n.scope===`project`?Mt:Gn,i=n.fork.editor===`agents`?`.agents/skills`:r[n.fork.editor]??null;if(i===null){q(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:n.fork.editor});return}let s=V(a,i,n.name),c=V(a,o.dir),u=LD(s);if(u===null||s===c){q(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return}if(u.contentHash===o.contentHash){q(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return}let d=new Date().toISOString().replace(/[:.]/g,`-`),f=(e,t)=>{try{let r=V(Bs,`.ok`,`edit-backups`,`forks`,`${n.name}-${t}-${d}`);Jo(V(r,`..`),{recursive:!0}),Zo(e,r,{recursive:!0})}catch(e){Z.warn({name:n.name,err:e},`[skill-fork] stash failed`)}};if(n.fork.action===`align`)f(s,n.fork.editor),Qo(s,{recursive:!0,force:!0}),CB({canonicalAbs:c,canonicalHash:o.contentHash,canonicalRootRel:R(o.dir),name:n.name,cwd:a,targets:[n.fork.editor].filter(ua),roots:hB(n.scope)});else if(n.fork.action===`make-source`){let e=o.hosts.filter(ua);f(c,`source`),EB({canonicalAbs:c,canonicalHash:o.contentHash,name:n.name,cwd:a,targets:e,roots:hB(n.scope)}),Qo(c,{recursive:!0,force:!0});let t=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name);t&&CB({canonicalAbs:V(a,t.dir),canonicalHash:t.contentHash,canonicalRootRel:R(t.dir),name:n.name,cwd:a,targets:e,roots:hB(n.scope)})}else{let r=n.fork.toName;if(!Ie.test(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:r});return}if((n.scope===`project`?iV(l):aV(Bs)).some(e=>e.name===r)){q(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:r});return}let o=V(a,i,r);Vo(s,o);let c=V(o,`SKILL.md`);try{let{fenced:t,body:n}=ct(U(c,`utf-8`)),i=ht(t,{name:r});i.ok?rs(c,`${i.nextFenced}${n}`):(Z.warn({name:r,reason:i.error.kind},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md still declares the old name — edit the frontmatter to match.`))}catch(t){Z.warn({name:r,err:t},`[skill-fork] frontmatter rename failed`),e.push(`Renamed the folder to "${r}", but its SKILL.md could not be updated — edit the frontmatter to match.`)}}se?.(`files`),Y(t,200,jr,{name:n.name,hosts:o.hosts.filter(ua),scripts:!1,warnings:e,warningCodes:e.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){q(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=e=>e.replace(/\\/g,`/`).replace(/^~\//,``),r=o.hosts[0];if(r!==void 0&&(n.remove??[]).some(t=>e(t)===r)){q(t,400,`urn:ok:error:invalid-request`,`"${r}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`});return}let i=new Set(o.hosts.filter(e=>ua(e)));for(let t of n.add??[])ua(t)?i.add(t):p.push(e(t));let s=qB(a,n.scope),c=[],l=[];for(let e of n.add??[])if(ua(e)&&s[e]!==void 0&&!H(V(a,s[e],n.name,`SKILL.md`))){let t=e===`agents`?`.agents/skills`:(n.scope===`project`?Mt:Gn)[e]??null;t!==null&&l.push(t)}for(let t of n.remove??[])if(ua(t)){if(!i.has(t)&&s[t]!==void 0&&H(V(a,s[t],n.name,`SKILL.md`))){let e=t===`agents`?`.agents/skills`:(n.scope===`project`?Mt:Gn)[t]??null;e!==null&&c.push(e)}i.delete(t)}else m.push(e(t));for(let{subRoot:e,exclude:r}of[...l.map(e=>({subRoot:e,exclude:void 0})),...c.map(e=>({subRoot:e,exclude:[n.name]}))]){let n=IJ({base:a,folderRel:e,...r===void 0?{}:{exclude:r}});if(n.ok&&await RJ(a,e,{expect:`own`}),!n.ok){q(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e} following its pool (${n.reason}).`,{handler:`skill-install`,detail:n.reason});return}}f=[...i]}if(u&&!o){let e=u,i=wB({canonicalAbs:s,canonicalHash:LD(s)?.contentHash??``,name:n.name,cwd:a,newTarget:e,roots:hB(n.scope)});if(!i.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:i.reason});return}await cI(r,n.name),await LJ(a,n.name,e),se?.(`files`);let o=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name);Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:B(a,i.newAbs).split(Al).join(`/`)},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?A:Bs;if(!e){q(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.place.dir.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),i=V(e,r),a=`${r}/${n.name}`,l=MB(e,a),u=V(e),d=Ws(r);if(r===``||l===null||!l.startsWith(u+Al)||d){q(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}if(l===V(s)){Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:a},{handler:`skill-install`});return}if(H(l)){q(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}Jo(i,{recursive:!0}),n.place.mode===`link`?Wo(B(i,V(s)),l,`dir`):Zo(s,l,{recursive:!0,dereference:!0});let f=a;await WJ(e,n.name,{path:f,mode:n.place.mode,...n.place.mode===`copy`?{hash:LD(s)?.contentHash}:{}}),se?.(`files`),Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:f},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?A:Bs;if(!e){q(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=n.unplace.path.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``);if(!HJ(e)[n.name]?.find(e=>e.path===r)){q(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r});return}let i=MB(e,r);if(i===null){q(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return}let a=LD(s)?.contentHash??``;switch(SB(i,V(s),a)){case`different`:q(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r});return;case`canonical-dir`:q(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r});return;case`absent`:break;default:Qo(i,{recursive:!0,force:!0})}await UJ(e,n.name,r),se?.(`files`),Y(t,200,jr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){q(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?A:Bs,l=hB(n.scope),u=ua(e)?e===`agents`?`.agents/skills`:l[e]:e.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),d=u===null||u===``?null:MB(a??r,`${u}/${n.name}`);if(u===null||u===``||d===null){q(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return}let f=V(s),p=o.contentHash,m=SB(d,f,p);if(m===`canonical-dir`){q(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return}if(m===`different`){q(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return}if(m===`absent`){q(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return}let h=i===`link`&&m===`link-to-canonical`||i===`copy`&&m===`same-copy`;if(h&&await WJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}}),!h){let e=R(d);Qo(d,{recursive:!0,force:!0}),Jo(e,{recursive:!0}),i===`link`?Wo(B(e,f),d,`dir`):Zo(f,d,{recursive:!0,dereference:!0}),await WJ(a??r,n.name,{path:`${u}/${n.name}`,mode:i,...i===`copy`?{hash:p}:{}})}se?.(`files`),Y(t,200,jr,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?Et.filter(e=>f?.some(t=>t===e)):[...Et]:f===void 0?mB(r):Et.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),c.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),c.warnings.length>0&&(g.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],v=n.scope===`project`?A:Bs,y=d===void 0?Zs(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=o.hosts[0],i=u,d=ua(i),f;if(!d){let e=i.replace(/\\/g,`/`).replace(/^~\//,``).replace(/^\/+|\/+$/g,``),a=Ws(e),o=V(r,e,n.name);if(e===``||a||!o.startsWith(V(r)+Al)){q(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:i});return}f=o}let p;if(e!==void 0&&i!==e){let e=B(a,V(s)).split(Al).join(`/`),c=wB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:d?i:`agents`,...f===void 0?{}:{destDirAbs:f},leaveLinkBehind:!0,roots:hB(n.scope)});if(!c.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}p=B(a,c.newAbs).split(Al).join(`/`),await WJ(v??r,n.name,{path:e,mode:`link`});for(let e of HJ(v??r)[n.name]??[]){let t=V(v??r,e.path);if(t===c.newAbs)continue;try{if(!Hl(t).isSymbolicLink())continue}catch{continue}let n=null;try{n=W(t)}catch{n=null}(n===null||n===V(s))&&(Qo(t,{recursive:!0,force:!0}),Wo(B(R(t),c.newAbs),t,`dir`))}await WJ(v??r,n.name,{path:p,mode:`copy`}),await LJ(v??r,n.name,i)}se?.(`files`);let m=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name);Y(t,200,jr,{name:n.name,hosts:m?[...m.hosts]:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[],...p===void 0?{}:{sourceMovedTo:p}},{handler:`skill-install`});return}let b=o.hosts.filter(e=>ua(e)),x=o.hosts[0],S;if(f!==void 0&&x!==void 0&&!x.includes(`/`)&&i.length>0&&!i.includes(x)){let e=i[0],c=wB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,newTarget:e,roots:hB(n.scope)});if(!c.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:c.reason});return}s=c.newAbs,S=B(a,c.newAbs).split(Al).join(`/`),await WJ(v??r,n.name,{path:S,mode:`copy`}),await LJ(v??r,n.name,e)}let C=S?S.split(`/`).slice(0,-1).join(`/`):e;EB({canonicalAbs:s,canonicalHash:o.contentHash,name:n.name,cwd:r,targets:f===void 0?[]:b.filter(e=>!i.includes(e)),roots:hB(n.scope)});let w=CB({canonicalAbs:s,canonicalHash:o.contentHash,canonicalRootRel:C,name:n.name,cwd:r,targets:i,mode:y,convertLinks:d===!1,roots:hB(n.scope)});for(let e of w.conflicted)g.push(`A different skill named "${n.name}" already exists in the ${e} skills folder — left untouched.`),_.push(`name-conflict`);if(d!==void 0&&v&&p.length>0){let e=new Set(p.map(e=>`${e}/${n.name}`));for(let t of(HJ(v)[n.name]??[]).filter(t=>e.has(t.path))){let e=V(v,t.path);if(e===V(s))continue;let r=SB(e,V(s),o.contentHash);d===!0&&r===`same-copy`?(Qo(e,{recursive:!0,force:!0}),Wo(B(R(e),V(s)),e,`dir`),await WJ(v,n.name,{path:t.path,mode:`link`})):d===!1&&r===`link-to-canonical`&&(Qo(e,{recursive:!0,force:!0}),Zo(V(s),e,{recursive:!0,dereference:!0}),await WJ(v,n.name,{path:t.path,mode:`copy`,hash:o.contentHash}))}}for(let t of w.hosts){let i=t===`agents`?`.agents/skills`:Mt[t];if(i===null||i===e)continue;let a=V(r,i,n.name),s=!1;try{s=Hl(a).isSymbolicLink()}catch{continue}if(s){y===`link`&&await WJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`link`});continue}let c=H(z(a,`SKILL.md`))?LD(a)?.contentHash:void 0;c!==void 0&&c===o.contentHash&&await WJ(v??r,n.name,{path:`${i}/${n.name}`,mode:`copy`,hash:c})}if((p.length>0||m.length>0)&&v){let e=V(s);for(let t of p){let r=Ws(t),i=V(v,t),a=MB(v,`${t}/${n.name}`);if(t===``||r||a===null||a===e){g.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=SB(a,e,o.contentHash);if(s===`different`){g.push(`A different "${n.name}" already exists at ${t} — left untouched.`),_.push(`name-conflict`);continue}s===`absent`&&(Jo(i,{recursive:!0}),y===`link`?Wo(B(i,e),a,`dir`):Zo(e,a,{recursive:!0,dereference:!0})),await WJ(v,n.name,{path:`${t}/${n.name}`,mode:y,...y===`copy`?{hash:o.contentHash}:{}})}for(let t of m){let r=`${t}/${n.name}`,i=HJ(v)[n.name]?.find(e=>e.path===r),a=MB(v,r);if(a===null){g.push(`"${t}" is not a placeable custom root — skipped.`),_.push(`place-path-invalid`);continue}let s=SB(a,e,o.contentHash);if(s===`different`){g.push(`The copy at ${r} has been hand-edited (a fork) — refused, never deleted. Remove it manually if you mean it.`),_.push(`place-fork-refused`);continue}s!==`absent`&&s!==`canonical-dir`&&Qo(a,{recursive:!0,force:!0}),i&&await UJ(v,n.name,r)}}let T=(n.scope===`project`?iV(l):aV(Bs)).find(e=>e.name===n.name),ee=T?[...T.hosts]:w.hosts;se?.(`files`),Y(t,200,jr,{name:n.name,hosts:ee,scripts:c.hasScripts,warnings:g,warningCodes:_,...S===void 0?{}:{sourceMovedTo:S}},{handler:`skill-install`});return}let v=sB(aI(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&DB(n.name,r,v,hB(n.scope));let y=z(r,...kD),b=H(y)?U(y,`utf-8`):null,x=b===null?null:jD(b);b!==null&&x===null&&Z.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=xB(s,n.name,r,h,C,hB(n.scope));w.length===0?await cI(r,n.name):await sI(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),se?.(`files`),Y(t,200,jr,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Jc=J(Dn,async(e,t,n)=>{try{if(!Rs(n.name,t,`skill-uninstall`))return;let e=cc(n.scope);if(!e){q(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 lc(e,n.name,n.scope);se?.(`files`),Y(t,200,yo,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Yc=nW({GET:J(oo,async(e,t)=>{try{let e=mB(A??``),n=(e,t)=>{let n=zJ(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};Y(t,200,yt,{targets:e,configured:!1,folders:[...A?jJ(l,XB(l,`project`)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...jJ(Bs,XB(Bs,`global`)).map(e=>({...e,scope:`global`,...n(Bs,e)}))]},{handler:`skill-targets-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(ree,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:Bs;if(e.scope===`project`&&!A){q(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await BJ(r,i.join(`/`)),se?.(`files`),Y(t,200,Qt,{targets:mB(A??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(XB(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){q(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?FJ({base:r,folderRel:e.root,targetRootRel:a}):IJ({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){q(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await RJ(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),se?.(`files`),Y(t,200,Qt,{targets:mB(A??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),Xc=J(Be,async(e,t,n)=>{try{let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Rs(n.name,t,`skill-restore`)||ic(n.name,t,`skill-restore`))return;if(n.scope===`global`){q(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=ne?.current;if(!r){q(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await JJ({shadow:r,contentDir:l,contentRoot:O??`.`,name:n.name,version:n.version,skillDirRel:Qs(n.name)});if(!i.ok){Xs(t,i,`skill-restore`);return}let a=[],o=fB(V(l,Qs(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),ar(e,ir(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await lr(`skill-restore`),se?.(`files`),Y(t,200,Pi,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Zc=J(pee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Rs(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Bs:l,{root:a,dirRel:o,realDir:s}=hc(n.scope,n.name),c=!o.startsWith(`${Pa}/`);if(s===null||!H(V(i,o,`SKILL.md`))){q(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=z(n.scope===`global`?Bs:A,...kD),d=Mc(u).skills[n.name];if(!d){let e=Koe(n.name,LD(V(a,n.name))?.contentHash??``,new Date().toISOString())??nc(i,n.name);e&&(d=e)}if(!d){q(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await eY(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),Y(t,200,Vi,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=await HD(d.source,d.skill??n.name),i=e?.source??pO(d.source,d.pluginProvider),a=e?.skill??d.skill,o=e?.spec??ED(i);if(!o){q(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if($Y(t,o,`skill-reimport`))return;let s=await OD(o);r=s.cleanup,f=s.ref;let c=RD(s.dir),l=(a?c.find(e=>e.name===a):void 0)??c.find(e=>e.name===n.name)??c.find(e=>LD(e.dir)?.name===n.name)??(c.length===1?c[0]:void 0);if(!l){q(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:c.map(e=>e.name).join(`, `)});return}let u=ID(l.dir);if(u){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:u});return}p=LD(l.dir)}catch(e){if(e instanceof vD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=tX(p);if(h){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=LD(V(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){Y(t,200,Vi,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=js(p.skillMd).body;if(n.dryRun){let e=LD(V(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&A)try{let e=gs({baseDir:A,timeout:{block:15e3}}),t=B(A,V(a,n.name)).split(Al).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}Y(t,200,Vi,{name:n.name,updated:!0,source:d.source,localBody:js(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await wn(e,`deleted-upstream`)}let x=MP({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){q(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=FP({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:eX});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=IP({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(ar(e,ir(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await lr(`skill-reimport`));let C=Nc(a,n.name),w=n.scope===`project`?await Pc(Fc(e),o):void 0;await eY(u,e=>MD(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!c&&n.scope===`project`&&await Ic({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),se?.(`files`),Y(t,200,Vi,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Qc=J(lee,async(e,t,n)=>{try{if(!A){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=fM(n,me);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Rs(n.name,t,`skill-revert`)||ic(n.name,t,`skill-revert`))return;if(n.scope===`global`){q(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=z(A,...kD),i=Mc(r).skills[n.name];if(!i?.baselineRef){q(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=ne?.current;if(!a){q(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await JJ({shadow:a,contentDir:l,contentRoot:O??`.`,name:n.name,version:i.baselineRef,skillDirRel:Qs(n.name)});if(!o.ok){Xs(t,o,`skill-revert`);return}ar(e,ir(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await lr(`skill-revert`);let s=V(l,Qs(n.name),`..`),c=Nc(s,n.name);await eY(r,e=>MD(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Vs(`project`)&&await Ic({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),se?.(`files`),Y(t,200,sn,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function $c(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])=>We({kind:`folder`,path:e,modifiedTs:t}))}function el(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 tl(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function nl(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 rl(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function il(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function al(e,t,n,r){let i=r.documents.filter(e=>!Xa(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Oe?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Oe.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Oe.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=ke?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Oe.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function ol(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`?el(e.document.content,t):void 0}}async function sl(e){let t=performance.now();if(gl())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await _l(),i=await al(e.query,e.intent,e.semanticParam,n),a=xee(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>ol(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},uce({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 cl(){let e=[],t=new Set;for(let n of iV(l)){let r=V(l,n.dir,`SKILL.md`);try{let i=$l(r);e.push({name:n.name,absolutePath:r,docPath:`${n.dir}/SKILL`,mtimeMs:i.mtimeMs,size:i.size}),t.add(n.name)}catch{}}let n=Vs(`project`);if(!H(n))return e;let r;try{r=Jl(n,{withFileTypes:!0})}catch{return e}for(let i of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!i.isDirectory()||!Ie.test(i.name)||t.has(i.name))continue;let r=V(n,i.name,`SKILL.md`);try{let t=$l(r);e.push({name:i.name,absolutePath:r,docPath:`${Pa}/${i.name}/SKILL`,mtimeMs:t.mtimeMs,size:t.size})}catch{}}return e}function ll(){let e=[];for(let t of cl()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=js(U(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(We({kind:`page`,path:t.docPath,title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function ul(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let dl=new Map;async function fl(){let e=[],t=[],n=new Set;for(let[r,i]of m()){if(fC(r)||pC(r)||ra(r)?.kind===`skill`||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(We({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=ul(i),o=dl.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await pu(i.canonicalPath,`utf-8`)}catch(e){l=!0,Z.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=xR(s,r)}catch(e){Z.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=We({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||dl.set(r,{key:a,doc:u}),e.push(u)}for(let e of dl.keys())n.has(e)||dl.delete(e);let r=VX(),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),L(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),hX().add(1)),{documents:[...e,...ll(),...i,...$c([...e,...i])],truncated:a}}function pl(){return cl().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function ml(){return g?`gen:${g()}|skills${pl()}`:`${[...m()].filter(([e])=>!fC(e)&&!pC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${ul(t)}`).join(``)}|skills${pl()}`}let hl=Ce===void 0;Ce?.then(()=>{hl=!0},e=>{hl=!0,Z.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function gl(){return!hl}async function _l(){let e=`${l}${A??``}`,t=ml(),n=DZ.get(e);if(n?.fingerprint===t&&n.corpus)return{corpus:n.corpus,truncated:n.truncated??!1};if(n?.fingerprint===t&&n.pending)return n.pending;let r=n?.corpus,i=n?.pending,a=(async()=>{let e=i?await i.then(e=>e.corpus,()=>void 0):r,{documents:t,truncated:n}=await fl();if(!e)return _X().add(1,{mode:`cold`}),{corpus:cte(t),truncated:n};let a=kt(e,t);if(a.rebuilt){_X().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;L(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else _X().add(1,{mode:`incremental`}),L(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();DZ.set(e,{fingerprint:t,pending:a});try{let n=await a;return DZ.get(e)?.pending===a&&DZ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw DZ.get(e)?.pending===a&&DZ.delete(e),t}}function vl(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{_l().catch(e=>{Z.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}vl();let yl=nW({GET:J(oo,tW(async(e,t)=>{let n=ws(e),r=n.get(`limit`),i=n.get(`query`)??``,a=tl(n.get(`intent`)),o=oc(n.get(`ranking`)),s=nl(n.get(`scope`)??n.get(`scopes`)),c=rl(n.get(`semantic`)),l=il(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}Y(t,200,Ua,await sl({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:J(Xr,tW(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=tl(n.intent),a=oc(n.ranking),o=nl(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=rl(n.semantic),l=il(n.source);if(r.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}Y(t,200,Ua,await sl({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`}),bl=J(oo,tW(async(e,t)=>{Y(t,200,ste,{...await Wz(au())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Sl(e,t){if(r(e,t,{handler:`handoff`}))try{await Uce(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:bt.probeWithCache})}catch(n){t.headersSent||(Z.error({err:n,requestId:CC(e)},`[handoff] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Cl(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await VF(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Z.error({err:n,requestId:CC(e)},`[spawn-cursor] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Tl=J(cr,async(e,t,n)=>{try{if(!A){AR(`no-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`no-remote`},{handler:ER});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!DR(e,n.kind)){AR(`invalid-path`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`invalid-path`},{handler:ER});return}let r=FR(A);if(r===null){if(zR(A).kind===`no-remote`){AR(`no-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`no-remote`},{handler:ER});return}AR(`detached-head`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`detached-head`},{handler:ER});return}let i=zR(A);if(i.kind===`no-remote`){AR(`no-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`no-remote`},{handler:ER});return}if(i.kind===`non-github`){AR(`non-github-remote`,{kind:n.kind}),Y(t,200,yn,{ok:!1,error:`non-github-remote`},{handler:ER});return}if(!UR(A,r)){AR(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),Y(t,200,yn,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:ER});return}let a=yZ(A,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&L(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=OR(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=kR(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Vu(s)}`,u=await MR(A,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);AR(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),Y(t,200,yn,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:ER})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:ER,cause:e})}},{handler:ER,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ER})}),Ol=J(oo,async(e,t)=>{try{if(!A){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:VU});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(!Yi(r)){q(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:VU});return}if(!zU(i,a)){q(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:VU});return}Y(t,200,iee,await BU(A,r,i,a),{handler:VU})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:VU,cause:e})}},{handler:VU,method:`GET`,skipBodyParse:!0}),kl=J(Di,async(e,t,n)=>{try{if(!A){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:az});return}if(!zU(n.path,n.kind)){q(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:az});return}let e=yZ(A,l);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;Y(t,200,wr,await cz(A,n.branch,r,n.kind),{handler:az})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:az,cause:e})}},{handler:az,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:az})}),jl=J(rr,async(e,t,n)=>{if(fM(n,me).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:KU});return}if(!A){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:KU});return}try{Y(t,200,Oee,await _s(()=>JU(A,n.branch,{fastForward:n.fastForward===!0})),{handler:KU})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:KU,cause:e})}},{handler:KU,method:`POST`});async function Ml(e){let[t,...n]=de,r=[...n,...e];return await new Promise((e,n)=>{let i=xl(t,r,NF({...Ba,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},qR),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${qR}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=iz(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Z.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 Nl=J(oo,async(e,t)=>{if(!Ye.tryAcquire(`/api/share/publish/owners`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:WR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ml([`share`,`owners`,`--json`]),n=ZR(XR(e));rz(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),Y(t,200,qee,n,{handler:WR})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:WR,cause:e})}finally{Ye.release(`/api/share/publish/owners`)}},{handler:WR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:WR})}),Pl=J(oo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!YR(r)||!JR(i)){q(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:GR});return}if(!Ye.tryAcquire(`/api/share/publish/name-check`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:GR,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ml([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=$R(XR(e));rz(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),Y(t,200,Zr,n,{handler:GR})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:GR,cause:e})}finally{Ye.release(`/api/share/publish/name-check`)}},{handler:GR,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:GR})}),Fl=J(la,async(e,t,n)=>{if(!A){rz(`publish-create`,`no-project`),Y(t,200,Na,{ok:!1,error:`no-project`},{handler:KR});return}if(!YR(n.owner)||!JR(n.name)){q(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:KR});return}if(!Ye.tryAcquire(`/api/share/publish`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:KR,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,A,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Ml(e),i=nz(XR(r));rz(`publish-create`,i.ok?`ok`:i.error),i.ok&&ue?.()?.refreshRemote().catch(()=>{}),Y(t,200,Na,i,{handler:KR})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:KR,cause:e})}finally{Ye.release(`/api/share/publish`)}},{handler:KR,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:KR})}),Il=J(cee,async(e,t,n)=>{try{let e=L(`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{}Y(t,200,uee,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Ll=A?rN(A):null;async function Rl(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:dM(e.headers),previewUrl:null,port:Ll?As(Ll)?.port??0:0,singleFile:Re};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}Y(t,200,lte,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function zl(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Ue?.()??{diagnostics:[]};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}Y(t,200,ge,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Vl=`local-op-embeddings-set-key`,Gl=`local-op-embeddings-clear-key`,Kl=`/api/local-op/embeddings`;function ql(){let e=Ae?.();return{projectDir:A??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Yl=J(Yr,async(e,t,n)=>{if(!Ye.tryAcquire(Kl)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Vl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=ql();await new DF(I).setForProject(e,r,n.key),Oe?.reloadCredential(),Y(t,200,Fe,{keyPresent:!0},{handler:Vl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Vl,cause:e})}finally{Ye.release(Kl)}},{handler:Vl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Vl})}),Xl=J(oo,async(e,t)=>{if(!Ye.tryAcquire(Kl)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Gl,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=ql();await new DF(I).clearForProject(e,n),Oe?.reloadCredential(),Y(t,200,Fe,{keyPresent:!1},{handler:Gl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Gl,cause:e})}finally{Ye.release(Kl)}},{handler:Gl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Gl})}),Zl=`local-op-embeddings-test`,Ql=`/api/local-op/embeddings/test`,nu=J(oo,async(e,t)=>{if(!Ye.tryAcquire(Ql)){q(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Zl,extraHeaders:{"Retry-After":`5`}});return}try{let e=Ae?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await bF(new DF(I),A??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await yce({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};Y(t,200,Kee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Zl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Zl,cause:e})}finally{Ye.release(Ql)}},{handler:Zl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zl})}),ru=J(oo,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Oe){let t=Oe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Ae?.()?.baseUrl??`https://api.openai.com/v1`,o=await bF(new DF(I),A??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of f())!fC(e)&&!pC(e)&&!Xa(e)&&(p+=1);Y(t,200,ca,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),iu=0;function ou(){iu+=1,se?.(`lint-config`)}let su=()=>`${iu} ${t.getActiveBranch()}`;async function lu(e,t){let n=je?.()??Ze;try{let r=await oa(e,FL(l,n,{docName:t,projectDir:A??l,onProblem:e=>Z.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Me?.()??`warning`;if(oe&&a!==`off`&&!vC(t)){await on(t,e,`lint-validation`);let r=nR({projectDir:A??l,contentDir:l,baseConfig:n,derivedDocumentIndex:oe,linksValidation:a,admittedDocNames:tn,docFilePathFor:e=>uZ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:uZ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Z.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function uu(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=RL({projectDir:A??l,contentDir:l});return sL(t.schemas,n)}let du=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!kZ(n))){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=je?.()??Ze,i=[],a=ML(l,n??void 0,e=>i.push(e)),o=PL(A??l,NL(r,a),e=>i.push(e));n===null&&i.push(...uu(o)),Y(t,200,_i,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){q(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}),fu=J(ate,async(e,t,n)=>{let r;try{r=eR(V(l),n.ruleId,n.value)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){q(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}ou();try{let e=je?.()??Ze,n=[],r=ML(l,void 0,e=>n.push(e)),i=PL(A??l,NL(e,r),e=>n.push(e));n.push(...uu(i)),Y(t,200,_i,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){q(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`}),mu=J(ni,async(e,t,n)=>{let r;try{let e=V(A??l),t=n.parentPath??[];r=n.delete?JL(e,n.file):n.field!==void 0&&n.removeField?KL(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?qL(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?UL(e,n.file,n.field,n.constraint,t):WL(e,n.file)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){q(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&se?.(`files`),ou();try{let e=je?.()??Ze,n=[],r=ML(l,void 0,e=>n.push(e)),i=PL(A??l,NL(e,r),e=>n.push(e));n.push(...uu(i)),Y(t,200,_i,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),hu=J(oo,async(e,t)=>{try{let e=V(A??l),{schemas:n,truncated:r}=kle(e),i=new Set(n),a=!1;if(P!==void 0){let t=qX({contentDir:l,contentFilter:P,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Ki(a)){let t=B(e,V(l,a));!t.startsWith(`..`)&&!Dl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));Y(t,200,Lee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),gu=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=o.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},_u=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!kZ(n)){q(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=uZ(l,n);if(r===null){q(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=je?.()??Ze,a=[],o=await LL({projectDir:A??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:gu});Y(t,200,li,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof OI){q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),vu=new rL,yu=AJ();function bu(e,t,n){let r=`${n} ${su()} ${t??``}`;return yu.run(r,()=>rR(e,{targetPath:t})).promise}function xu(e,t){q(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Su=J(oo,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&&!YX(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=je?.()??Ze;Y(t,200,$i,await zL({projectDir:A??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:gu,cache:vu,auditGeneration:su}),{handler:`lint-audit`})}catch(e){if(e instanceof IL){xu(t,`lint-audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),wu=J(oo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!YX(i)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!YX(o)){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=uZ(l,o)??`${o}.md`}let s=je?.()??Ze,c=await bu(nR({projectDir:A??l,contentDir:l,baseConfig:s,liveSourceFor:gu,derivedDocumentIndex:oe??null,linksValidation:Me?.(),admittedDocNames:tn,docFilePathFor:e=>uZ(l,e),cache:vu,auditGeneration:su}),i,rL.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){Y(t,200,kr,tR(c),{handler:`audit`});return}Y(t,200,rte,c,{handler:`audit`})}catch(e){if(e instanceof IL){xu(t,`audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),Tu=J(mr,async(t,n,r)=>{try{let t=eZ(r.docName,n,`lint-fix`);if(t===null)return;let i=It(t),a=fM(r,me);if(a.kind===`invalid-summary`){q(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(fC(i)||pC(i)){q(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=uZ(l,i);if(f===null){q(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}tZ(V(l,f),l);let p=je?.()??Ze,{stored:m}=Qn(a.summary),h=await s.getSession(i,o,{displayName:c,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Xle({projectDir:A??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Br(d),n=Nr[t]??Gi(u??o);ce?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{VT(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,zT(h))},h.origin),a.kind!==`anonymous`&&tF(i,o,c,u,void 0,a.kind===`agent`?Zn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{ce?.touchMode(o,`idle`)}let t=await Jt(i);if(t?.kind===`failure`){Xt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Zt(n,`lint-fix`);return}Wt(i,`lint-fix`);try{b=await oa(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Z.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;Y(n,200,Xee,{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 OI){q(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof NC){PC(n,e,`lint-fix`);return}if(e instanceof RC){BC(n,e,`lint-fix`);return}if(e instanceof ZT){q(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e},`[lint-fix] handler failed`),q(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Eu=`link-preview`,Du=new lG({cacheDir:Re?null:V(A??l,`.ok`,`local`,`link-previews`)}),Ou=null,ku=()=>(Ou??=Du.init(),Ou),Au=ze??eG;async function Mu(e){let t=await Au(e);return t.ok?{ok:!0,metadata:await aG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Au})}:{ok:!1,reason:t.reason}}let Pu=()=>{try{return Ve?.()===!0}catch{return!1}},Fu=J(qi,async(e,t,n)=>{try{if(!Pu()){Z.debug({outcome:`disabled`},`[link-preview] request outcome`),Y(t,200,Ya,{ok:!1,reason:`disabled`},{handler:Eu});return}await ku();let e=!1,r=await Du.load(n.url,()=>(e=!0,Mu(n.url)));Du.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Z.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),Y(t,200,Ya,i,{handler:Eu})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Eu,cause:e})}},{handler:Eu,method:`POST`,preBodyGate:(e,t)=>{let n=fG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?q(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Eu}):q(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Eu}),!1)}}),Iu=GM({service:St,getPrincipal:me,onChanged:()=>se?.(`comments`)}),Lu={"/api/config":Rl,"/api/config/diagnostics":zl,"/api/comments":nW({GET:Iu.list,POST:Iu.create},{handler:`comments`}),"/api/comment":nW({GET:Iu.read,POST:Iu.mutate,DELETE:Iu.remove},{handler:`comment`}),"/api/asset":ga,"/api/asset-text":va,"/api/document":Mr,"/api/documents":Pr,"/api/backlinks":Fr,"/api/backlink-counts":ei,"/api/comment-counts":ti,"/api/link-preview":Fu,"/api/forward-links":oi,"/api/link-graph":si,"/api/dead-links":mi,"/api/orphans":ci,"/api/hubs":fi,"/api/tags":vs,"/api/pages":Aa,"/api/folder-config":Es,"/api/template":Fs,"/api/template/import":Ls,"/api/templates":ks,"/api/skill":Sc,"/api/skill-file":kc,"/api/skill-file/rename":Ac,"/api/skills":dc,"/api/skills/installed":zr,"/api/skills/search":Vr,"/api/skills/popular":Wr,"/api/skills/detail":Kr,"/api/skills/preview":qr,"/api/skills/discover":Jr,"/api/skills/resolve-ref":$r,"/api/skill/import":zc,"/api/skills/import-bulk":Bc,"/api/skill/edit-external":yc,"/api/skill/duplicate":xc,"/api/skill/move-scope":bc,"/api/skill-upload":Kc,"/api/skill/install":qc,"/api/skill/uninstall":Jc,"/api/skill/restore":Xc,"/api/skill/reimport":Zc,"/api/skill/revert":Qc,"/api/skill-targets":Yc,"/api/search":yl,"/api/semantic-status":ru,"/api/lint/config":du,"/api/lint/markdownlint-config":fu,"/api/lint/frontmatter-schema":mu,"/api/lint/frontmatter-schemas":hu,"/api/lint":_u,"/api/lint/audit":Su,"/api/lint/fix":Tu,"/api/audit":wu,"/api/suggest-links":ja,"/api/page-headings":Ta,"/api/create-page":xa,"/api/create-folder":Ca,"/api/duplicate-path":wa,"/api/rename-path":Ea,"/api/delete-path":Da,"/api/trash/cleanup":ka,"/api/upload":Fa,"/api/agent-write":yr,"/api/agent-write-md":br,"/api/agent-write-batch":xr,"/api/frontmatter-patch":Dr,"/api/agent-patch":hi,"/api/agent-undo":gi,"/api/agent-activity":Si,"/api/agent-burst-diff":Ci,"/api/save-version":Ni,"/api/history":Fi,"/api/rollback":zi,"/api/metrics/reconciliation":Bi,"/api/metrics/parse-health":Hi,"/api/metrics/agent-presence":aa,"/api/metrics/agent-effects":da,"/api/metrics/watcher-recent":fa,"/api/__embed-detect":pa,"/api/server-info":Wi,"/api/acp/catalog":ta,"/api/share/construct-url":Tl,"/api/share/target-status":kl,"/api/git/branch-info":Ol,"/api/git/checkout":jl,"/api/share/publish/owners":Nl,"/api/share/publish/name-check":Pl,"/api/share/publish":Fl,"/api/principal":ia,"/api/rescue":ya,"/api/workspace":ma,"/api/sync/status":es,"/api/sync/trigger":ns,"/api/sync/conflicts":is,"/api/sync/conflict-content":os,"/api/sync/resolve-conflict":as,"/api/local-op/clone":Wa,"/api/local-op/ok-init":Ja,"/api/local-op/auth/login":To,"/api/local-op/auth/status":Po,"/api/local-op/auth/pat":Io,"/api/local-op/auth/gh-login":ko,"/api/local-op/auth/cancel":jo,"/api/local-op/auth/repos":zo,"/api/local-op/auth/signout":Go,"/api/local-op/auth/set-identity":$o,"/api/local-op/embeddings/set-key":Yl,"/api/local-op/embeddings/clear-key":Xl,"/api/local-op/embeddings/test":nu,"/api/installed-agents":hs,"/api/spawn-cursor":Cl,"/api/handoff":Sl,"/api/install-skill":ps,"/api/skill/install-state":bl,"/api/seed/plan":ls,"/api/seed/apply":ds,"/api/seed/packs":fs,"/api/client-logs":Il};w&&(Lu[`/api/test-reset`]=Ai,Lu[`/api/test-flush-git`]=wi,Lu[`/api/test-rescan-backlinks`]=ji,Lu[`/api/test-rescan-files`]=Mi);let Ru=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),zu=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let r=e.url?.split(`?`)[0];if(!r)return;let a=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};Xse({ts:Date.now(),url:r,method:e.method??``,ua:a(`user-agent`),origin:a(`origin`),referer:a(`referer`),host:a(`host`),remote:e.socket?.remoteAddress,secChUa:a(`sec-ch-ua`),secChUaMobile:a(`sec-ch-ua-mobile`),secChUaPlatform:a(`sec-ch-ua-platform`),secFetchSite:a(`sec-fetch-site`),secFetchDest:a(`sec-fetch-dest`),secFetchMode:a(`sec-fetch-mode`),secFetchUser:a(`sec-fetch-user`)});let o=e.method??`GET`,s=r;r.startsWith(`/api/history/`)?s=`/api/history/:sha`:r.startsWith(`/api/tags/`)?s=`/api/tags/:name`:Lu[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?Vae(e):void 0;if(c!==void 0&&(Hae(e,c),typeof t.setHeader==`function`&&t.setHeader(xC,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Z.info({event:`api.access`,requestId:c,method:o,route:s,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${o} ${s} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(r.startsWith(`/api/`)){let r=e.headers.origin;if(r!==void 0&&!wj(r,n)){q(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(r!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,r),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${xC}, ${Ln.protocol}, ${Ln.runtime}, ${Ln.kind}`),t.setHeader(`Access-Control-Expose-Headers`,xC)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(Ru.has(r)||zu.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!pj(n)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(Re&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!pj(n)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=wo.extract(Eo.active(),e.headers),u=dte(),d=Date.now();await Eo.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:ute.SERVER,attributes:{[us]:o,[ss]:s,[cs]:r,[pte]:`http`,[fte]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=Lu[r],a=!1;if(i)a=!0,await i(e,t);else if(r.startsWith(`/api/history/`)){let n=decodeURIComponent(r.slice(13));n&&(a=!0,await Li(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await ys(e,t,n))}a||q(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${o} ${r}`});let s=t.statusCode;n.setAttribute(ms,s),s>=500&&n.setStatus({code:Co.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:Co.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s,cause:e}),e}finally{n.end();let e=(Date.now()-d)/1e3;nX().record(e,{[us]:o,[ss]:s,[ms]:t.statusCode})}}))}}}function MZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function NZ(e){let t;try{t=Jl(e.contentDir,{withFileTypes:!0})}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&tC(n.name,c)&&e.basenameIndex.add(n.name)}async function PZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await mu(i,{withFileTypes:!0})}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=z(i,o.name),s=Tj(B(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await fu(a)}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await hu(a)}catch(t){let n=MZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Ej(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await gu(i)}catch(t){let n=MZ(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()&&tC(a,u)&&!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()&&tC(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const FZ=M({principalId:F().optional(),tabSessionId:F().optional(),expectedServerInstanceId:F().optional(),expectedBranch:F().optional(),expectedDocLineageEpoch:F().optional(),clientProtocolVersion:N().optional(),clientRuntimeVersion:F().optional(),clientKind:F().optional()}).loose(),IZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function LZ(e){return IZ.includes(e)}function RZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function zZ(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!LZ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var BZ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=RZ(e,this.payload)}};function VZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=FZ.safeParse(t);return n.success?n.data:void 0}var HZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const UZ=L(`conflict-storage`);var WZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=z(rN(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!H(this.storePath)){this.conflicts=[];return}try{let e=U(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){UZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){UZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=R(this.storePath);H(e)||Ul(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return tu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return UZ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-BHI57rg_.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(!Ej(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);dV(r,t),rs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),UZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await aS(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){UZ.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}),UZ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=V(this.projectDir),a=V(i,e.file);if(!Ej(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(dV(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-BHI57rg_.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);dV(a,i),rs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);rs(a,n,`utf-8`);break;case`delete`:H(a)&&Uo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function GZ(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 KZ(e,t){let n=rN(e);try{Ul(n,{recursive:!0}),tu(z(n,er),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=ds(e);Ul(R(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`};tu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const qZ=new Map;let JZ=!1;function YZ(e,t){try{let n=GZ(e,t);for(let e of qZ.keys())KZ(e,n)}catch{}}function XZ(e){qZ.set(e,(qZ.get(e)??0)+1),JZ||(JZ=!0,process.on(`uncaughtExceptionMonitor`,YZ));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=qZ.get(e)??0;n<=1?qZ.delete(e):qZ.set(e,n-1)}}}function ZZ(e){let t=e.scheduler??Ba,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 QZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $Z(e){if(!H(e))return{};let t;try{t=(0,nj.parse)(U(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(!QZ(t))return{};let n=t.telemetry;if(!QZ(n))return{};let r=n.localSink;return QZ(r)?r:{}}function eQ(e){return typeof e==`boolean`?e:void 0}function tQ(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function nQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function rQ(e){if(QZ(e))return tQ(e.maxBytes)}function iQ(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=$Z(Fo(`project`,e.projectDir)),n=$Z(Fo(`project-local`,e.projectDir));if((eQ(n.enabled)??eQ(t.enabled)??!0)===!1)return null;let r=rQ(n.spans)??rQ(t.spans)??52428800,i=rQ(n.logs)??rQ(t.logs)??26214400,a=nQ(n.attributeDenylist)??nQ(t.attributeDenylist)??Ee;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var aQ;(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})(aQ||={});var oQ;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(oQ||={});const sQ=aQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),cQ=e=>{switch(typeof e){case`undefined`:return sQ.undefined;case`string`:return sQ.string;case`number`:return Number.isNaN(e)?sQ.nan:sQ.number;case`boolean`:return sQ.boolean;case`function`:return sQ.function;case`bigint`:return sQ.bigint;case`symbol`:return sQ.symbol;case`object`:return Array.isArray(e)?sQ.array:e===null?sQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?sQ.promise:typeof Map<`u`&&e instanceof Map?sQ.map:typeof Set<`u`&&e instanceof Set?sQ.set:typeof Date<`u`&&e instanceof Date?sQ.date:sQ.object;default:return sQ.unknown}},Q=aQ.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 lQ=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,aQ.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()}};lQ.create=e=>new lQ(e);const uQ=(e,t)=>{let n;switch(e.code){case Q.invalid_type:n=e.received===sQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Q.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,aQ.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:n=`Unrecognized key(s) in object: ${aQ.joinValues(e.keys,`, `)}`;break;case Q.invalid_union:n=`Invalid input`;break;case Q.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${aQ.joinValues(e.options)}`;break;case Q.invalid_enum_value:n=`Invalid enum value. Expected ${aQ.joinValues(e.options)}, received '${e.received}'`;break;case Q.invalid_arguments:n=`Invalid function arguments`;break;case Q.invalid_return_type:n=`Invalid function return type`;break;case Q.invalid_date:n=`Invalid date`;break;case Q.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}"`:aQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Q.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 Q.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 Q.custom:n=`Invalid input`;break;case Q.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Q.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Q.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,aQ.assertNever(e)}return{message:n}};let dQ=uQ;function fQ(){return dQ}const pQ=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 mQ(e,t){let n=fQ(),r=pQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===uQ?void 0:uQ].filter(e=>!!e)});e.common.issues.push(r)}var hQ=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 gQ;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 gQ;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 gQ=Object.freeze({status:`aborted`}),_Q=e=>({status:`dirty`,value:e}),vQ=e=>({status:`valid`,value:e}),yQ=e=>e.status===`aborted`,bQ=e=>e.status===`dirty`,xQ=e=>e.status===`valid`,SQ=e=>typeof Promise<`u`&&e instanceof Promise;var CQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(CQ||={});var wQ=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 TQ=(e,t)=>{if(xQ(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 lQ(e.common.issues);return this._error=t,this._error}}};function EQ(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 DQ=class{get description(){return this._def.description}_getType(e){return cQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hQ,ctx:{common:e.parent.common,data:e.data,parsedType:cQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(SQ(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:cQ(e)};return TQ(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:cQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return xQ(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=>xQ(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:cQ(e)},r=this._parse({data:e,path:n.path,parent:n});return TQ(n,await(SQ(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:Q.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 k$({schema:this,typeName:$.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 A$.create(this,this._def)}nullable(){return j$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return u$.create(this)}promise(){return O$.create(this,this._def)}or(e){return p$.create([this,e],this._def)}and(e){return _$.create(this,e,this._def)}transform(e){return new k$({...EQ(this._def),schema:this,typeName:$.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new M$({...EQ(this._def),innerType:this,defaultValue:t,typeName:$.ZodDefault})}brand(){return new F$({typeName:$.ZodBranded,type:this,...EQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new N$({...EQ(this._def),innerType:this,catchValue:t,typeName:$.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return I$.create(this,e)}readonly(){return L$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const OQ=/^c[^\s-]{8,}$/i,kQ=/^[0-9a-z]+$/,AQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jQ=/^[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,MQ=/^[a-z0-9_-]{21}$/i,NQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,PQ=/^[-+]?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)?)??$/,FQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let IQ;const LQ=/^(?:(?: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])$/,RQ=/^(?:(?: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])$/,zQ=/^(([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]))$/,BQ=/^(([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])$/,VQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,HQ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,UQ=`((\\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])))`,WQ=RegExp(`^${UQ}$`);function GQ(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 KQ(e){return RegExp(`^${GQ(e)}$`)}function qQ(e){let t=`${UQ}T${GQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function JQ(e,t){return!!((t===`v4`||!t)&&LQ.test(e)||(t===`v6`||!t)&&zQ.test(e))}function YQ(e,t){if(!NQ.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 XQ(e,t){return!!((t===`v4`||!t)&&RQ.test(e)||(t===`v6`||!t)&&BQ.test(e))}var ZQ=class e extends DQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==sQ.string){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.string,received:t.parsedType}),gQ}let t=new hQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.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),mQ(n,{code:Q.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?mQ(n,{code:Q.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&mQ(n,{code:Q.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)FQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`email`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)IQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),IQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`emoji`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)jQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`uuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)MQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`nanoid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)OQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`cuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)kQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`cuid2`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)AQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`ulid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),mQ(n,{validation:`url`,code:Q.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),mQ(n,{validation:`regex`,code:Q.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),mQ(n,{code:Q.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),mQ(n,{code:Q.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?qQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?WQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?KQ(r).test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?PQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`duration`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?JQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`ip`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?YQ(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`jwt`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?XQ(e.data,r.version)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`cidr`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?VQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`base64`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?HQ.test(e.data)||(n=this._getOrReturnCtx(e,n),mQ(n,{validation:`base64url`,code:Q.invalid_string,message:r.message}),t.dirty()):aQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Q.invalid_string,...CQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...CQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...CQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...CQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...CQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...CQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...CQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...CQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...CQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...CQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...CQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...CQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...CQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...CQ.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,...CQ.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,...CQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...CQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...CQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...CQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...CQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...CQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...CQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...CQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...CQ.errToObj(t)})}nonempty(e){return this.min(1,CQ.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}};ZQ.create=e=>new ZQ({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...EQ(e)});function QQ(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 $Q=class e extends DQ{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)!==sQ.number){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.number,received:t.parsedType}),gQ}let t,n=new hQ;for(let r of this._def.checks)r.kind===`int`?aQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),mQ(t,{code:Q.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),mQ(t,{code:Q.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),mQ(t,{code:Q.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?QQ(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),mQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),mQ(t,{code:Q.not_finite,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,CQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,CQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,CQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,CQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:CQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:CQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:CQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:CQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:CQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:CQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:CQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:CQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:CQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:CQ.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`&&aQ.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)}};$Q.create=e=>new $Q({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...EQ(e)});var e$=class e extends DQ{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)!==sQ.bigint)return this._getInvalidInput(e);let t,n=new hQ;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),mQ(t,{code:Q.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),mQ(t,{code:Q.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),mQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.bigint,received:t.parsedType}),gQ}gte(e,t){return this.setLimit(`min`,e,!0,CQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,CQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,CQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,CQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:CQ.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:CQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:CQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:CQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:CQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:CQ.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}};e$.create=e=>new e$({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...EQ(e)});var t$=class extends DQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==sQ.boolean){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.boolean,received:t.parsedType}),gQ}return vQ(e.data)}};t$.create=e=>new t$({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...EQ(e)});var n$=class e extends DQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==sQ.date){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.date,received:t.parsedType}),gQ}if(Number.isNaN(e.data.getTime()))return mQ(this._getOrReturnCtx(e),{code:Q.invalid_date}),gQ;let t=new hQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),mQ(n,{code:Q.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),mQ(n,{code:Q.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):aQ.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:CQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:CQ.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)}};n$.create=e=>new n$({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...EQ(e)});var r$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.symbol){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.symbol,received:t.parsedType}),gQ}return vQ(e.data)}};r$.create=e=>new r$({typeName:$.ZodSymbol,...EQ(e)});var i$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.undefined,received:t.parsedType}),gQ}return vQ(e.data)}};i$.create=e=>new i$({typeName:$.ZodUndefined,...EQ(e)});var a$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.null){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.null,received:t.parsedType}),gQ}return vQ(e.data)}};a$.create=e=>new a$({typeName:$.ZodNull,...EQ(e)});var o$=class extends DQ{constructor(){super(...arguments),this._any=!0}_parse(e){return vQ(e.data)}};o$.create=e=>new o$({typeName:$.ZodAny,...EQ(e)});var s$=class extends DQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return vQ(e.data)}};s$.create=e=>new s$({typeName:$.ZodUnknown,...EQ(e)});var c$=class extends DQ{_parse(e){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.never,received:t.parsedType}),gQ}};c$.create=e=>new c$({typeName:$.ZodNever,...EQ(e)});var l$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.undefined){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.void,received:t.parsedType}),gQ}return vQ(e.data)}};l$.create=e=>new l$({typeName:$.ZodVoid,...EQ(e)});var u$=class e extends DQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==sQ.array)return mQ(t,{code:Q.invalid_type,expected:sQ.array,received:t.parsedType}),gQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(mQ(t,{code:e?Q.too_big:Q.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&&(mQ(t,{code:Q.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&&(mQ(t,{code:Q.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 wQ(t,e,t.path,n)))).then(e=>hQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new wQ(t,e,t.path,n)));return hQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:CQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:CQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:CQ.toString(n)}})}nonempty(e){return this.min(1,e)}};u$.create=(e,t)=>new u$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...EQ(t)});function d$(e){if(e instanceof f$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=A$.create(d$(r))}return new f$({...e._def,shape:()=>t})}else if(e instanceof u$)return new u$({...e._def,type:d$(e.element)});else if(e instanceof A$)return A$.create(d$(e.unwrap()));else if(e instanceof j$)return j$.create(d$(e.unwrap()));else if(e instanceof v$)return v$.create(e.items.map(e=>d$(e)));else return e}var f$=class e extends DQ{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=aQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==sQ.object){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.object,received:t.parsedType}),gQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof c$&&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 wQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof c$){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&&(mQ(n,{code:Q.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 wQ(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=>hQ.mergeObjectSync(t,e)):hQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return CQ.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:CQ.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:$.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 aQ.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 aQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return d$(this)}partial(t){let n={};for(let e of aQ.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 aQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof A$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return T$(aQ.objectKeys(this.shape))}};f$.create=(e,t)=>new f$({shape:()=>e,unknownKeys:`strip`,catchall:c$.create(),typeName:$.ZodObject,...EQ(t)}),f$.strictCreate=(e,t)=>new f$({shape:()=>e,unknownKeys:`strict`,catchall:c$.create(),typeName:$.ZodObject,...EQ(t)}),f$.lazycreate=(e,t)=>new f$({shape:e,unknownKeys:`strip`,catchall:c$.create(),typeName:$.ZodObject,...EQ(t)});var p$=class extends DQ{_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 lQ(e.ctx.common.issues));return mQ(t,{code:Q.invalid_union,unionErrors:n}),gQ}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 lQ(e));return mQ(t,{code:Q.invalid_union,unionErrors:i}),gQ}}get options(){return this._def.options}};p$.create=(e,t)=>new p$({options:e,typeName:$.ZodUnion,...EQ(t)});const m$=e=>e instanceof C$?m$(e.schema):e instanceof k$?m$(e.innerType()):e instanceof w$?[e.value]:e instanceof E$?e.options:e instanceof D$?aQ.objectValues(e.enum):e instanceof M$?m$(e._def.innerType):e instanceof i$?[void 0]:e instanceof a$?[null]:e instanceof A$?[void 0,...m$(e.unwrap())]:e instanceof j$?[null,...m$(e.unwrap())]:e instanceof F$||e instanceof L$?m$(e.unwrap()):e instanceof N$?m$(e._def.innerType):[];var h$=class e extends DQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.object)return mQ(t,{code:Q.invalid_type,expected:sQ.object,received:t.parsedType}),gQ;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}):(mQ(t,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),gQ)}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=m$(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:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...EQ(r)})}};function g$(e,t){let n=cQ(e),r=cQ(t);if(e===t)return{valid:!0,data:e};if(n===sQ.object&&r===sQ.object){let n=aQ.objectKeys(t),r=aQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=g$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===sQ.array&&r===sQ.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=g$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===sQ.date&&r===sQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var _$=class extends DQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(yQ(e)||yQ(r))return gQ;let i=g$(e.value,r.value);return i.valid?((bQ(e)||bQ(r))&&t.dirty(),{status:t.value,value:i.data}):(mQ(n,{code:Q.invalid_intersection_types}),gQ)};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}))}};_$.create=(e,t,n)=>new _$({left:e,right:t,typeName:$.ZodIntersection,...EQ(n)});var v$=class e extends DQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.array)return mQ(n,{code:Q.invalid_type,expected:sQ.array,received:n.parsedType}),gQ;if(n.data.length<this._def.items.length)return mQ(n,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),gQ;!this._def.rest&&n.data.length>this._def.items.length&&(mQ(n,{code:Q.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 wQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>hQ.mergeArray(t,e)):hQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};v$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new v$({items:e,typeName:$.ZodTuple,rest:null,...EQ(t)})};var y$=class e extends DQ{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!==sQ.object)return mQ(n,{code:Q.invalid_type,expected:sQ.object,received:n.parsedType}),gQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new wQ(n,e,n.path,e)),value:a._parse(new wQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?hQ.mergeObjectAsync(t,r):hQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof DQ?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...EQ(r)}):new e({keyType:ZQ.create(),valueType:t,typeName:$.ZodRecord,...EQ(n)})}},b$=class extends DQ{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!==sQ.map)return mQ(n,{code:Q.invalid_type,expected:sQ.map,received:n.parsedType}),gQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new wQ(n,e,n.path,[a,`key`])),value:i._parse(new wQ(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 gQ;(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 gQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};b$.create=(e,t,n)=>new b$({valueType:t,keyType:e,typeName:$.ZodMap,...EQ(n)});var x$=class e extends DQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==sQ.set)return mQ(n,{code:Q.invalid_type,expected:sQ.set,received:n.parsedType}),gQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(mQ(n,{code:Q.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&&(mQ(n,{code:Q.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 gQ;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 wQ(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:CQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:CQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};x$.create=(e,t)=>new x$({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...EQ(t)});var S$=class e extends DQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==sQ.function)return mQ(t,{code:Q.invalid_type,expected:sQ.function,received:t.parsedType}),gQ;function n(e,n){return pQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fQ(),uQ].filter(e=>!!e),issueData:{code:Q.invalid_arguments,argumentsError:n}})}function r(e,n){return pQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fQ(),uQ].filter(e=>!!e),issueData:{code:Q.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof O$){let e=this;return vQ(async function(...t){let o=new lQ([]),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 vQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new lQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new lQ([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:v$.create(t).rest(s$.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||v$.create([]).rest(s$.create()),returns:n||s$.create(),typeName:$.ZodFunction,...EQ(r)})}},C$=class extends DQ{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})}};C$.create=(e,t)=>new C$({getter:e,typeName:$.ZodLazy,...EQ(t)});var w$=class extends DQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return mQ(t,{received:t.data,code:Q.invalid_literal,expected:this._def.value}),gQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};w$.create=(e,t)=>new w$({value:e,typeName:$.ZodLiteral,...EQ(t)});function T$(e,t){return new E$({values:e,typeName:$.ZodEnum,...EQ(t)})}var E$=class e extends DQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return mQ(t,{expected:aQ.joinValues(n),received:t.parsedType,code:Q.invalid_type}),gQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return mQ(t,{received:t.data,code:Q.invalid_enum_value,options:n}),gQ}return vQ(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})}};E$.create=T$;var D$=class extends DQ{_parse(e){let t=aQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==sQ.string&&n.parsedType!==sQ.number){let e=aQ.objectValues(t);return mQ(n,{expected:aQ.joinValues(e),received:n.parsedType,code:Q.invalid_type}),gQ}if(this._cache||=new Set(aQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=aQ.objectValues(t);return mQ(n,{received:n.data,code:Q.invalid_enum_value,options:e}),gQ}return vQ(e.data)}get enum(){return this._def.values}};D$.create=(e,t)=>new D$({values:e,typeName:$.ZodNativeEnum,...EQ(t)});var O$=class extends DQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==sQ.promise&&t.common.async===!1?(mQ(t,{code:Q.invalid_type,expected:sQ.promise,received:t.parsedType}),gQ):vQ((t.parsedType===sQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};O$.create=(e,t)=>new O$({type:e,typeName:$.ZodPromise,...EQ(t)});var k$=class extends DQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.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=>{mQ(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 gQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?gQ:r.status===`dirty`||t.value===`dirty`?_Q(r.value):r});{if(t.value===`aborted`)return gQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?gQ:r.status===`dirty`||t.value===`dirty`?_Q(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`?gQ:(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`?gQ:(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(!xQ(e))return gQ;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=>xQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):gQ);aQ.assertNever(r)}};k$.create=(e,t,n)=>new k$({schema:e,typeName:$.ZodEffects,effect:t,...EQ(n)}),k$.createWithPreprocess=(e,t,n)=>new k$({schema:t,effect:{type:`preprocess`,transform:e},typeName:$.ZodEffects,...EQ(n)});var A$=class extends DQ{_parse(e){return this._getType(e)===sQ.undefined?vQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};A$.create=(e,t)=>new A$({innerType:e,typeName:$.ZodOptional,...EQ(t)});var j$=class extends DQ{_parse(e){return this._getType(e)===sQ.null?vQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j$.create=(e,t)=>new j$({innerType:e,typeName:$.ZodNullable,...EQ(t)});var M$=class extends DQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===sQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};M$.create=(e,t)=>new M$({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...EQ(t)});var N$=class extends DQ{_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 SQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new lQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};N$.create=(e,t)=>new N$({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...EQ(t)});var P$=class extends DQ{_parse(e){if(this._getType(e)!==sQ.nan){let t=this._getOrReturnCtx(e);return mQ(t,{code:Q.invalid_type,expected:sQ.nan,received:t.parsedType}),gQ}return{status:`valid`,value:e.data}}};P$.create=e=>new P$({typeName:$.ZodNaN,...EQ(e)});var F$=class extends DQ{_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}},I$=class e extends DQ{_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`?gQ:e.status===`dirty`?(t.dirty(),_Q(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`?gQ: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:$.ZodPipeline})}},L$=class extends DQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(xQ(e)&&(e.value=Object.freeze(e.value)),e);return SQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:$.ZodReadonly,...EQ(t)}),f$.lazycreate;var $;(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`})($||={}),ZQ.create,$Q.create,P$.create,e$.create,t$.create,n$.create,r$.create,i$.create,a$.create,o$.create,s$.create,c$.create,l$.create,u$.create;const R$=f$.create;f$.strictCreate,p$.create,h$.create,_$.create,v$.create,y$.create,b$.create,x$.create,S$.create,C$.create,w$.create,E$.create,D$.create,O$.create,k$.create,A$.create,j$.create,k$.createWithPreprocess,I$.create;const z$=m(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);v.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>he(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>me(e,t,n),e.parseAsync=async(t,n)=>r(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>h(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)=>y(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),B$=m(`ZodMiniObject`,(e,t)=>{o.init(e,t),z$.init(e,t),l(e,`shape`,()=>t.shape)});function V$(e,t){return new B$({type:`object`,shape:e??{},...d(t)})}function H$(e){return!!e._zod}function U$(e){let t=Object.values(e);if(t.length===0)return V$({});let n=t.every(H$),r=t.every(e=>!H$(e));if(n)return V$(e);if(r)return R$(e);throw Error(`Mixed Zod versions detected in object shape.`)}function W$(e,t){return H$(e)?me(e,t):e.safeParse(t)}async function G$(e,t){return H$(e)?await h(e,t):await e.safeParseAsync(t)}function K$(e){if(!e)return;let t;if(t=H$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function q$(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 U$(e)}}if(H$(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 J$(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 Y$(e){return e.description}function X$(e){if(H$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Z$(e){if(H$(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 Q$=`2025-11-25`,$$=[Q$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],e1=`io.modelcontextprotocol/related-task`,t1=be(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),n1=I([F(),N().int()]),r1=F();ue({ttl:N().optional(),pollInterval:N().optional()});const eue=M({ttl:N().optional()}),tue=M({taskId:F()}),i1=ue({progressToken:n1.optional(),[e1]:tue.optional()}),a1=M({_meta:i1.optional()}),o1=a1.extend({task:eue.optional()}),nue=e=>o1.safeParse(e).success,s1=M({method:F(),params:a1.loose().optional()}),c1=M({_meta:i1.optional()}),l1=M({method:F(),params:c1.loose().optional()}),u1=ue({_meta:i1.optional()}),d1=I([F(),N().int()]),f1=M({jsonrpc:k(`2.0`),id:d1,...s1.shape}).strict(),p1=e=>f1.safeParse(e).success,m1=M({jsonrpc:k(`2.0`),...l1.shape}).strict(),rue=e=>m1.safeParse(e).success,h1=M({jsonrpc:k(`2.0`),id:d1,result:u1}).strict(),g1=e=>h1.safeParse(e).success;var _1;(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`})(_1||={});const v1=M({jsonrpc:k(`2.0`),id:d1.optional(),error:M({code:N().int(),message:F(),data:O().optional()})}).strict(),y1=e=>v1.safeParse(e).success,b1=I([f1,m1,h1,v1]);I([h1,v1]);const x1=u1.strict(),iue=c1.extend({requestId:d1.optional(),reason:F().optional()}),S1=l1.extend({method:k(`notifications/cancelled`),params:iue}),C1=M({icons:j(M({src:F(),mimeType:F().optional(),sizes:j(F()).optional(),theme:we([`light`,`dark`]).optional()})).optional()}),w1=M({name:F(),title:F().optional()}),T1=w1.extend({...w1.shape,...C1.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),aue=fe(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,_e(M({form:_e(M({applyDefaults:D().optional()}),E(F(),O())).optional(),url:t1.optional()}),E(F(),O()).optional())),oue=ue({list:t1.optional(),cancel:t1.optional(),requests:ue({sampling:ue({createMessage:t1.optional()}).optional(),elicitation:ue({create:t1.optional()}).optional()}).optional()}),sue=ue({list:t1.optional(),cancel:t1.optional(),requests:ue({tools:ue({call:t1.optional()}).optional()}).optional()}),cue=M({experimental:E(F(),t1).optional(),sampling:M({context:t1.optional(),tools:t1.optional()}).optional(),elicitation:aue.optional(),roots:M({listChanged:D().optional()}).optional(),tasks:oue.optional(),extensions:E(F(),t1).optional()}),lue=a1.extend({protocolVersion:F(),capabilities:cue,clientInfo:T1}),E1=s1.extend({method:k(`initialize`),params:lue}),D1=e=>E1.safeParse(e).success,uue=M({experimental:E(F(),t1).optional(),logging:t1.optional(),completions:t1.optional(),prompts:M({listChanged:D().optional()}).optional(),resources:M({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:M({listChanged:D().optional()}).optional(),tasks:sue.optional(),extensions:E(F(),t1).optional()}),due=u1.extend({protocolVersion:F(),capabilities:uue,serverInfo:T1,instructions:F().optional()}),O1=l1.extend({method:k(`notifications/initialized`),params:c1.optional()}),fue=e=>O1.safeParse(e).success,k1=s1.extend({method:k(`ping`),params:a1.optional()}),pue=M({progress:N(),total:A(N()),message:A(F())}),mue=M({...c1.shape,...pue.shape,progressToken:n1}),A1=l1.extend({method:k(`notifications/progress`),params:mue}),hue=a1.extend({cursor:r1.optional()}),j1=s1.extend({params:hue.optional()}),M1=u1.extend({nextCursor:r1.optional()}),gue=we([`working`,`input_required`,`completed`,`failed`,`cancelled`]),N1=M({taskId:F(),status:gue,ttl:I([N(),ye()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:A(N()),statusMessage:A(F())}),P1=u1.extend({task:N1}),_ue=c1.merge(N1),F1=l1.extend({method:k(`notifications/tasks/status`),params:_ue}),I1=s1.extend({method:k(`tasks/get`),params:a1.extend({taskId:F()})}),L1=u1.merge(N1),R1=s1.extend({method:k(`tasks/result`),params:a1.extend({taskId:F()})});u1.loose();const z1=j1.extend({method:k(`tasks/list`)}),B1=M1.extend({tasks:j(N1)}),V1=s1.extend({method:k(`tasks/cancel`),params:a1.extend({taskId:F()})}),vue=u1.merge(N1),H1=M({uri:F(),mimeType:A(F()),_meta:E(F(),O()).optional()}),U1=H1.extend({text:F()}),W1=F().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),G1=H1.extend({blob:W1}),K1=we([`user`,`assistant`]),q1=M({audience:j(K1).optional(),priority:N().min(0).max(1).optional(),lastModified:i({offset:!0}).optional()}),J1=M({...w1.shape,...C1.shape,uri:F(),description:A(F()),mimeType:A(F()),size:A(N()),annotations:q1.optional(),_meta:A(ue({}))}),yue=M({...w1.shape,...C1.shape,uriTemplate:F(),description:A(F()),mimeType:A(F()),annotations:q1.optional(),_meta:A(ue({}))}),Y1=j1.extend({method:k(`resources/list`)}),bue=M1.extend({resources:j(J1)}),X1=j1.extend({method:k(`resources/templates/list`)}),xue=M1.extend({resourceTemplates:j(yue)}),Z1=a1.extend({uri:F()}),Sue=Z1,Q1=s1.extend({method:k(`resources/read`),params:Sue}),Cue=u1.extend({contents:j(I([U1,G1]))}),wue=l1.extend({method:k(`notifications/resources/list_changed`),params:c1.optional()}),Tue=Z1,Eue=s1.extend({method:k(`resources/subscribe`),params:Tue}),Due=Z1,Oue=s1.extend({method:k(`resources/unsubscribe`),params:Due}),kue=c1.extend({uri:F()}),Aue=l1.extend({method:k(`notifications/resources/updated`),params:kue}),jue=M({name:F(),description:A(F()),required:A(D())}),Mue=M({...w1.shape,...C1.shape,description:A(F()),arguments:A(j(jue)),_meta:A(ue({}))}),$1=j1.extend({method:k(`prompts/list`)}),Nue=M1.extend({prompts:j(Mue)}),Pue=a1.extend({name:F(),arguments:E(F(),F()).optional()}),e0=s1.extend({method:k(`prompts/get`),params:Pue}),t0=M({type:k(`text`),text:F(),annotations:q1.optional(),_meta:E(F(),O()).optional()}),n0=M({type:k(`image`),data:W1,mimeType:F(),annotations:q1.optional(),_meta:E(F(),O()).optional()}),r0=M({type:k(`audio`),data:W1,mimeType:F(),annotations:q1.optional(),_meta:E(F(),O()).optional()}),Fue=M({type:k(`tool_use`),name:F(),id:F(),input:E(F(),O()),_meta:E(F(),O()).optional()}),Iue=M({type:k(`resource`),resource:I([U1,G1]),annotations:q1.optional(),_meta:E(F(),O()).optional()}),i0=I([t0,n0,r0,J1.extend({type:k(`resource_link`)}),Iue]),Lue=M({role:K1,content:i0}),Rue=u1.extend({description:F().optional(),messages:j(Lue)}),zue=l1.extend({method:k(`notifications/prompts/list_changed`),params:c1.optional()}),Bue=M({title:F().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Vue=M({taskSupport:we([`required`,`optional`,`forbidden`]).optional()}),a0=M({...w1.shape,...C1.shape,description:F().optional(),inputSchema:M({type:k(`object`),properties:E(F(),t1).optional(),required:j(F()).optional()}).catchall(O()),outputSchema:M({type:k(`object`),properties:E(F(),t1).optional(),required:j(F()).optional()}).catchall(O()).optional(),annotations:Bue.optional(),execution:Vue.optional(),_meta:E(F(),O()).optional()}),o0=j1.extend({method:k(`tools/list`)}),Hue=M1.extend({tools:j(a0)}),s0=u1.extend({content:j(i0).default([]),structuredContent:E(F(),O()).optional(),isError:D().optional()});s0.or(u1.extend({toolResult:O()}));const Uue=o1.extend({name:F(),arguments:E(F(),O()).optional()}),c0=s1.extend({method:k(`tools/call`),params:Uue}),Wue=l1.extend({method:k(`notifications/tools/list_changed`),params:c1.optional()});M({autoRefresh:D().default(!0),debounceMs:N().int().nonnegative().default(300)});const l0=we([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Gue=a1.extend({level:l0}),u0=s1.extend({method:k(`logging/setLevel`),params:Gue}),Kue=c1.extend({level:l0,logger:F().optional(),data:O()}),que=l1.extend({method:k(`notifications/message`),params:Kue}),Jue=M({hints:j(M({name:F().optional()})).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),Yue=M({mode:we([`auto`,`required`,`none`]).optional()}),Xue=M({type:k(`tool_result`),toolUseId:F().describe(`The unique identifier for the corresponding tool call.`),content:j(i0).default([]),structuredContent:M({}).loose().optional(),isError:D().optional(),_meta:E(F(),O()).optional()}),Zue=Se(`type`,[t0,n0,r0]),d0=Se(`type`,[t0,n0,r0,Fue,Xue]),Que=M({role:K1,content:I([d0,j(d0)]),_meta:E(F(),O()).optional()}),$ue=o1.extend({messages:j(Que),modelPreferences:Jue.optional(),systemPrompt:F().optional(),includeContext:we([`none`,`thisServer`,`allServers`]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:j(F()).optional(),metadata:t1.optional(),tools:j(a0).optional(),toolChoice:Yue.optional()}),ede=s1.extend({method:k(`sampling/createMessage`),params:$ue}),f0=u1.extend({model:F(),stopReason:A(we([`endTurn`,`stopSequence`,`maxTokens`]).or(F())),role:K1,content:Zue}),p0=u1.extend({model:F(),stopReason:A(we([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(F())),role:K1,content:I([d0,j(d0)])}),tde=M({type:k(`boolean`),title:F().optional(),description:F().optional(),default:D().optional()}),nde=M({type:k(`string`),title:F().optional(),description:F().optional(),minLength:N().optional(),maxLength:N().optional(),format:we([`email`,`uri`,`date`,`date-time`]).optional(),default:F().optional()}),rde=M({type:we([`number`,`integer`]),title:F().optional(),description:F().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),ide=M({type:k(`string`),title:F().optional(),description:F().optional(),enum:j(F()),default:F().optional()}),ade=M({type:k(`string`),title:F().optional(),description:F().optional(),oneOf:j(M({const:F(),title:F()})),default:F().optional()}),ode=I([I([M({type:k(`string`),title:F().optional(),description:F().optional(),enum:j(F()),enumNames:j(F()).optional(),default:F().optional()}),I([ide,ade]),I([M({type:k(`array`),title:F().optional(),description:F().optional(),minItems:N().optional(),maxItems:N().optional(),items:M({type:k(`string`),enum:j(F())}),default:j(F()).optional()}),M({type:k(`array`),title:F().optional(),description:F().optional(),minItems:N().optional(),maxItems:N().optional(),items:M({anyOf:j(M({const:F(),title:F()}))}),default:j(F()).optional()})])]),tde,nde,rde]),sde=I([o1.extend({mode:k(`form`).optional(),message:F(),requestedSchema:M({type:k(`object`),properties:E(F(),ode),required:j(F()).optional()})}),o1.extend({mode:k(`url`),message:F(),elicitationId:F(),url:F().url()})]),cde=s1.extend({method:k(`elicitation/create`),params:sde}),lde=c1.extend({elicitationId:F()}),ude=l1.extend({method:k(`notifications/elicitation/complete`),params:lde}),m0=u1.extend({action:we([`accept`,`decline`,`cancel`]),content:fe(e=>e===null?void 0:e,E(F(),I([F(),N(),D(),j(F())])).optional())}),dde=M({type:k(`ref/resource`),uri:F()}),fde=M({type:k(`ref/prompt`),name:F()}),pde=a1.extend({ref:I([fde,dde]),argument:M({name:F(),value:F()}),context:M({arguments:E(F(),F()).optional()}).optional()}),h0=s1.extend({method:k(`completion/complete`),params:pde});function mde(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function hde(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const gde=u1.extend({completion:ue({values:j(F()).max(100),total:A(N().int()),hasMore:A(D())})}),_de=M({uri:F().startsWith(`file://`),name:F().optional(),_meta:E(F(),O()).optional()}),vde=s1.extend({method:k(`roots/list`),params:a1.optional()}),g0=u1.extend({roots:j(_de)}),yde=l1.extend({method:k(`notifications/roots/list_changed`),params:c1.optional()});I([k1,E1,h0,u0,e0,$1,Y1,X1,Q1,Eue,Oue,c0,o0,I1,R1,z1,V1]),I([S1,A1,O1,yde,F1]),I([x1,f0,p0,m0,g0,L1,B1,P1]),I([k1,ede,cde,vde,I1,R1,z1,V1]),I([S1,A1,que,Aue,wue,Wue,zue,F1,ude]),I([x1,due,gde,Rue,Nue,bue,xue,Cue,s0,Hue,L1,B1,P1]);var _0=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===_1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new bde(e.elicitations,n)}return new e(t,n,r)}},bde=class extends _0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(_1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function v0(e){return e===`completed`||e===`failed`||e===`cancelled`}const xde=Symbol(`Let zodToJsonSchema decide on which parser to use`),y0={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`},Sde=e=>typeof e==`string`?{...y0,name:e}:{...y0,...e},Cde=e=>{let t=Sde(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 b0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function x0(e,t,n,r,i){e[t]=n,b0(e,t,r,i)}const S0=(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 C0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?S0(t,e.currentPath):t.join(`/`)}}function wde(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==$.ZodAny&&(n.items=I0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&x0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&x0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(x0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),x0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Tde(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?x0(n,`minimum`,r.value,r.message,t):x0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),x0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?x0(n,`maximum`,r.value,r.message,t):x0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),x0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:x0(n,`multipleOf`,r.value,r.message,t);break}return n}function Ede(){return{type:`boolean`}}function w0(e,t){return I0(e.type._def,t)}const Dde=(e,t)=>I0(e.innerType._def,t);function T0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>T0(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 Ode(e,t)}}const Ode=(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`:x0(n,`minimum`,r.value,r.message,t);break;case`max`:x0(n,`maximum`,r.value,r.message,t);break}return n};function kde(e,t){return{...I0(e.innerType._def,t),default:e.defaultValue()}}function Ade(e,t){return t.effectStrategy===`input`?I0(e.schema._def,t):C0(t)}function jde(e){return{type:`string`,enum:Array.from(e.values)}}const Mde=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Nde(e,t){let n=[I0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),I0(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(Mde(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 Pde(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 E0;const D0={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:()=>(E0===void 0&&(E0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),E0),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 O0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:x0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:x0(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`:A0(n,`email`,r.message,t);break;case`format:idn-email`:A0(n,`idn-email`,r.message,t);break;case`pattern:zod`:j0(n,D0.email,r.message,t);break}break;case`url`:A0(n,`uri`,r.message,t);break;case`uuid`:A0(n,`uuid`,r.message,t);break;case`regex`:j0(n,r.regex,r.message,t);break;case`cuid`:j0(n,D0.cuid,r.message,t);break;case`cuid2`:j0(n,D0.cuid2,r.message,t);break;case`startsWith`:j0(n,RegExp(`^${k0(r.value,t)}`),r.message,t);break;case`endsWith`:j0(n,RegExp(`${k0(r.value,t)}$`),r.message,t);break;case`datetime`:A0(n,`date-time`,r.message,t);break;case`date`:A0(n,`date`,r.message,t);break;case`time`:A0(n,`time`,r.message,t);break;case`duration`:A0(n,`duration`,r.message,t);break;case`length`:x0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),x0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:j0(n,RegExp(k0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&A0(n,`ipv4`,r.message,t),r.version!==`v4`&&A0(n,`ipv6`,r.message,t);break;case`base64url`:j0(n,D0.base64url,r.message,t);break;case`jwt`:j0(n,D0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&j0(n,D0.ipv4Cidr,r.message,t),r.version!==`v4`&&j0(n,D0.ipv6Cidr,r.message,t);break;case`emoji`:j0(n,D0.emoji(),r.message,t);break;case`ulid`:j0(n,D0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:A0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:x0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:j0(n,D0.base64,r.message,t);break}break;case`nanoid`:j0(n,D0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function k0(e,t){return t.patternStrategy===`escape`?Ide(e):e}const Fde=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Ide(e){let t=``;for(let n=0;n<e.length;n++)Fde.has(e[n])||(t+=`\\`),t+=e[n];return t}function A0(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}}})):x0(e,`format`,t,n,r)}function j0(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:M0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):x0(e,`pattern`,M0(t,r),n,r)}function M0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
1216
1216
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
1217
1217
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function N0(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===$.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:I0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??C0(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:I0(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===$.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=O0(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===$.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===$.ZodBranded&&e.keyType._def.type._def.typeName===$.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=w0(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Lde(e,t){return t.mapStrategy===`record`?N0(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[I0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||C0(t),I0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||C0(t)],minItems:2,maxItems:2}}}function Rde(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 zde(e){return e.target===`openAi`?void 0:{not:C0({...e,currentPath:[...e.currentPath,`not`]})}}function Bde(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const P0={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Vde(e,t){if(t.target===`openApi3`)return F0(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in P0&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=P0[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 F0(e,t)}const F0=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>I0(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 Hde(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:P0[e.innerType._def.typeName],nullable:!0}:{type:[P0[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=I0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=I0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Ude(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`,b0(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?x0(n,`minimum`,r.value,r.message,t):x0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),x0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?x0(n,`maximum`,r.value,r.message,t):x0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),x0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:x0(n,`multipleOf`,r.value,r.message,t);break}return n}function Wde(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=Kde(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=I0(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=Gde(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Gde(e,t){if(e.catchall._def.typeName!==`ZodNever`)return I0(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 Kde(e){try{return e.isOptional()}catch{return!0}}const qde=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return I0(e.innerType._def,t);let n=I0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:C0(t)},n]}:C0(t)},Jde=(e,t)=>{if(t.pipeStrategy===`input`)return I0(e.in._def,t);if(t.pipeStrategy===`output`)return I0(e.out._def,t);let n=I0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,I0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Yde(e,t){return I0(e.type._def,t)}function Xde(e,t){let n={type:`array`,uniqueItems:!0,items:I0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&x0(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&x0(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Zde(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>I0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:I0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>I0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Qde(e){return{not:C0(e)}}function $de(e){return C0(e)}const efe=(e,t)=>I0(e.innerType._def,t),tfe=(e,t,n)=>{switch(t){case $.ZodString:return O0(e,n);case $.ZodNumber:return Ude(e,n);case $.ZodObject:return Wde(e,n);case $.ZodBigInt:return Tde(e,n);case $.ZodBoolean:return Ede();case $.ZodDate:return T0(e,n);case $.ZodUndefined:return Qde(n);case $.ZodNull:return Bde(n);case $.ZodArray:return wde(e,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return Vde(e,n);case $.ZodIntersection:return Nde(e,n);case $.ZodTuple:return Zde(e,n);case $.ZodRecord:return N0(e,n);case $.ZodLiteral:return Pde(e,n);case $.ZodEnum:return jde(e);case $.ZodNativeEnum:return Rde(e);case $.ZodNullable:return Hde(e,n);case $.ZodOptional:return qde(e,n);case $.ZodMap:return Lde(e,n);case $.ZodSet:return Xde(e,n);case $.ZodLazy:return()=>e.getter()._def;case $.ZodPromise:return Yde(e,n);case $.ZodNaN:case $.ZodNever:return zde(n);case $.ZodEffects:return Ade(e,n);case $.ZodAny:return C0(n);case $.ZodUnknown:return $de(n);case $.ZodDefault:return kde(e,n);case $.ZodBranded:return w0(e,n);case $.ZodReadonly:return efe(e,n);case $.ZodCatch:return Dde(e,n);case $.ZodPipeline:return Jde(e,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(e=>void 0)(t)}};function I0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==xde)return i}if(r&&!n){let e=nfe(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=tfe(e,e.typeName,t),o=typeof a==`function`?I0(a(),t):a;if(o&&rfe(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const nfe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:S0(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`),C0(t)):t.$refStrategy===`seen`?C0(t):void 0}},rfe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),ife=(e,t)=>{let n=Cde(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:I0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??C0(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=I0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??C0(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 afe(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function L0(e,t){return H$(e)?De(e,{target:afe(t?.target),io:t?.pipeStrategy??`input`}):ife(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function R0(e){let t=K$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Z$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function z0(e,t){let n=W$(e,t);if(!n.success)throw n.error;return n.data}var ofe=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(S1,e=>{this._oncancel(e)}),this.setNotificationHandler(A1,e=>{this._onprogress(e)}),this.setRequestHandler(k1,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(I1,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new _0(_1.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(R1,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 _0(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 _0(_1.InvalidParams,`Task not found: ${r}`);if(!v0(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(v0(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[e1]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(z1,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 _0(_1.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(V1,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new _0(_1.InvalidParams,`Task not found: ${e.params.taskId}`);if(v0(n.status))throw new _0(_1.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 _0(_1.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof _0?e:new _0(_1.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),_0.fromError(_1.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),g1(e)||y1(e)?this._onresponse(e):p1(e)?this._onrequest(e,t):rue(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=_0.fromError(_1.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?.[e1]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:_1.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=nue(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 _0(_1.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:_1.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),g1(e)?n(e):n(new _0(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(g1(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),g1(e)?r(e):r(_0.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 _0?e:new _0(_1.InternalError,String(e))}}return}let i;try{let r=await this.request(e,P1,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new _0(_1.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},v0(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new _0(_1.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new _0(_1.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 _0?e:new _0(_1.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||{},[e1]: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 _0?e:new _0(_1.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=W$(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(_0.fromError(_1.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},L1,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},B1,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},vue,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||{},[e1]: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||{},[e1]: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||{},[e1]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=R0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=z0(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=R0(e);this._notificationHandlers.set(n,n=>{let r=z0(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`&&p1(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new _0(_1.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 _0(_1.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new _0(_1.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 _0(_1.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=F1.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),v0(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 _0(_1.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(v0(a.status))throw new _0(_1.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=F1.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),v0(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function B0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sfe(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];B0(a)&&B0(i)?n[r]={...a,...i}:n[r]=i}return n}var cfe=t(en(),1),lfe=t(Mi(),1);function ufe(){let e=new cfe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,lfe.default)(e),e}var dfe=class{constructor(e){this._ajv=e??ufe()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},ffe=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},f0,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},m0,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function pfe(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function mfe(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var hfe=class extends ofe{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(l0.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new dfe,this.setRequestHandler(E1,e=>this._oninitialize(e)),this.setNotificationHandler(O1,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(u0,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=l0.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new ffe(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=sfe(this._capabilities,e)}setRequestHandler(e,t){let n=K$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(H$(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=W$(c0,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new _0(_1.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=W$(P1,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new _0(_1.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=W$(s0,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new _0(_1.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){mfe(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&pfe(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:$$.includes(t)?t:Q$,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},x1)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},p0,t):this.request({method:`sampling/createMessage`,params:e},f0,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},m0,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},m0,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new _0(_1.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof _0?e:new _0(_1.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},g0,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const V0=Symbol.for(`mcp.completable`);function H0(e){return!!e&&typeof e==`object`&&V0 in e}function gfe(e){return e[V0]?.complete}var _fe;(function(e){e.Completable=`McpCompletable`})(_fe||={});const vfe=/^[A-Za-z0-9._-]{1,128}$/;function yfe(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!vfe.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function bfe(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function U0(e){let t=yfe(e);return bfe(e,t.warnings),t.isValid}var xfe=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},W0=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new hfe(e,t)}get experimental(){return this._experimental||={tasks:new xfe(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Y0(o0)),this.server.assertCanSetRequestHandler(Y0(c0)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(o0,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=q$(t.inputSchema);return e?L0(e,{strictUnions:!0,pipeStrategy:`input`}):Sfe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=q$(t.outputSchema);e&&(n.outputSchema=L0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(c0,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new _0(_1.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new _0(_1.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new _0(_1.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new _0(_1.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof _0&&e.code===_1.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await G$(q$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=J$(`error`in r?r.error:`Unknown error`);throw new _0(_1.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new _0(_1.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await G$(q$(e.outputSchema),t.structuredContent);if(!r.success){let e=J$(`error`in r?r.error:`Unknown error`);throw new _0(_1.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new _0(_1.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Y0(h0)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(h0,async e=>{switch(e.params.ref.type){case`ref/prompt`:return mde(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return hde(e),this.handleResourceCompletion(e,e.params.ref);default:throw new _0(_1.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new _0(_1.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new _0(_1.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Z0;let r=K$(n.argsSchema)?.[e.params.argument.name];if(!H0(r))return Z0;let i=gfe(r);return i?X0(await i(e.params.argument.value,e.params.context)):Z0}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Z0;throw new _0(_1.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?X0(await r(e.params.argument.value,e.params.context)):Z0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Y0(Y1)),this.server.assertCanSetRequestHandler(Y0(X1)),this.server.assertCanSetRequestHandler(Y0(Q1)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Y1,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(X1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Q1,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new _0(_1.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new _0(_1.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Y0($1)),this.server.assertCanSetRequestHandler(Y0(e0)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($1,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Cfe(t.argsSchema):void 0}))})),this.server.setRequestHandler(e0,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new _0(_1.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new _0(_1.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await G$(q$(n.argsSchema),e.params.arguments);if(!r.success){let t=J$(`error`in r?r.error:`Unknown error`);throw new _0(_1.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:U$(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=U$(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>H0(e instanceof ce?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){U0(e);let l={title:t,description:n,inputSchema:J0(r),outputSchema:J0(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&U0(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=U$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=U$(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(q0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!q0(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const Sfe={type:`object`,properties:{}};function G0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function K0(e){return`_def`in e||`_zod`in e||G0(e)}function q0(e){return typeof e!=`object`||!e||K0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(G0)}function J0(e){if(e){if(q0(e))return U$(e);if(!K0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Cfe(e){let t=K$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Y$(t),required:!X$(t)})):[]}function Y0(e){let t=K$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Z$(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function X0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Z0={completion:{values:[],hasMore:!1}};var Q0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},wfe=e=>e instanceof Q0?e:new Q0(e.message,{cause:e}),Tfe=global.Request,$0=class extends Tfe{constructor(e,t){typeof e==`object`&&t2 in e&&(e=e[t2]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Efe=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},e2=Symbol(`wrapBodyStream`),Dfe=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new $0(t,a);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[e2]){let e;a.body=new ReadableStream({async pull(t){try{e||=Eu.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Eu.toWeb(r);return new $0(t,a)},t2=Symbol(`getRequestCache`),n2=Symbol(`requestCache`),r2=Symbol(`incomingKey`),i2=Symbol(`urlKey`),Ofe=Symbol(`headersKey`),a2=Symbol(`abortControllerKey`),o2={get method(){return this[r2].method||`GET`},get url(){return this[i2]},get headers(){return this[Ofe]||=Efe(this[r2])},[Symbol(`getAbortController`)](){return this[t2](),this[a2]},[t2](){return this[a2]||=new AbortController,this[n2]||=Dfe(this.method,this[i2],this.headers,this[r2],this[a2])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(o2,e,{get(){return this[t2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(o2,e,{value:function(){return this[t2]()[e]()}})}),Object.defineProperty(o2,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[n2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(o2,$0.prototype);var kfe=(e,t)=>{let n=Object.create(o2);n[r2]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof Bu)throw new Q0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[i2]=new URL(r).href}catch(e){throw new Q0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof Bu?e.authority:e.headers.host)||t;if(!i)throw new Q0(`Missing host header`);let a;if(e instanceof Bu){if(a=e.scheme,!(a===`http`||a===`https`))throw new Q0(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;let o=new URL(`${a}://${i}${r}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,``))throw new Q0(`Invalid host header`);return n[i2]=o.href,n},s2=Symbol(`responseCache`),c2=Symbol(`getResponseCache`),l2=Symbol(`cache`),u2=global.Response,d2=class e{#e;#t;[c2](){return delete this[l2],this[s2]||=new u2(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[s2];if(e){this.#t=e,this[c2]();return}else this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[l2]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[l2];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[c2]().headers}get status(){return this[l2]?.[0]??this[c2]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(d2.prototype,e,{get(){return this[c2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(d2.prototype,e,{value:function(){return this[c2]()[e]()}})}),Object.defineProperty(d2.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[s2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(d2,u2),Object.setPrototypeOf(d2.prototype,u2.prototype);async function Afe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function f2(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function jfe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:f2(e.getReader(),t)}var p2=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Mfe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Tu);var m2=Symbol(`outgoingEnded`),h2=Symbol(`incomingDraining`),Nfe=500,Pfe=64*1024*1024,g2=e=>{let t=e;if(e.destroyed||t[h2])return;if(t[h2]=!0,e instanceof Bu){try{e.stream?.close?.(hte.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(a),e.off(`data`,o),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},a=setTimeout(i,Nfe);a.unref?.();let o=e=>{n+=e.length,n>Pfe&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},Ffe=()=>new Response(null,{status:400}),_2=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),v2=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},y2=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},b2=async(e,t)=>{let[n,r,i]=e[l2],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=p2(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=p2(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(y2(t),await jfe(r,t)?.catch(e=>v2(e,t))),t[m2]?.()},Ife=e=>typeof e.then==`function`,Lfe=async(e,t,n={})=>{if(Ife(e))if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(_2);if(l2 in e)return b2(e,t);let r=p2(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Afe(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&y2(t),await f2(n,t,o))}else r[Mfe]||(t.writeHead(e.status,r),t.end());t[m2]?.()},x2=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==$0&&(Object.defineProperty(global,`Request`,{value:$0}),Object.defineProperty(global,`Response`,{value:d2})),async(r,i)=>{let a,o;try{o=kfe(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[e2]=!0,r.on(`end`,()=>{s=!0}),r instanceof Bu&&(i[m2]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{g2(r)})})}),i.on(`finish`,()=>{s||g2(r)})),i.on(`close`,()=>{o[a2]&&(r.errored?o[a2].abort(r.errored.toString()):i.writableFinished||o[a2].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{g2(r)})})}),a=e(o,{incoming:r,outgoing:i}),l2 in a)return b2(a,i)}catch(e){if(a)return v2(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:wfe(e)),!a)return}else a=o?_2(e):Ffe()}try{return await Lfe(a,i,t)}catch(e){return v2(e,i)}}},Rfe=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:i,id:null}),{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e)){this.onerror?.(Error(`Failed replay events`));try{i.close()}catch{}}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
|
|
1218
1218
|
`;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>b1.parse(e)):[b1.parse(a)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(D1);if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(p1)){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>D1(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)p1(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)p1(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;p1(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!$$.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${$$.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${$$.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((g1(e)||y1(e))&&(n=e.id),n===void 0){if(g1(e)||y1(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(g1(e)||y1(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},zfe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Rfe(e),this._requestListener=x2(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,n){let r=e.auth;await x2(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};const S2=`x-ok-connection-id`;function C2(e,t){let n=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return n?n.slice(0,128):t}function w2(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!Bfe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=g(i.error);throw new _0(_1.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function Bfe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const T2=2e3,E2=2e3,Vfe=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function D2(e){return Vfe.some(t=>t.test(e))}function Hfe(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return Dl(e)?e:null}catch{return null}}function Ufe(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&Dl(a)?a:null}function Wfe(e){let t=[];for(let n of e.split(`
|
|
@@ -2025,6 +2025,6 @@ native-divergence-injected
|
|
|
2025
2025
|
`,`utf-8`),o&&ee!==void 0){let r=null;try{H(E)&&(r=U(E,`utf-8`))}catch(e){r=null,j7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&si(r)!==si(ee)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:ee.length,candidateBytes:S.length})),ve(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=QS(e);if(t.length===0)return;o?.record({event:Qx,docName:i,writerId:BS.id,direction:`b`,site:A,lostLen:t.reduce((e,t)=>e+t.length,0),digest:Hn(t.join(`
|
|
2026
2026
|
`))})}catch(e){j7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},AH)}catch(e){throw t.recordStoreFailure(i,P7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(tie(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let D=`${E}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===i){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${i}`);throw e.code=`ENOSPC`,e}await Ro(D,S,`utf-8`),await ns(D,E),$H(E,tU(S)),t.clearStoreFailure(i),oie();try{d?.(i,f,S,ee??null)}catch(e){j7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{Uo(D)}catch{}throw C.delete(i),t.recordStoreFailure(i,P7(e)),j7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}j7.info({filePath:E,bytes:S.length},`[persistence] Wrote ${E} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){j7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Ao({"persistence.bytes":S.length}),k()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),P?.record((Date.now()-o)/1e3)})}function we({document:e,documentName:n,lastTransactionOrigin:r}){ae.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function Te(e=`within-branch`){return D?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,D):(D=(async()=>{let n=e;for(;;){let e=[...ae.entries()];if(ae.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await Ce({document:r.document,documentName:n,lastTransactionOrigin:r.lastTransactionOrigin})}catch(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`,r=``;try{r=String(e?.message??``)}catch{r=``}let i=Hn(r),a;try{a=_Se(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:Hn(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}nae(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),j7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,ae.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{D=null}),D)}let F={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),fC(i))return;if(pC(i)){Fxe(n,i,h);return}if(mC(i)){AK(n,i,_);return}if(hC(i)||gC(i)){fSe(n,i,v);return}Se();let o=Date.now();return Lo(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{j7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=Dj(i,r);if(!H(a))return;let o=a;try{let e=W(a);if(!Oj(e,r)){j7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(Is(e)===`ELOOP`){j7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=$l(o).size;if(s>524288)throw j7.warn({documentName:i,fileSize:s,limit:Vt},`[persistence] Document exceeds open byte limit; refusing to load`),new hSe(i,s);let c=U(a,`utf-8`),l=n.getXmlFragment(`default`);j7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{jH(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(ar,crypto.randomUUID())},AH),j7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{j7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):j7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{N?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!fC(n)){if(pC(n)){let t=await Lxe(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){j7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(mC(n)){if(await NK(e,n,r,_)===`persisted`){let e=M7(r,c);if(e&&e.id!==HS.id&&!e.id.startsWith(`agent-`)){let t=SK(n);t&&(tF(t.docKey,e.id,e.name,e.id,t.subject),k())}}return}if(hC(n)||gC(n)){await k7(e,n,r,v);return}if(t.isBatchInProgress()){we({document:e,documentName:n,lastTransactionOrigin:r});return}return Ce({document:e,documentName:n,lastTransactionOrigin:r})}}};async function Ee(){ie&&await ie}async function De(){if(ie){await ie;return}aF()!==0&&(ie=O().finally(()=>{ie=null,E&&(E=!1,k())}),await ie)}function Oe(){return{branchDeferred:ae.size,quiescenceDeferred:C.size}}async function ke(e,n){if(!yC(n)){if(t.isBatchInProgress()){we({document:e,documentName:n,lastTransactionOrigin:null});return}return Ce({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:F,durabilityState:t,flushDeferredStores:Te,flushPendingGitCommit:ce,flushContributors:De,waitForPendingCommits:Ee,getQueueDepths:Oe,forceStore:ke,configPersistenceCtx:h,managedArtifactCtx:_}}const I7=L(`persistence-staleness`);var L7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function ySe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,{getBase:i,isBatchActive:a,peekInFlight:o}=e,s=e.msSinceLastUserTx??xw,c=new Map,l=!1,u=null;function d(e){return N7(e)}function f(e){return e===void 0?void 0:si(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Qa(r,n):!0}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),yC(n)||MC(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S,y,b)){c.delete(n);continue}m++;let C=r(),w=s(v,C);if(w!==null&&w<t)continue;let T=c.get(n);if(T&&T.fingerprint===x&&(T.declined||C-T.atMs<t))continue;let ee=T?.fingerprint!==x;ee&&bie();let te=!ee&&T?T.firstDetectedAtMs:C,ne=C-te,re=null,ie=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(re=`disk-file-never-loaded`):t===null?re=`disk-file-missing`:si(t)!==S&&(re=`disk-diverged-from-base`)}catch(e){e instanceof L7?(re=`disk-read-refused`,I7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(re=`disk-read-failed`,ie=!0,I7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(re!==null){g++,Sie(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!ie}),I7.warn({docName:n,ageMs:w,staleForMs:ne,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:re},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}I7.warn({docName:n,ageMs:w,staleForMs:ne,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:te,declined:!1}),xie(),h++;try{await e.forceStore(v,n)}catch(e){I7.error({err:e,docName:n,staleForMs:ne},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let E=v.getText(`source`).toString(),D=i(n),ae=d(E);p(ae,f(D),E,D)&&ae===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!0}),I7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?I7.info(v,`[persistence-staleness] sweep complete`):I7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{I7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function bSe(e){try{let t=gs({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function R7(e){let t=rN(e),n=V(t,`principal.json`),{name:r,email:i}=await bSe(e);if(H(n)){let e;try{e=JSON.parse(U(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Cu()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?Gh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?Gh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return tu(n,JSON.stringify(s,null,2),`utf-8`),s}Ul(t,{recursive:!0});let a=`principal-${Cu()}`,o=a.slice(10,18),s={id:a,display_name:r?Gh(r):`Local User`,display_email:i?Gh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return tu(n,JSON.stringify(s,null,2),`utf-8`),s}var xSe=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};function z7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function SSe(e,t){try{if(_C(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(z7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw vS(),Ao({"auth.reason":`doc-deleted`}),new BZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){oae(),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 _S(),Ao({"auth.reason":`rename-redirect`}),new BZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw z7(t,i)?(t.recentlyRemovedDocs.delete(i),_S(),Ao({"auth.reason":`rename-redirect`}),new BZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(vS(),Ao({"auth.reason":`doc-deleted`}),new BZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof BZ)throw t;aae(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const B7=L(`removed-docs-journal`);function V7(e){return z(rN(e),`removed-docs.json`)}function CSe(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 wSe(e){let t=V7(e);if(!H(t))return[];try{let e=JSON.parse(U(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return B7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!CSe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return B7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function H7(e,t){let n=V7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};Jo(R(n),{recursive:!0});let i=`${n}.tmp`;rs(i,JSON.stringify(r),`utf-8`),Vo(i,n)}const U7=L(`server-observers`);function W7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(fC(r)||pC(r)||hC(r)||gC(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=NT({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,deferGuardEnabled:e.deferGuardEnabled,lossDetectorEnabled:e.lossDetectorEnabled,fixedPointBackstopEnabled:e.fixedPointBackstopEnabled,preDrainEnabled:e.preDrainEnabled,lossRing:e.lossRing});return t.set(r,n),!0}catch(e){return U7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),mS(`a`),mS(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(U7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){U7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const G7=`state.json`;function K7(e){return e.lockDir,H(e.shadowRepoDir)?`adopt`:`fresh`}function q7(e){return V(e,G7)}function TSe(e,t){return e===t||e===0&&t===1}var J7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function ESe(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function Y7(e){let t=q7(e);if(!H(t))return{status:`absent`};let n;try{n=U(t,`utf-8`)}catch(e){throw new J7({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new J7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!ESe(r))throw new J7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function X7(e,t){let n=q7(e);Ul(R(n),{recursive:!0}),tu(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function Z7(e){let t=L(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Os,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=q7(e.lockDir),s=Y7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!TSe(c.stateSchemaVersion,n))throw new J7({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return X7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(K7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return X7(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return X7(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}function DSe(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 OSe(e){return e.git?.toString()??e.message??``}function Q7(e,t){return t.some(t=>t.test(e))}const kSe={"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`},ASe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],$7=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],jSe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],MSe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],NSe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PSe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],FSe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],ISe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],LSe=[/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],RSe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],zSe=[/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],BSe=[/\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],VSe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function e9(e){let t=HSe(e);return{...t,userFacingCode:DSe(t.class,t.subclass)}}function HSe(e){let t=e instanceof Error?e:Error(String(e)),n=OSe(t),r=`${t.message}\n${n}`.toLowerCase();if(Q7(r,ISe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(Q7(r,LSe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(Q7(r,RSe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=ga(t);return i.kind===`auth`?i.subclass===`403`&&Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:kSe[i.subclass],rawStderr:n}:Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Q7(r,ASe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Q7(r,jSe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Q7(r,MSe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Q7(r,NSe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Q7(r,FSe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Q7(r,PSe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Q7(r,VSe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Q7(r,BSe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Q7(r,zSe)?/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 USe(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const t9=L(`github-permissions`);function WSe(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function GSe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function KSe(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 qSe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return t9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=KSe(t);return n===null?(t9.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return t9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function JSe(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){t9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function YSe(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 JSe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(t9.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(t9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${WSe(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;t9.info({host:r,tokenSource:u,tokenLen:l===void 0?0:l.length},`[permissions] probe starting`);let f=new AbortController,p=setTimeout(()=>f.abort(),c);try{let e=await s(d,{signal:f.signal,headers:GSe(l)}),t=await qSe(e,l!==void 0);return t9.info({host:r,tokenSource:u,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return f.signal.aborted?(t9.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(t9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function XSe(e){let t=performance.now(),n=await YSe(e);return eCe(n,performance.now()-t),n}function ZSe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let n9=null;function QSe(){return n9||=os().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),n9}let r9=null;function $Se(){return r9||=os().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),r9}function eCe(e,t){let n=ZSe(e);QSe().add(1,n),$Se().record(t,{outcome:n.outcome})}function i9(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}function tCe(e,t){return t===`anonymous`?Math.max(180,e):e}const a9=L(`sync-engine`),o9=/^[0-9a-f]{40}$/i,nCe=Pu(yl);function rCe(e){let{exitCode:t,stderr:n}=e,r=n??``;return t===128||/^fatal:/m.test(r)&&/not possible to fast-forward/i.test(r)?`divergence`:/^error:/m.test(r)&&/would be overwritten by merge/i.test(r)?`overlay-overlap`:`unknown`}function iCe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function s9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function c9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function l9(e){let t=Wu(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 aCe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const u9=12e4;var oCe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;mode;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.detectGh=e.detectGh,this.ghTokenSource=USe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??XSe,this.statePath=V(rN(this.projectDir),`sync-state.json`),this.conflictStore=new WZ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return BR(this.projectDir)}gitHandle(e){return ys(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){a9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),a9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){a9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=td(this.projectDir),n=t?z(t,`MERGE_HEAD`):null,r=n!==null&&H(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){a9.warn({count:i().length},`[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state`);for(let e of i())this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count()}else if(i().length>0&&r)try{let e=this.gitHandle(),t=new Set(await aS(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of i())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&a9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){a9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){a9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(i().length>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),a9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=this.conflictStore.list().filter(e=>e.variant===`working-tree`);a.length>0&&await this.notifyContentConflictsDetected(a.map(e=>e.file)),this.mode===`follow`&&await this.refreshAuthTier();let o=i9(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=i9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),a9.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,a9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){a9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await Nu(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||l9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||l9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){a9.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){a9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await _s(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,a9.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,a9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?a9.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):a9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(await this.runPushCycle(),await this.runPullCycle())}async pullOnce(){let e=this.mode,t=await this.runOneShotPull();return a9.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||l9(this.projectDir))return this.recordPullOutcome(`refused`);let e=this.mode,t=this.state,n=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,e===`off`?(this.pausedReason=n,this.transitionTo(t)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?VR(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 $U(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=zR(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,s9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,a9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){a9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=iCe(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.mode===`full`?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,a9.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),a=!0,a9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!s9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,a9.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!H(z(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return a9.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){let e=this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(e.length===0)return;let t=this.conflictCount,n=td(this.projectDir),r=n?z(n,`MERGE_HEAD`):null;if(r!==null&&H(r))try{let n=this.gitHandle(),r=new Set(await aS(n.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let t of e)r.has(t.file)||this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<t&&a9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){a9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{a9.info({cleared:e.length},`[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts`);for(let t of e)this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count()}this.conflictCount!==t&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&(a9.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e])),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{a9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??c9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{a9.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){let e=this.syncGhTokenHost();if(this.ghTokenSource.get(e)!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(e))?.token)return`authenticated`}catch(e){a9.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?tCe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=aCe(this.consecutiveFailures);return c9(e>0?e/1e3:this.currentPullIntervalSeconds())}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(l9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,a9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.mode!==`full`){let n=await this.doPullCycleB1(e,t);return this.scheduleSaveState(),n}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return`refused`;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}return this.scheduleSaveState(),`succeeded`}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),a9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await aS(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await aS(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=new Map;for(let e of this.conflictStore.list())e.variant===`working-tree`&&i.set(e.file,e);let a;try{a=await this.planOverlapReconciliation(e,t,n,r,i)}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){a9.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...r])}catch(e){return a9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return a9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(a9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(e9(Error(`git merge --ff-only timed out after ${u9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),a9.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return a9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=!0;for(let e of a.upserts)i=this.conflictStore.addConflict(e)&&i;for(let e of a.dissolved)i=this.conflictStore.removeConflict(e)&&i;if(this.conflictCount=this.conflictStore.count(),!i)return a9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(e9(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return a9.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:o},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await nCe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:u9}),{ok:!0}}catch(e){let t=e,n=t.killed===!0||t.signal===`SIGTERM`,r=typeof t.code==`number`?t.code:null,i=typeof t.stderr==`string`?t.stderr:e instanceof Error?e.message:String(e);return{ok:!1,refusal:rCe({exitCode:r,stderr:i}),stderr:i,exitCode:r,timedOut:n}}}async planOverlapReconciliation(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[];for(let p of r){let r=i.get(p),m=r!==void 0;if(!H(z(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),a9.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=U(z(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&a9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=hi(v?await this.gitBlobContent(e,v):``,g,_);if(y.clean){a.push({path:p,bytes:Buffer.from(y.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let b=await this.gitBlobSha(e,`origin/${t}:${p}`);if(b===void 0){a9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({file:p,detectedAt:r?.detectedAt??new Date().toISOString(),variant:`working-tree`,theirsSha:b,baseSha:v}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){for(let{path:t,bytes:n}of e){let e=z(this.projectDir,t);dV(e,this.projectDir),rs(e,n)}for(let e of t){let t=z(this.projectDir,e);dV(t,this.projectDir);try{Uo(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=z(this.projectDir,e),n=Tj(B(this.contentDir,t));return!n.startsWith(`..`)&&eC(n)&&!this.contentFilter.isExcluded(n)}async gitBlobSha(e,t){try{return(await e.git.revparse([t])).trim()}catch{return}}classifyRefReadFailure(e){let t=e instanceof Error?e.message:String(e);return/does not exist in|exists on disk, but not in/i.test(t)?`absent`:`error`}async gitBlobContent(e,t){return e.git.raw([`cat-file`,`blob`,t])}async countStandingOverlay(e){try{return(await aS(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(!this.pushInFlight&&this.mode===`full`&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(l9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=z(cu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await _s(async()=>{let e=this.gitHandle(n);if(l9(this.projectDir)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(e9(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i);if(t.length>0)for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));await this.removePathsFromIndex(e,s);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){a9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}a9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[],d=[];try{let n=await aS(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)??Tj(B(this.contentDir,z(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 $U(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`;xs(e,{GIT_AUTHOR_NAME:h,GIT_AUTHOR_EMAIL:g,GIT_COMMITTER_NAME:h,GIT_COMMITTER_EMAIL:g});let _=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,f])).trim();if(!_||!o9.test(_)){a9.warn({raw:_},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,_,i]),await this.resetRealIndexForPaths(u);let v=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),v=!0}catch{}v?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=_}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=e9(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){a9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}a9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{eu(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=z(cu(),`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 aS(a.git,[`diff-tree`,`--name-only`,`-r`,t,s])}catch{c=n.map(e=>e.projectRelPath).concat(o)}let l=await $U(this.projectDir),u=l?.name??`OpenKnowledge`,d=l?.email??`sync@open-knowledge.local`;xs(a,{GIT_AUTHOR_NAME:u,GIT_AUTHOR_EMAIL:d,GIT_COMMITTER_NAME:u,GIT_COMMITTER_EMAIL:d});let f=(await a.git.raw([`commit-tree`,s,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!f||!o9.test(f)?(a9.warn({raw:f},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,f,t]),await this.resetRealIndexForPaths(c,e),f)}finally{try{eu(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await aS(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return a9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await aS(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return a9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return a9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){a9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=Jl(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=z(n,i.name);if(i.isDirectory()){let e=Tj(B(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=Tj(B(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Tj(B(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return H(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await aS(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=z(this.projectDir,e),r=Tj(B(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 aS(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){a9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=z(this.projectDir,e),i=Tj(B(this.contentDir,t));!i.startsWith(`..`)&&eC(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),a9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){a9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),a9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=td(this.projectDir);t=n===null||!H(z(n,`MERGE_HEAD`))}catch(e){a9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),a9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),a9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict resolved callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),a9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,a9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};tu(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){a9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(H(this.statePath))try{let e=U(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){a9.warn({err:e},`[sync] failed to load sync state`)}}};To();const sCe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function cCe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(fC(e)||pC(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&sCe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Mo(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Eo.with(wo.extract(Eo.active(),r),e)}else e()}catch(e){L(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let d9=!1;function f9(){if(d9)return;let e=vte;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){d9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),d9=!0}catch(e){L(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const lCe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function uCe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(y8).join(` `)} auth git-credential`]}function dCe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Sl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],NF({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return L(`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 L(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
|
|
2027
2027
|
`)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=V(e,r);if(!Oj(a,t))continue;let s=fU(a,t);i.has(s)||H(a)&&i.set(s,o)}return i}function p9(e){f9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=L(`server`),x=new c7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),ee=e=>x.switchReconciledBaseScope(e),te=e=>x.setBatchInProgress(e),ne=()=>x.isBatchInProgress();function ie(){let e=No({absPath:Fo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=le(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function E(){let e=No({absPath:Fo(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=b(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let r=No({absPath:Fo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:re(r.value.autoSync?.default)??`off`,source:`committed-default`}}function D(){let e=No({absPath:Fo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Mn(e):Ze}function ae(){return No({absPath:Fo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function O(){return OF(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function oe(){let e=No({absPath:Fo(`project-local`,n,l),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function k(){return jo({cwd:n,homedirOverride:l,warn:e=>y.debug({message:e},`[config] diagnostics read`)})}function ce(){for(let e of k().diagnostics)e.code===`REMOVED_KEY`&&y.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function ue(e){return`${vF(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function de(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=E();t=n.mode,dt?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=O();ke.applyConfig({enabled:n.enabled,providerFingerprint:ue(n)}),e===`__config__/project`&&Ce?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}as();let fe=Cu(),A=rN(n),pe=new Md({localDir:A,log:L(`acp-registry`)}),j=new Td(A,L(`acp-permissions`));if(Ns(A,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{Z7({lockDir:A,shadowRepoDir:nd(n)})}catch(e){throw Cs(A),e}let me=Aa(),he=(e,t)=>me.resolveEmbed(e,t),ge=(e,n)=>{let r=me.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=V(t,r);if(!Ej(i,V(t)))return null;try{let e=$l(i);return e.isFile()?e.size:null}catch{return null}},_e,M,ve,ye,be,N,P,xe,Se,Ce=null,we=null,Te=null,F=null,Ee=null,De=null,Oe=O(),ke=new Mce({loadEmbedder:e.embedderLoader??(()=>{let t=O();return vce({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:z(rN(n),`embeddings`),enabled:Oe.enabled,providerFingerprint:ue(Oe)}),I=null,Ae=new Set,je=!1,Me=[],Ne,Fe,Ie,Le=new Promise((e,t)=>{Fe=e,Ie=t});function Re(e){Ce?.signal(e)}let ze=null,Be=!1,Ve=()=>{try{H7(n,He.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},He=new xSe(void 0,{onEviction:()=>rae(),onSizeChange:e=>iae(e),onMutate:()=>{!Be||ze!==null||(ze=setTimeout(()=>{ze=null,Ve()},2e3))}});for(let[e,r]of wSe(n))_C(e)||kZ(e)&&([`.md`,`.mdx`].some(n=>{let r=V(t,`${e}${n}`);return Ej(r,V(t))&&H(r)})||He.restore(e,r));Be=!0;let Ue={current:null},We=(e,t)=>{_C(e)||He.setRenamed(e,t)},Ge=e=>{if(!_C(e)){if(He.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}He.setDeleted(e),Ue.current?.deleted(e)}},Ke=e=>{_C(e)||He.delete(e)};try{_e=ZI({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:cV(t),rescanInPlaceSkillDirs:()=>cV(t),onAfterRebuild:()=>{M.refreshContentScope().catch(e=>{L(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),FU(lt).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?L(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):L(`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=>{L(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),M=new kH({projectDir:n,contentDir:t,contentFilter:_e,getGlobalSkillRoots:()=>wK(be.managedArtifactCtx),signalChannel:Re}),ve={current:d},ye=o?lSe({getShadow:()=>ve.current??null,getCurrentBranch:()=>ut?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:td(n)??void 0,isWriterLive:e=>{if(!F&&!xe)return L(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(F?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of xe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,be=F7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:ve,ephemeral:v,contentRoot:f,derivedDocumentIndex:M,configHomedirOverride:l,getCurrentBranch:()=>ut?.getLastKnownBranch()??null,resolveEmbed:he,resolveSize:ge,getPrincipal:()=>I,onAgentCommit:()=>Ce?.signal(`session-activity`),onFlushCommit:()=>ye?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Ce?.emitDiskAck(e,t),!_C(e)&&$j(r,n)&&(Ee?.(),Re(`files`))},onConfigRejected:(e,t)=>Ce?.emitConfigValidationRejected(e,t),onConfigPersisted:de,isRecentlyRemoved:e=>He.has(e),mdManager:e.mdManager,getLossRing:()=>N,durabilityState:x}),P=new Txe({quiet:r,debounce:i,maxDebounce:a,extensions:[be.extension]});let p=P;Me.push(ooe(()=>p.documents.size),soe(()=>be.getQueueDepths()),loe(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),doe(),v||(De=ySe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>be.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=Dj(e,t),r,i;try{r=W(n),i=$l(r).size}catch(t){let n=Is(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new L7(`symlink cycle at content path: ${e}`):t}if(!Oj(r,t))throw new L7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new L7(`document exceeds the open byte limit: ${e}`);try{return U(r,`utf-8`)}catch(e){if(Is(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=P.shouldUnloadDocument.bind(P);P.shouldUnloadDocument=e=>{if(Ae.has(e)||je&&g(e))return!0;let t=e.name;return _C(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Ne=async e=>{Ae.add(e);try{await P.unloadDocument(e)}finally{Ae.delete(e)}},Ce=new bC(P),Te=new gD(P),F=new _D(P),xe=new eE(P);let b=xe;Me.push(uoe(()=>({active:b.liveSessionCount,limit:b.sessionLimit})));let w=f7({derivedDocumentIndex:M,onDocumentSettled:e=>Ue.current?.changed(e)});P.configuration.extensions.push(w),P.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=VZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==fe)throw new BZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${fe}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new BZ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(I&&n.principalId===I.id?o.principalId=I.id:I?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:I.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),P.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!pC(t.documentName)&&!mC(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!pj(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&yj(a,e.remotePublicHost);if(!mj(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=V(t);function ee(e){if(!kZ(e))return null;let t=V(T,lC(e));return Ej(t,T)?t:null}P.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await SSe(e.documentName,{recentlyRemovedDocs:He,resolveFilePath:ee,fileExists:H})}}),P.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=VZ(e.token);Vxe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>P.documents.get(e)})}}),P.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new E5(e.update);if(t.readVarString(),t.readVarUint()===L5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${za} rejected — server-only channel`)}});let te=jZ({hocuspocus:P,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:xe,commentDocHooksRef:Ue,contentDir:t,contentFilter:_e,serverInstanceId:fe,getFileIndex:()=>lt?lt.getFileIndex():new Map,getAttachmentFolderPath:ie,getAllFilesIndex:()=>lt?lt.getAllFilesIndex():new Map,getFileIndexGeneration:()=>lt?.getFileIndexGeneration()??0,mutateFileIndex:e=>lt?.mutateFileIndex(e),getFolderIndex:()=>lt?lt.getFolderIndex():new Map,getAliasMap:()=>lt?lt.getAliasMap():new Map,getFolderAliasIndex:()=>lt?lt.getFolderAliasIndex():new Map,rescanFiles:()=>lt?.rescanFromDisk(),enableTestRoutes:u,shadowRef:ve,flushGitCommit:()=>be.flushPendingGitCommit(),flushContributors:()=>be.flushContributors(),getCurrentBranch:()=>ut?.getLastKnownBranch()??null,getDiskAckSVs:()=>Ce?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:M,signalChannel:Re,agentFocusBroadcaster:Te,agentPresenceBroadcaster:F,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>dt,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:he,getBridgeLossReporter:()=>Se,getPrincipal:()=>I,acpRegistry:pe,loadAcpCustomAgents:()=>Nd(A,L(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Ne,ready:Le,recentlyRemovedDocs:He,serializeDoc:Qe,evictManagedArtifactLkg:e=>{be.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ke,getSemanticSimilarityFloor:()=>O().similarityFloor,getLinterBaseConfig:()=>D(),getLinksValidationSetting:()=>ae(),getLinkPreviewsEnabled:oe,getConfigDiagnostics:k,embeddingsSecretsFile:TF(l),readSemanticProviderConfig:O,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{Ee=e}});P.configuration.extensions.push(te);let ne=No({absPath:Fo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),re=ne.value.bridge.deferGuard.enabled,E=ne.value.bridge.fixedPoint.enabled,se=ne.value.bridge.preDrain.enabled;N=ne.value.lossCapture.enabled?new Kre({projectDir:n,maxBytes:ne.value.lossCapture.maxBytes}):void 0,ne.value.bridge.lossDetector.enabled&&(Se=Lae({shadow:()=>ve.current,ring:N,getBranch:()=>ut?.getLastKnownBranch()??`main`,contentRoot:f??``}),xe.attachBridgeLossReporter(Se)),P.configuration.extensions.push(W7({mdManager:Oo,schema:Do,shadowRef:ve,contentRoot:f,getCurrentBranch:()=>ut?.getLastKnownBranch()??null,resolveEmbed:he,resolveSize:ge,deferGuardEnabled:re,lossDetectorEnabled:ne.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:E,preDrainEnabled:se,lossRing:N})),P.configuration.extensions.push(cCe()),P.configuration.extensions.push(Bxe({getSyncEngine:()=>dt,projectDir:n,contentDir:t}))}catch(e){for(let e of Me.splice(0))e();throw De?.dispose(),De=null,Cs(A),e}let qe=null,Je=new Map,Ye=[];function Xe(e,t){let n=V(e,`rescue`),r=V(n,lC(t));return Ej(r,n)?r:null}function Qe(e){let t=P.documents.get(e);return t?HH(t):null}let $e=(e,t)=>zH(x,P,e,t,he,ge,Se);function et(e){if(!AC(e)||dt?.getConflicts().some(r=>s7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of P.documents){if(_C(n))continue;let r=P.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{jH(r,i,he,n)},AH)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},nt=null,rt=e=>{e&&(nt===null&&(nt=new Set,setImmediate(()=>{let e=nt;if(nt=null,e)try{for(let t of e)tt(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),nt.add(e))};function it(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 JH(e)}}async function at(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await M.recordDiskUpsert(e.docName,e.content),Re(`files`),Ke(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=P.documents.get(t);if(!r){await M.recordDiskUpsert(t,n);return}let i=C(t)??``,a=Qe(t)??i,o=FH({docName:t,base:i,ours:a,theirs:n}),s=tU(i).slice(0,6),c=tU(a).slice(0,6),l=tU(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:et(r),await M.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{$e(t,o.newContent),w(t,o.newContent),oS(),et(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),et(r)}e&&await M.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{$e(t,o.newContent),w(t,n),oS(),et(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),et(r)}e&&await M.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{$e(t,o.newContent),w(t,o.newContent),oS(),sS(),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await M.recordDiskUpsert(t,n);break}case`refused`:{sS();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=P.documents.get(t);if(!n){await M.recordDiskDelete(t),Re(`files`),Ge(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=Qe(t)??``,a=i!==r;if(a&&ve.current){let e=ve.current,n=ut?.getLastKnownBranch()??`main`;queueMicrotask(()=>{qS(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{lS(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await M.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),P.closeConnections(t),await Ne(n),Re(`files`),Ge(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=P.documents.get(t);if(T(t),w(n,r),await M.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),Re(`files`),We(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=P.documents.get(t);if(!n)return;let r=Qe(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:me.add(e.relativePath),Re(`files`),rt(wl(e.relativePath));break;case`asset-delete`:me.remove(e.relativePath),Re(`files`),rt(wl(e.relativePath));break;case`folder-create`:case`folder-delete`:Re(`files`);break;case`file-create`:case`file-update`:case`file-delete`:Re(`files`);break;default:JH(e)}}catch(t){let n=it(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let ot=[];async function st(e){if(ne()){ot.push(e);return}await at(e)}async function ct(){let e=ot.splice(0,ot.length);for(let t of e)await at(t)}let lt=null,ut=null,dt=null,ft=null;async function pt(e){if(P.documents.size===0)return;let t=!1,n=new Promise(e=>{P.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(P.documents.keys());P.closeConnections(),P.flushPendingStores();for(let e of P.documents.values())e.getConnectionsCount()===0&&P.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(P.documents.keys()),i=[],o=[];if(ve.current){for(let e of n)if(!_C(e))try{let t=Qe(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Xe(ve.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:ve.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Ul(R(n),{recursive:!0}),tu(n,t,`utf-8`),lS(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function mt(){return ft||(ft=(async()=>{let e=Date.now(),t=[];je=!0;for(let e of Me.splice(0))e();try{await De?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}De=null;try{Ps(A)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(ze!==null&&(clearTimeout(ze),ze=null),Be)try{H7(n,He.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([Le.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=P.documents.size;ye?.destroy();try{try{try{we&&=(clearTimeout(we),null),ut&&=(await ut.unsubscribe(),null),lt&&=(await lt.unsubscribe(),null);for(let{docName:e,cleanup:t}of Ye)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Ye.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Ce?.destroy(),F?.destroy(),qe&&=(await qe.disconnect(),null);for(let[e,t]of Je)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Je.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await xe.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await dw()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await pt(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}M.close();let e;try{await Promise.race([(async()=>{await be.flushPendingGitCommit(),await be.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{dt&&=(await dt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ve.current){try{let e=(await gs({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&tu(V(ve.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{vae(ve.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Cs(A,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await is()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),ft)}let ht=[];async function gt(){try{I=await R7(n),y.info({principalId:I.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ve.current)try{ve.current=await NS(n),y.info({gitDir:ve.current.gitDir},`[server] history repo initialized at ${ve.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),ht.push(`shadow-repo`)}if(ve.current){let e=null;try{e=mq(ve.current.gitDir),Lq(ve.current.gitDir,e),yq(ve.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([Rq(ve.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ye?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ve.current)try{await jS(ve.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ve.current=await NS(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),ve.current=void 0,ht.includes(`shadow-repo`)||ht.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(ve.current)try{let e=V(ve.current.gitDir,`last-known-head`),t=null;try{t=U(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await gs({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await gs({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await WS(ve.current,f??``,t,r,e),cS()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{tu(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=eq(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),ht.push(`managed-rename-recovery`)}try{let e=OV(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),ht.push(`upload-tempfile-sweep`)}try{qe=await P.openDirectConnection(za),Ce?.emitServerInfo(fe,S())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),ht.push(`cc1-push`)}let r=v?[]:Sn;for(let e of r)try{let t=await P.openDirectConnection(e);Je.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),ht.push(`config-doc:${e}`)}let i=new Map([[$r,Fo(`project`,n)],[Ga,Fo(`project-local`,n)],[da,Fo(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await X5(t,t=>{let n=P.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=o7(n??null,e,t,be.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),de(e)});Ye.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),ht.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=kK(e,be.managedArtifactCtx);if(!n)return;let r=PK(P.documents.get(n)??null,n,t,be.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Re(`files`),oi(n)&&M.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=kK(e,be.managedArtifactCtx);Re(`files`),t&&oi(t)&&M.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=wK(be.managedArtifactCtx),r=await w7(n,e,void 0,t);Ye.push({docName:`__skill-files__`,cleanup:r}),y.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),ht.push(`managed-artifact-watcher:skills`)}try{let e=V(xK(be.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await X5(e,()=>{Re(`files`)});Ye.push({docName:`__skill-state__`,cleanup:t}),y.info({path:e},`[skill-state-watcher] started`)}catch(e){y.warn({err:e},`[skill-state-watcher] failed to start`),ht.push(`skill-state-watcher`)}try{let t=new Set([``]);try{for(let e of cP(n).templates)t.add(e.source_folder)}catch(e){y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?V(n,e,`.ok`,`templates`):V(n,`.ok`,`templates`)),i=await w7(r,e,dSe);Ye.push({docName:`__template-files__`,cleanup:i}),y.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),ht.push(`managed-artifact-watcher:templates`)}}try{let e=V(t,`.okignore`),r=V(n,`.gitignore`),i=null;try{let e=Sl(`git`,[`rev-parse`,`--git-common-dir`],NF({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=z(V(n,e.stdout.trim()),`info`,`exclude`);H(R(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await jxe(a,(t,r)=>{(async()=>{if(t===e)try{let e=o7(P.documents.get(`__config__/okignore`)??null,Pe,r,be.configPersistenceCtx);o.info({docName:Pe,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:B(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await _e.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:B(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Ce?.signal(`files`);else{let e=B(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Ce?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:B(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Ye.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),ht.push(`ignore-files-watcher`)}let a=d7(n).branch??`main`;ee(a);let o=M.beginStartup(a),s=!1,c=performance.now();try{await Lo(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&&ht.push(`backlink-index`);let i=0;for(let t of e)_C(t)||He.peek(t)?.kind!==`renamed`&&(He.setDeleted(t),i++);i>0&&y.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,u=_e?cV(t):new Set,d=e=>{e.some(e=>c.test(B(t,e).split(Al).join(`/`)))&&(we&&clearTimeout(we),we=setTimeout(()=>{we=null;try{GJ(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),Ce?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=cV(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,_e.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),Ce?.signal(`files`)):y.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>y.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){y.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};lt=await Lo(`ok.boot.seed-walk`,void 0,async()=>PU(t,st,_e,{onRawBatch:d})),GJ(n,t).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=l??au();GJ(e,e,aV(e)).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] global copy re-sync failed`))}mH(`seedWalkMs`,Math.round(performance.now()-a));{let e=V(t),n=0;for(let[t]of He.entries()){if(!kZ(t))continue;let r=V(e,`${t}${sC(t)}`);Ej(r,e)&&H(r)&&(He.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await M.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&ht.push(`tag-index`);let p=0;try{_===void 0?await PZ({contentDir:t,contentFilter:_e,basenameIndex:me,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):NZ({contentDir:t,basenameIndex:me,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(y.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),ht.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),ht.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),ht.push(`file-watcher`),!s){let e=await M.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&ht.push(`tag-index`)}}finally{mH(`indexesMs`,Math.round(performance.now()-c)),lt&&hH(`fileCount`,lt.getFileIndex().size)}try{ut=await Kxe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),eie(),P.flushPendingStores(),await be.flushPendingGitCommit(),te(!0),ve.current){let e=S(),t=d7(n).branch??e,r=[];for(let[e,t]of P.documents){if(_C(e))continue;let n=null;if(t.transact(()=>{n=Qe(e)},lCe),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await Oae(ve.current,e,HS.id,r,t);n&&(rie(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=ot.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(te(!1),await ct(),e.headMoved&&e.newHead){let r=dCe(n,V(t),e.oldHead,e.newHead);if(r.size>0){Gse(r.keys());for(let[e,t]of r)tF(e,yte(t.email),t.name,t.email,_d(e));await be.flushContributors()}}if(await be.flushDeferredStores(`within-branch`),dt!==null)try{await dt.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{nie(),ot.splice(0,ot.length);let n=!1,r;try{ee(i),r=await M.beginBranchSwitch(i),_e.rebuildDirCount();try{let e=0;me.clear(),await PZ({contentDir:t,contentFilter:_e,basenameIndex:me,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),ht.includes(`basename-index-partial`)||ht.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of P.documents)if(!_C(e))try{let r=Dj(e,t);if(!H(r)){let t=C(e)??``,r=Qe(e)??``;if(r!==t&&ve.current){let t=ve.current;queueMicrotask(()=>{qS(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{lS(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=U(r,`utf-8`);$e(e,a),w(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:P.documents.size},`[branch-switch] loaded branch ${i} (${P.documents.size} docs)`);try{await M.settleBranchFromDisk(r)}catch(e){M.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(ve.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of P.documents)if(!_C(t))try{let n=await Aae(ve.current,i,HS.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=FH({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:$e(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:$e(t,a.newContent),w(t,a.newContent),sS(),e++;{let e=P.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&ve.current)try{let t=jS(ve.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await DS(ve.current).withMutator(async()=>{for(let e of n.split(`
|
|
2028
|
-
`))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}te(!1),await be.flushDeferredStores(`discard-stale`),n=!0,Ce?.emitBranchSwitched(i)}finally{M.abortBranchSwitch(r),n||(te(!1),await be.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ve.current&&r>0){let t=f??`.`;try{let n=await WS(ve.current,t,e.oldHead,e.newHead,i);cS(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),ht.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Tj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=nC(e),a=P.documents.get(i);if(!a)continue;let o=Qe(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=Tj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=P.documents.get(nC(e));i&&et(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=uCe(m),h=E();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{dt=new oCe({projectDir:n,contentDir:t,contentFilter:_e,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:Ce,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||be.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ve.current;n&&await KS(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ve.current;n&&await KS(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await qo({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:se(t.error),configPath:Fo(`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 dt.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),dt=null}Re(`files`),M.announceReadyViews();let g=pH();g!==void 0&&mH(`readyMs`,g),ce()}return gt().then(Fe,e=>{M.close(),Ie(e)}),{hocuspocus:P,durabilityState:x,sessionManager:xe,cc1Broadcaster:Ce,agentFocusBroadcaster:Te,agentPresenceBroadcaster:F,maintenanceCoordinator:ye,contentFilter:_e,basenameIndex:me,serverInstanceId:fe,destroy:mt,ready:Le,degraded:ht,lockDir:A,get syncEngine(){return dt},getLinkPreviewsEnabled:oe,resolveEmbed:he,acpRegistry:pe,acpPermissions:j}}function m9(e){return e/1048576}function fCe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:m9(e.rss),heapTotalMb:m9(e.heapTotal),heapUsedMb:m9(e.heapUsed),externalMb:m9(e.external),arrayBuffersMb:m9(e.arrayBuffers)}}}let h9=null,g9=null,_9=null;const v9=1e6;let y9=null,b9=null;Io(()=>{h9=null,g9=null,_9=null,y9?.disable(),y9=null,b9=null});function pCe(){if(h9)return;let e=os().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}=fCe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),h9=e}function mCe(){if(!g9){let e=os().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!y9){y9=Ou({resolution:20}),y9.enable();return}e.observe(y9.percentile(50)/v9,{stat:`p50`}),e.observe(y9.percentile(99)/v9,{stat:`p99`}),y9.reset()}),g9=e}if(!_9){let e=os().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=b9;if(b9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),_9=e}}const x9=L(`skill-migrate`);function S9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=UD.indexOf(e.host),r=UD.indexOf(t.host);return(n===-1?UD.length:n)-(r===-1?UD.length:r)||e.host.localeCompare(t.host)})}const hCe=S9(Mt),gCe=S9(Gn);function _Ce(e,t){Jo(R(t),{recursive:!0});try{Vo(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;Zo(e,t,{recursive:!0}),Qo(e,{recursive:!0,force:!0})}}function vCe(e,t,n){let r;try{r=Hl(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return W(e)===t?{kind:`ok-link`}:{kind:`foreign-link`}}catch{return{kind:`foreign-link`}}return r.isDirectory()&&LD(e)?.contentHash===n?{kind:`same-copy`}:{kind:`different`}}function C9(e,t){let n;try{n=W(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!W(V(e,t.dir)).startsWith(n+Al)}catch{return!0}}).map(e=>e.name))}async function w9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??hCe,a={migrated:[],skipped:[]};if(!H(n))return a;let o;try{o=Jl(n)}catch{return a}let s=B(t,n).split(Al).join(`/`),c=new Set;for(let[e,n]of Object.entries(HJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ie.test(e)||uz.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=V(n,e);if(!H(z(o,`SKILL.md`)))continue;let s=LD(o)?.contentHash;if(s===void 0)continue;let l=W(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:vB(t,i),state:vCe(z(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`ok-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind!==`different`&&e.state.kind!==`foreign-link`&&H(V(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`different`||d.state.kind===`foreign-link`){a.skipped.push({name:e,reason:`target-occupied:${d.root}`});continue}d.state.kind===`same-copy`?Qo(o,{recursive:!0,force:!0}):(d.state.kind===`ok-link`&&Qo(d.path,{recursive:!0,force:!0}),_Ce(o,d.path));for(let e of u)e===d||e.state.kind!==`ok-link`||(Qo(e.path,{recursive:!0,force:!0}),Zo(d.path,e.path,{recursive:!0}));await cI(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),x9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),x9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const T9=L(`skill-reconcile`),yCe=uz;function E9(){let e=[];for(let t of Et){let n=Mt[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function bCe(e,t){let n=B(e,V(t));return Dl(n)?V(t):n}function D9(e){let{frontmatter:t,body:n}=eo(e),r={};if(t!==``)try{let e=(0,nj.parse)(mo(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function xCe(e,t){let n=D9(e),r=D9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function O9(e,t){let n=k9(e),r=k9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=z(e,o),c=z(t,o);if(i+=$l(s).size+$l(c).size,i>1048576)return!1;let l=U(s),u=U(c);if(!l.equals(u)&&(o!==`SKILL.md`||!xCe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function k9(e,t=``){let n=[];for(let r of Jl(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...k9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function A9(e,t,n){Qo(t,{recursive:!0,force:!0}),Jo(e,{recursive:!0}),Wo(bCe(e,n),t,`dir`)}function j9(e,t){try{let n=Yl(e);return V(Dl(n)?n:V(R(e),n))===V(t)}catch{return!1}}function SCe(e,t){try{let n=Yl(e),r=Dl(n)?V(n):V(R(e),n);if(!H(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||Dl(i))}catch(t){return T9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const CCe=[...Et,`agents`];function wCe(e){for(let t of CCe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function TCe(e){let{projectDir:t,skillsRoot:n}=e;if(!H(n))return;let r;try{r=Jl(n)}catch{return}let i=E9();for(let e of r){let r=wCe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(H(o))try{let n=Hl(a);if(n.isSymbolicLink()||!n.isDirectory()||!H(z(a,`SKILL.md`))||!H(z(o,`SKILL.md`))||!O9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(vB(t,r))continue;let i=z(r,e);j9(i,a)&&A9(r,i,o)}Qo(a,{recursive:!0,force:!0}),T9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){T9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function ECe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of E9()){let o=V(t,e);if(!H(o)||vB(t,o))continue;let s;try{s=Jl(o)}catch(e){T9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(yCe.has(e))continue;let t=z(o,e),s=V(n,e),c=H(s);try{let l=Hl(t);if(l.isSymbolicLink()){if(j9(t,s)&&c)continue;if(SCe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(A9(o,t,s),r.healed.push({name:e,editor:i})):(Qo(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ie.test(e)){T9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&O9(t,s)){A9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){T9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=aI(t);for(let[r,a]of i){let i=V(n,r);if(!H(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await sI(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??fB(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){T9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{TCe({projectDir:t,skillsRoot:n})}catch(e){T9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=rN(e);M9=new ps({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),va(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,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){va(null),await M9?.drain(),M9=null,N9=!1}To();const DCe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],OCe=[`cache`,`tmp`];function kCe(e){let t=V(e,ve);if(!(()=>{if(!H(t))return!0;try{return Jl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of DCe)H(V(e,t))&&n.push(t);for(let t of OCe){let r=V(e,t);try{H(r)&&$l(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function ACe(e){let t=ed(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 jCe(e){fH();let t=e.projectDir??e.contentDir,n=iQ({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}ls.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}as({localSink:n?.telemetry}),F9(t),pCe(),mCe();let{kind:r,gitdir:i}=ACe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Xo(i));let o=XZ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Lo(`ok.boot`,{attributes:a},async()=>MCe(e)),l=()=>{if(s)try{let e=wo.extract(Eo.active(),{traceparent:s});return Eo.with(e,c)}catch(e){L(`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 MCe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??L(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?gj(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new hj("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await import(`./server-lock-GGE1_Y5o.mjs`),p=!1;if(!t&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=V(m,`.ok`);if(!H(V(h,`config.yml`)))throw new Y8(H(h)?`config`:`okdir`,m);let g=V(h,`.gitignore`);H(g)||L(`boot`).warn({path:g},"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 _=e.gitPreflight??zG;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof IG||e instanceof LG){let t=e instanceof LG?e.detected:``,n=e instanceof LG?`too_old`:`not_available`;iK(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await is(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let v=kCe(h);v.length>0&&L(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ve}/.`);let y=p9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie}=y,E=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),D=e.port??0,ae=e.ephemeral?void 0:U8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${E}:${D}`,log:r}),O=l();O.headersTimeout=3e4,O.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:uM({contentFilter:y.contentFilter,contentSirv:zs(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ee,assetExtensions:c,blocklistExtensions:x}),se=!1;if(e.reactShellDistDir)try{mV(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof pV)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:T},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await S().catch(()=>{}),d(T),e}let k=e.reactShellDistDir?zs(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ce=e.ephemeral?null:new fD({contentDir:e.contentDir,localDir:T,globalDir:V(au(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:te,agentPresenceBroadcaster:re,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${E}:${D}`,getMcpStdioCommand:()=>dD(e.localOpCliArgs,D),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ce!==null&&await ce.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let le=G8({httpServer:O,hocuspocus:b,mcpHttpHandler:ae,remoteAccess:i,log:r,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:k,ephemeral:e.ephemeral,acpThreadManager:ce}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},de=null;a!==null&&(de=ZZ({httpServer:O,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ue()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);O.once(`error`,r),O.listen(e.port,e.host,()=>{O.removeListener(`error`,r),t()})})}catch(e){if(se)try{_V(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let fe=pH();fe!==void 0&&mH(`httpListenMs`,fe);let A=O.address(),pe=typeof A==`object`&&A?A.port:e.port??0;if(D=pe,f(T,pe),se&&hV(T,pe),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let j=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ue=async()=>{if(j)return;j=!0;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),se&&vV(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{de?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ce!==null&&await t(`acpThreads.destroy`,()=>ce.destroy()),await t(`mount.shutdown`,()=>le.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),se&&await t(`releaseUiLock`,async()=>_V(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>is()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>ls.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await w9({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:C9(e.contentDir,iV(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`store-skill-migration-failed`,error:String(e)},`Store-skill in-place migration failed (non-fatal).`)}try{let e=au(),t=await w9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:gCe,inPlaceNames:C9(e,aV(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`global-store-skill-migration-failed`,error:String(e)},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await ECe({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:O,destroy:ue,lockDir:T,contentDir:e.contentDir,port:pe,ready:C,degraded:w,didAutoInit:p,serverInstance:y,acpThreadManager:ce}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new WZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=td(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!H(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=vs({baseDir:n,timeout:{block:5e3}});s=new Set(await aS(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=nC(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 NCe=ke;function PCe(e={}){let t=e.home??au(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?H(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?H(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(fs(),1);const B9=z(au(),`.ok`,`logs`),FCe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function ICe(){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 LCe(e){Ul(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function RCe(e){try{if($l(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{Xl(n,r)}catch{}}try{eu(`${e}.3`)}catch{}}function zCe(e){try{let t=Date.now(),n=10080*60*1e3,r=Jl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=$l(z(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{eu(z(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{eu(z(e,t.name)),a-=t.size}catch{}}}catch{}}function BCe(e){LCe(B9);let t=V9(),n=e.filePath??z(B9,`${e.name}.${t}.log`);RCe(n),(e._setTimeout??setTimeout)(()=>zCe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:ICe(),name:e.name,redact:{paths:FCe,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 VCe(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 HCe(e){return z(B9,`${e}.${V9()}.log`)}function UCe(){return B9}function WCe(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=H(V(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}const H9=Pu(yl),U9=L(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function GCe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],NF({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function KCe(e){let t=V(e),n=V(t,`.git`),r=V(n,`HEAD`),i=!1;if(H(n)){if(!$l(n).isDirectory()||H(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=zG()}catch(e){throw e instanceof IG||e instanceof LG?(iK(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof LG?`too_old`:`not_available`,detectedVersion:e instanceof LG?e.detected:``},e instanceof LG?`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 GCe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],NF({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(!H(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=L(`project-skill-git`),K9=/^[0-9a-f]{40}$/,qCe=Jt.map(e=>e.replace(/\/$/,``));async function JCe(e){let t=td(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(QCe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ys(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await _s(async()=>{let t=await YCe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await XCe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=ys(e,{gitIndexFile:z(cu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await ZCe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await $U(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;xs(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${Da}\` 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 qCe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function YCe(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 XCe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function ZCe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function QCe(e){return H(z(e,`MERGE_HEAD`))||H(z(e,`rebase-merge`))||H(z(e,`rebase-apply`))||H(z(e,`CHERRY_PICK_HEAD`))||H(z(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function $Ce(e,t){let n;try{n=vl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=R(n),r=0;r<32;r+=1){let n=z(t,`package.json`);if(H(n))try{let t=JSON.parse(await pu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=R(t);if(r===t)return;t=r}}const ewe=[{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 ewe)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 twe(e){if(!eC(e))throw new $9(e);let t;try{t=W(V(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!$l(t).isFile())throw new Q9(e);let n=R(t),r=LU(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:nC(B(nwe(e),t).split(Al).join(`/`)),canonicalFilePath:t}}let i=wl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:nC(i)}}function nwe(e){return V(e,No({absPath:Fo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function rwe(e){let t=Wl(V(cu(),`ok-ephemeral-`)),n=V(t,`.ok`);return Ul(n,{recursive:!0}),tu(V(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),tu(V(n,`.gitignore`),`local/
|
|
2028
|
+
`))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}te(!1),await be.flushDeferredStores(`discard-stale`),n=!0,Ce?.emitBranchSwitched(i)}finally{M.abortBranchSwitch(r),n||(te(!1),await be.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ve.current&&r>0){let t=f??`.`;try{let n=await WS(ve.current,t,e.oldHead,e.newHead,i);cS(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),ht.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Tj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=nC(e),a=P.documents.get(i);if(!a)continue;let o=Qe(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=Tj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=P.documents.get(nC(e));i&&et(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=uCe(m),h=E();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{dt=new oCe({projectDir:n,contentDir:t,contentFilter:_e,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:Ce,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||be.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ve.current;n&&await KS(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ve.current;n&&await KS(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await qo({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:se(t.error),configPath:Fo(`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 dt.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),dt=null}Re(`files`),M.announceReadyViews();let g=pH();g!==void 0&&mH(`readyMs`,g),ce()}return gt().then(Fe,e=>{M.close(),Ie(e)}),{hocuspocus:P,durabilityState:x,sessionManager:xe,cc1Broadcaster:Ce,agentFocusBroadcaster:Te,agentPresenceBroadcaster:F,maintenanceCoordinator:ye,contentFilter:_e,basenameIndex:me,serverInstanceId:fe,destroy:mt,ready:Le,degraded:ht,lockDir:A,get syncEngine(){return dt},getLinkPreviewsEnabled:oe,resolveEmbed:he,acpRegistry:pe,acpPermissions:j}}function m9(e){return e/1048576}function fCe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:m9(e.rss),heapTotalMb:m9(e.heapTotal),heapUsedMb:m9(e.heapUsed),externalMb:m9(e.external),arrayBuffersMb:m9(e.arrayBuffers)}}}let h9=null,g9=null,_9=null;const v9=1e6;let y9=null,b9=null;Io(()=>{h9=null,g9=null,_9=null,y9?.disable(),y9=null,b9=null});function pCe(){if(h9)return;let e=os().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}=fCe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),h9=e}function mCe(){if(!g9){let e=os().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!y9){y9=Ou({resolution:20}),y9.enable();return}e.observe(y9.percentile(50)/v9,{stat:`p50`}),e.observe(y9.percentile(99)/v9,{stat:`p99`}),y9.reset()}),g9=e}if(!_9){let e=os().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=b9;if(b9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),_9=e}}const x9=L(`skill-migrate`);function S9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=UD.indexOf(e.host),r=UD.indexOf(t.host);return(n===-1?UD.length:n)-(r===-1?UD.length:r)||e.host.localeCompare(t.host)})}const hCe=S9(Mt),gCe=S9(Gn);function _Ce(e,t){Jo(R(t),{recursive:!0});try{Vo(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;Zo(e,t,{recursive:!0}),Qo(e,{recursive:!0,force:!0})}}function vCe(e,t,n){let r;try{r=Hl(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return W(e)===t?{kind:`ok-link`}:{kind:`foreign-link`}}catch{return{kind:`foreign-link`}}return r.isDirectory()&&LD(e)?.contentHash===n?{kind:`same-copy`}:{kind:`different`}}function C9(e,t){let n;try{n=W(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!W(V(e,t.dir)).startsWith(n+Al)}catch{return!0}}).map(e=>e.name))}async function w9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??hCe,a={migrated:[],skipped:[]};if(!H(n))return a;let o;try{o=Jl(n)}catch{return a}let s=B(t,n).split(Al).join(`/`),c=new Set;for(let[e,n]of Object.entries(HJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ie.test(e)||uz.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=V(n,e);if(!H(z(o,`SKILL.md`)))continue;let s=LD(o)?.contentHash;if(s===void 0)continue;let l=W(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:vB(t,i),state:vCe(z(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`ok-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind!==`different`&&e.state.kind!==`foreign-link`&&H(V(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`different`||d.state.kind===`foreign-link`){a.skipped.push({name:e,reason:`target-occupied:${d.root}`});continue}d.state.kind===`same-copy`?Qo(o,{recursive:!0,force:!0}):(d.state.kind===`ok-link`&&Qo(d.path,{recursive:!0,force:!0}),_Ce(o,d.path));for(let e of u)e===d||e.state.kind!==`ok-link`||(Qo(e.path,{recursive:!0,force:!0}),Zo(d.path,e.path,{recursive:!0}));await cI(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),x9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),x9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const T9=L(`skill-reconcile`),yCe=uz;function E9(){let e=[];for(let t of Et){let n=Mt[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function bCe(e,t){let n=B(e,V(t));return Dl(n)?V(t):n}function D9(e){let{frontmatter:t,body:n}=eo(e),r={};if(t!==``)try{let e=(0,nj.parse)(mo(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function xCe(e,t){let n=D9(e),r=D9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function O9(e,t){let n=k9(e),r=k9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=z(e,o),c=z(t,o);if(i+=$l(s).size+$l(c).size,i>1048576)return!1;let l=U(s),u=U(c);if(!l.equals(u)&&(o!==`SKILL.md`||!xCe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function k9(e,t=``){let n=[];for(let r of Jl(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...k9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function A9(e,t,n){Qo(t,{recursive:!0,force:!0}),Jo(e,{recursive:!0}),Wo(bCe(e,n),t,`dir`)}function j9(e,t){try{let n=Yl(e);return V(Dl(n)?n:V(R(e),n))===V(t)}catch{return!1}}function SCe(e,t){try{let n=Yl(e),r=Dl(n)?V(n):V(R(e),n);if(!H(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||Dl(i))}catch(t){return T9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const CCe=[...Et,`agents`];function wCe(e){for(let t of CCe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function TCe(e){let{projectDir:t,skillsRoot:n}=e;if(!H(n))return;let r;try{r=Jl(n)}catch{return}let i=E9();for(let e of r){let r=wCe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(H(o))try{let n=Hl(a);if(n.isSymbolicLink()||!n.isDirectory()||!H(z(a,`SKILL.md`))||!H(z(o,`SKILL.md`))||!O9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(vB(t,r))continue;let i=z(r,e);j9(i,a)&&A9(r,i,o)}Qo(a,{recursive:!0,force:!0}),T9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){T9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function ECe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of E9()){let o=V(t,e);if(!H(o)||vB(t,o))continue;let s;try{s=Jl(o)}catch(e){T9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(yCe.has(e))continue;let t=z(o,e),s=V(n,e),c=H(s);try{let l=Hl(t);if(l.isSymbolicLink()){if(j9(t,s)&&c)continue;if(SCe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(A9(o,t,s),r.healed.push({name:e,editor:i})):(Qo(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ie.test(e)){T9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&O9(t,s)){A9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){T9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=aI(t);for(let[r,a]of i){let i=V(n,r);if(!H(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await sI(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??fB(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){T9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{TCe({projectDir:t,skillsRoot:n})}catch(e){T9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=rN(e);M9=new ps({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),va(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,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){va(null),await M9?.drain(),M9=null,N9=!1}To();const DCe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],OCe=[`cache`,`tmp`];function kCe(e){let t=V(e,ve);if(!(()=>{if(!H(t))return!0;try{return Jl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of DCe)H(V(e,t))&&n.push(t);for(let t of OCe){let r=V(e,t);try{H(r)&&$l(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function ACe(e){let t=ed(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 jCe(e){fH();let t=e.projectDir??e.contentDir,n=iQ({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}ls.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}as({localSink:n?.telemetry}),F9(t),pCe(),mCe();let{kind:r,gitdir:i}=ACe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Xo(i));let o=XZ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Lo(`ok.boot`,{attributes:a},async()=>MCe(e)),l=()=>{if(s)try{let e=wo.extract(Eo.active(),{traceparent:s});return Eo.with(e,c)}catch(e){L(`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 MCe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??L(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?gj(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new hj("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await import(`./server-lock-CCA69O0D.mjs`),p=!1;if(!t&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=V(m,`.ok`);if(!H(V(h,`config.yml`)))throw new Y8(H(h)?`config`:`okdir`,m);let g=V(h,`.gitignore`);H(g)||L(`boot`).warn({path:g},"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 _=e.gitPreflight??zG;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof IG||e instanceof LG){let t=e instanceof LG?e.detected:``,n=e instanceof LG?`too_old`:`not_available`;iK(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await is(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let v=kCe(h);v.length>0&&L(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ve}/.`);let y=p9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie}=y,E=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),D=e.port??0,ae=e.ephemeral?void 0:U8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${E}:${D}`,log:r}),O=l();O.headersTimeout=3e4,O.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:uM({contentFilter:y.contentFilter,contentSirv:zs(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ee,assetExtensions:c,blocklistExtensions:x}),se=!1;if(e.reactShellDistDir)try{mV(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof pV)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:T},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await S().catch(()=>{}),d(T),e}let k=e.reactShellDistDir?zs(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ce=e.ephemeral?null:new fD({contentDir:e.contentDir,localDir:T,globalDir:V(au(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:te,agentPresenceBroadcaster:re,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${E}:${D}`,getMcpStdioCommand:()=>dD(e.localOpCliArgs,D),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ce!==null&&await ce.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let le=G8({httpServer:O,hocuspocus:b,mcpHttpHandler:ae,remoteAccess:i,log:r,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:k,ephemeral:e.ephemeral,acpThreadManager:ce}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},de=null;a!==null&&(de=ZZ({httpServer:O,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ue()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);O.once(`error`,r),O.listen(e.port,e.host,()=>{O.removeListener(`error`,r),t()})})}catch(e){if(se)try{_V(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let fe=pH();fe!==void 0&&mH(`httpListenMs`,fe);let A=O.address(),pe=typeof A==`object`&&A?A.port:e.port??0;if(D=pe,f(T,pe),se&&hV(T,pe),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let j=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ue=async()=>{if(j)return;j=!0;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),se&&vV(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{de?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ce!==null&&await t(`acpThreads.destroy`,()=>ce.destroy()),await t(`mount.shutdown`,()=>le.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),se&&await t(`releaseUiLock`,async()=>_V(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>is()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>ls.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await w9({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:C9(e.contentDir,iV(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`store-skill-migration-failed`,error:String(e)},`Store-skill in-place migration failed (non-fatal).`)}try{let e=au(),t=await w9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:gCe,inPlaceNames:C9(e,aV(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`global-store-skill-migration-failed`,error:String(e)},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await ECe({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:O,destroy:ue,lockDir:T,contentDir:e.contentDir,port:pe,ready:C,degraded:w,didAutoInit:p,serverInstance:y,acpThreadManager:ce}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new WZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=td(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!H(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=vs({baseDir:n,timeout:{block:5e3}});s=new Set(await aS(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=nC(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 NCe=ke;function PCe(e={}){let t=e.home??au(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?H(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?H(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(fs(),1);const B9=z(au(),`.ok`,`logs`),FCe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function ICe(){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 LCe(e){Ul(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function RCe(e){try{if($l(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{Xl(n,r)}catch{}}try{eu(`${e}.3`)}catch{}}function zCe(e){try{let t=Date.now(),n=10080*60*1e3,r=Jl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=$l(z(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{eu(z(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{eu(z(e,t.name)),a-=t.size}catch{}}}catch{}}function BCe(e){LCe(B9);let t=V9(),n=e.filePath??z(B9,`${e.name}.${t}.log`);RCe(n),(e._setTimeout??setTimeout)(()=>zCe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:ICe(),name:e.name,redact:{paths:FCe,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 VCe(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 HCe(e){return z(B9,`${e}.${V9()}.log`)}function UCe(){return B9}function WCe(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=H(V(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}const H9=Pu(yl),U9=L(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function GCe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],NF({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function KCe(e){let t=V(e),n=V(t,`.git`),r=V(n,`HEAD`),i=!1;if(H(n)){if(!$l(n).isDirectory()||H(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=zG()}catch(e){throw e instanceof IG||e instanceof LG?(iK(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof LG?`too_old`:`not_available`,detectedVersion:e instanceof LG?e.detected:``},e instanceof LG?`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 GCe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],NF({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(!H(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=L(`project-skill-git`),K9=/^[0-9a-f]{40}$/,qCe=Jt.map(e=>e.replace(/\/$/,``));async function JCe(e){let t=td(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(QCe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ys(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await _s(async()=>{let t=await YCe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await XCe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=ys(e,{gitIndexFile:z(cu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await ZCe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await $U(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;xs(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${Da}\` 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 qCe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function YCe(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 XCe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function ZCe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function QCe(e){return H(z(e,`MERGE_HEAD`))||H(z(e,`rebase-merge`))||H(z(e,`rebase-apply`))||H(z(e,`CHERRY_PICK_HEAD`))||H(z(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function $Ce(e,t){let n;try{n=vl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=R(n),r=0;r<32;r+=1){let n=z(t,`package.json`);if(H(n))try{let t=JSON.parse(await pu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=R(t);if(r===t)return;t=r}}const ewe=[{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 ewe)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 twe(e){if(!eC(e))throw new $9(e);let t;try{t=W(V(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!$l(t).isFile())throw new Q9(e);let n=R(t),r=LU(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:nC(B(nwe(e),t).split(Al).join(`/`)),canonicalFilePath:t}}let i=wl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:nC(i)}}function nwe(e){return V(e,No({absPath:Fo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function rwe(e){let t=Wl(V(cu(),`ok-ephemeral-`)),n=V(t,`.ok`);return Ul(n,{recursive:!0}),tu(V(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),tu(V(n,`.gitignore`),`local/
|
|
2029
2029
|
`,`utf-8`),t}export{ope as $,KS as $i,Wz as $n,aF as $r,IG as $t,X7 as A,dT as Ai,vU as An,Ole as Ar,OZ as At,d7 as B,_C as Bi,lH as Bn,LF as Br,sJ as Bt,p9 as C,dD as Ci,eU as Cn,DL as Cr,VZ as Ct,Z7 as D,YT as Di,$H as Dn,CL as Dr,WX as Dt,J7 as E,eE as Ei,fU as En,wL as Er,xX as Et,aSe as F,DC as Fi,NH as Fn,GF as Fr,nJ as Ft,K8 as G,HS as Gi,_V as Gn,Tce as Gr,fJ as Gt,J8 as H,YS as Hi,pV as Hn,OF as Hr,vJ as Ht,b7 as I,bC as Ii,FH as In,UF as Ir,gJ as It,A8 as J,FS as Ji,Qz as Jn,Cce as Jr,$q as Jt,U8 as K,LS as Ki,hV as Kn,Sce as Kr,cJ as Kt,y7 as L,pC as Li,PH as Ln,WF as Lr,mJ as Lt,R7 as M,NT as Mi,zH as Mn,bI as Mr,kJ as Mt,F7 as N,OC as Ni,BH as Nn,HF as Nr,EJ as Nt,K7 as O,XT as Oi,yU as On,Ule as Or,GX as Ot,v7 as P,q as Pi,MH as Pn,VF as Pr,xJ as Pt,Y2 as Q,JS as Qi,Uz as Qn,Jse as Qr,iK as Qt,qxe as R,vC as Ri,AH as Rn,zF as Rr,_J as Rt,I9 as S,Ooe as Si,tU as Sn,OL as Sr,zZ as St,G7 as T,ZT as Ti,_U as Tn,Wle as Tr,SX as Tt,Y8 as U,BS as Ui,mV as Un,DF as Ur,uJ as Ut,c7 as V,fC as Vi,tH as Vn,NF as Vr,hJ as Vt,G8 as W,VS as Wi,gV as Wn,wF as Wr,lJ as Wt,U2 as X,XS as Xi,Gz as Xn,pF as Xr,oK as Xt,H2 as Y,zS as Yi,rB as Yn,fce as Yr,cK as Yt,W2 as Z,NS as Zi,zz as Zn,bF as Zr,rK as Zt,NCe as _,id as _a,CO as _i,mW as _n,PL as _r,IZ as _t,twe as a,bS as aa,rN as ai,GG as an,Oz as ar,Yfe as at,F9 as b,Gu as ba,hD as bi,JH as bn,Yle as br,RZ as bt,JCe as c,qh as ca,uM as ci,AG as cn,Tz as cr,C2 as ct,WCe as d,Jh as da,hj as di,dW as dn,lz as dr,Q$ as dt,qS as ea,Kse as ei,LG as en,Lz as er,I2 as et,BCe as f,Md as fa,Cj as fi,fW as fn,mz as fr,fue as ft,PCe as g,ad as ga,pj as gi,aW as gn,NL as gr,HZ as gt,UCe as h,Td as ha,mj as hi,pW as hn,eR as hr,ZZ as ht,rwe as i,SS as ia,nF as ii,RG as in,Dz as ir,Jfe as it,W7 as j,fT as ji,ZH as jn,xI as jr,IX as jt,Y7 as k,VT as ki,PU as kn,ZI as kr,jZ as kt,W9 as l,Kh as la,Dj as li,DG as ln,fz as lr,W0 as lt,HCe as m,Nd as ma,gj as mi,gW as mn,BR as mr,g1 as mt,Z9 as n,jS as na,tF as ni,zG as nn,Bz as nr,A2 as nt,X9 as o,pS as oa,nN as oi,VG as on,Ez as or,w2 as ot,VCe as p,Ed as pa,xj as pi,sW as pn,hz as pr,p1 as pt,B8 as q,WS as qi,oB as qn,wce as qr,Qq as qt,$9 as r,wS as ra,rF as ri,nK as rn,Rz as rr,qfe as rt,$Ce as s,dae as sa,iN as si,jG as sn,yz as sr,S2 as st,Q9 as t,ZS as ta,iF as ti,PG as tn,Iz as tr,F2 as tt,KCe as u,Yh as ua,wj as ui,rW as un,pz as ur,b1 as ut,jCe as v,Cd as va,_D as vi,LU as vn,FL as vr,BZ as vt,f9 as w,FT as wi,xU as wn,TL as wr,PZ as wt,P9 as x,Wu as xa,fD as xi,bU as xn,EL as xr,LZ as xt,R9 as y,nd as ya,gD as yi,IU as yn,ML as yr,FZ as yt,f7 as z,mC as zi,CH as zn,PF as zr,oJ as zt};
|
|
2030
|
-
//# sourceMappingURL=src-
|
|
2030
|
+
//# sourceMappingURL=src-DlAv53T2.mjs.map
|