@inkeep/open-knowledge 0.56.0-beta.3 → 0.56.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-harness-probe-DXnd9xmF.mjs → acp-harness-probe-CW_nXSWP.mjs} +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/config-schema.json +1 -2
- package/dist/config.user.schema.json +1 -2
- package/dist/constants-C0QuALA7.mjs +2 -0
- package/dist/fs-traced-DN8Ne6OV.mjs +1 -0
- package/dist/{fs-traced-xJfl5Rxd.mjs → fs-traced-uUie5siN.mjs} +2 -2
- package/dist/{git-handle-B0tCzHAN.mjs → git-handle-BI3zkVk-.mjs} +2 -2
- package/dist/git-handle-Bo4ytezq.mjs +1 -0
- package/dist/index.d.mts +1 -2
- package/dist/index.mjs +2 -2
- package/dist/{init-BmnIpLHA.mjs → init--f4zFUMB.mjs} +3 -3
- package/dist/init-yZIwxM4j.mjs +1 -0
- package/dist/{launch-json-removal-YoOKlcfq.mjs → launch-json-removal-CfLRLAib.mjs} +2 -2
- package/dist/{loader-DA32Jr_m.mjs → loader-B4KkmTuM.mjs} +2 -2
- package/dist/loader-fKOwJB6S.mjs +1 -0
- package/dist/md-manager-Q1tI0hzy.mjs +2 -0
- package/dist/{open-browser-CXZADc20.mjs → open-browser-CvutfNRO.mjs} +2 -2
- package/dist/parse-worker.mjs +1 -1
- package/dist/{preview-B56IpPgt.mjs → preview-BbBZEvyk.mjs} +2 -2
- package/dist/preview-ssmwZAWL.mjs +1 -0
- package/dist/public/assets/{ActivityModeContent-U1FJ3QIy.js → ActivityModeContent-CuxM2GI1.js} +1 -1
- package/dist/public/assets/{AgentDiffPane-CHkouQJB.js → AgentDiffPane-CAsMvyqx.js} +1 -1
- package/dist/public/assets/{AgentThreadClientBinder-ChxqWHn_.js → AgentThreadClientBinder-FSBCMKY3.js} +1 -1
- package/dist/public/assets/{CodeMirrorPropInput-CBdNV6SE.js → CodeMirrorPropInput-Cw0ePGRQ.js} +1 -1
- package/dist/public/assets/{DocumentContext-CmVCZjAv.js → DocumentContext-BOGc7fjB.js} +1 -1
- package/dist/public/assets/{EditorModeToggle-CoLPtq1t.js → EditorModeToggle-DDFDVZ-W.js} +1 -1
- package/dist/public/assets/{EnableSyncConfirmDialog-CFRlwXGj.js → EnableSyncConfirmDialog-rACItPww.js} +1 -1
- package/dist/public/assets/FeedbackForm-Cg1ck408.js +1 -0
- package/dist/public/assets/{GraphPanel-COPEU9QX.js → GraphPanel--hj263vb.js} +1 -1
- package/dist/public/assets/{ImportSkillDialog-SdjDKtJN.js → ImportSkillDialog-Dip726xX.js} +1 -1
- package/dist/public/assets/{LintConfigEditor-BDyWMcfJ.js → LintConfigEditor-mJ7Vq7Gu.js} +1 -1
- package/dist/public/assets/{ManagedArtifactProperties-TjF4BQQf.js → ManagedArtifactProperties-CM_NiJGd.js} +1 -1
- package/dist/public/assets/ManagedArtifactProperties-DChOnvya.js +1 -0
- package/dist/public/assets/{McpConsentDialogBody-CVb-mMB8.js → McpConsentDialogBody-BAZN_O20.js} +1 -1
- package/dist/public/assets/{MermaidDocEditor-BhQaXQjB.js → MermaidDocEditor-B1RjPntQ.js} +1 -1
- package/dist/public/assets/{PropertyDisplayRow-B3TVSycQ.js → PropertyDisplayRow-BUTotMt7.js} +1 -1
- package/dist/public/assets/{ReportBugDialogBody-Ajl3p6In.js → ReportBugDialogBody-CBkRZUpU.js} +1 -1
- package/dist/public/assets/{SchemaConfigEditor-BQjnFuKU.js → SchemaConfigEditor-DlZiHNGy.js} +1 -1
- package/dist/public/assets/{SessionsHost-D0b_fHz9.js → SessionsHost-Dmk8ARcn.js} +2 -2
- package/dist/public/assets/{SettingsDialogBody-BVL7tByV.js → SettingsDialogBody-DboXXu3o.js} +1 -1
- package/dist/public/assets/{ShareBranchSwitchDialog-oqH7CVAK.js → ShareBranchSwitchDialog-BNq_3Gef.js} +1 -1
- package/dist/public/assets/{ShareReceiveDialog-qvhiGzxM.js → ShareReceiveDialog-B5FddHIB.js} +1 -1
- package/dist/public/assets/{ShareReceiveMissDialog-DdivT93v.js → ShareReceiveMissDialog-DJsrMn_9.js} +1 -1
- package/dist/public/assets/{SkillEditBanner-C2NwXGwp.js → SkillEditBanner-BW2VDVIo.js} +1 -1
- package/dist/public/assets/{SkillInstallMenu-DG2UypgE.js → SkillInstallMenu-CxQT1ld3.js} +1 -1
- package/dist/public/assets/{SkillOriginInline-Bfr_LvLW.js → SkillOriginInline-DUXTbZ1I.js} +1 -1
- package/dist/public/assets/{SkillToolbarControls-BfQkA4sf.js → SkillToolbarControls-DZaJ1ZyP.js} +1 -1
- package/dist/public/assets/{SlidesToolbarControls-Cib12Sqv.js → SlidesToolbarControls-DNGBygyg.js} +1 -1
- package/dist/public/assets/{SourceEditor-Dbik8eCt.js → SourceEditor-HnDtiE3q.js} +1 -1
- package/dist/public/assets/{TerminalPanel-CyjfYWsq.js → TerminalPanel-18X_ZMlO.js} +1 -1
- package/dist/public/assets/{TerminalWindowApp-CcYZi-zD.js → TerminalWindowApp-B6mvY0PM.js} +1 -1
- package/dist/public/assets/{TextDocEditor-DRMRlxJq.js → TextDocEditor-BpXrF4Sq.js} +1 -1
- package/dist/public/assets/{ThreadView-jlS0ehwV.js → ThreadView-CuvPDOR2.js} +1 -1
- package/dist/public/assets/{TimelineDiffPane-BvbIPNLH.js → TimelineDiffPane-BEO6_jvM.js} +1 -1
- package/dist/public/assets/{agent-diff-store-CbfY0VSo.js → agent-diff-store-DuZJJ7Ci.js} +1 -1
- package/dist/public/assets/{auth-state-cache-C6rYX6hP.js → auth-state-cache-CHAm12x1.js} +1 -1
- package/dist/public/assets/client-version-xTNgCY5Y.js +1 -0
- package/dist/public/assets/{comment-chips-8I53Qmd9.js → comment-chips-0OZCB2iB.js} +1 -1
- package/dist/public/assets/{config-provider-DE1EpoHY.js → config-provider-Cgwz6Lof.js} +2 -2
- package/dist/public/assets/{dist-COv61_fZ2.js → dist-A3OTH2KL2.js} +2 -2
- package/dist/public/assets/{doc-paths-7BigDJzU.js → doc-paths-BABCQ0wh.js} +1 -1
- package/dist/public/assets/{documents-events-BG9v7ZR8.js → documents-events-CK6j9M45.js} +1 -1
- package/dist/public/assets/{file-tree-adapter-BaT9ZAI6.js → file-tree-adapter-DcrKUDBN.js} +1 -1
- package/dist/public/assets/{file-tree-utils-BnMWB0rN.js → file-tree-utils-CJ-q2ioX.js} +1 -1
- package/dist/public/assets/{folder-config-api-CspTyRPC.js → folder-config-api-CjDyND9I.js} +1 -1
- package/dist/public/assets/{follow-file-CTh6w0Fk.js → follow-file-DAdcgwn_.js} +1 -1
- package/dist/public/assets/i18n-BYT2p-2f.js +1 -0
- package/dist/public/assets/{index-C0lgUj3_.js → index-aXt_JWZ2.js} +7 -7
- package/dist/public/assets/{lint-config-client-D4Gin48u.js → lint-config-client-Ci5UGAFH.js} +1 -1
- package/dist/public/assets/{markdownlint-rule-browser-qdlEJqGK.js → markdownlint-rule-browser-6w4wGoBF.js} +1 -1
- package/dist/public/assets/{navigation-targets-BlmF0SDc.js → navigation-targets-Cq8reTNr.js} +1 -1
- package/dist/public/assets/{open-managed-artifact-tab-DyQLDLZu.js → open-managed-artifact-tab-WbPC9lqJ.js} +1 -1
- package/dist/public/assets/{pending-receive-nav-store-hMEGGslQ.js → pending-receive-nav-store-DWYln4pm.js} +1 -1
- package/dist/public/assets/{prop-types-x3L5Ba9q.js → prop-types-JZyx8uP_.js} +1 -1
- package/dist/public/assets/{receive-store-DyKO2VJp.js → receive-store-Bq6Ld9zP.js} +1 -1
- package/dist/public/assets/{selection-context-B5-XIY2b.js → selection-context-h9OrguDp.js} +1 -1
- package/dist/public/assets/{skill-actions-D_LBQ9Ds.js → skill-actions-P6hLIq0o.js} +1 -1
- package/dist/public/assets/{skill-scope-Dvl0F_Nc.js → skill-scope-CbkpErsk.js} +1 -1
- package/dist/public/assets/{skills-api-D3yktqw_.js → skills-api-C_ayTuhp.js} +1 -1
- package/dist/public/assets/{src-CI7Rk9PO.js → src-BdAe1iLc.js} +1 -1
- package/dist/public/assets/{tag-pill-input-B-KJK7ye.js → tag-pill-input-Bl7OJSC_.js} +1 -1
- package/dist/public/assets/{target-navigation-intent-Cq4g4MwT.js → target-navigation-intent-BBy6G0-P.js} +1 -1
- package/dist/public/assets/{telemetry-impl-DRTdire4.js → telemetry-impl-BXKSOWP8.js} +2 -2
- package/dist/public/assets/{telemetry-startup-DWe6KY2T.js → telemetry-startup-BbS8KkvZ.js} +1 -1
- package/dist/public/assets/{terminal-cli-display-CpAOcb2j.js → terminal-cli-display-_UKgGxrA.js} +1 -1
- package/dist/public/assets/{terminal-launch-events-mKO9oOVx.js → terminal-launch-events-gIAwvS38.js} +1 -1
- package/dist/public/assets/{terminal-telemetry-hqCajE8l.js → terminal-telemetry-BoIx62eZ.js} +1 -1
- package/dist/public/assets/{typing-burst-detector-B73zIKbr.js → typing-burst-detector-ClR2eDHr.js} +1 -1
- package/dist/public/assets/{uninstall-DQiMrABF.js → uninstall-CKF78F-5.js} +1 -1
- package/dist/public/assets/{use-activity-panel-IvNsnSV8.js → use-activity-panel-yqtV5LnI.js} +1 -1
- package/dist/public/assets/{use-apply-config-color-theme-B1zL7AB7.js → use-apply-config-color-theme-BIhgV6Ch.js} +1 -1
- package/dist/public/assets/{use-collab-url-CBEaRBLp.js → use-collab-url-Cp-Rj0bC.js} +1 -1
- package/dist/public/assets/{use-live-xterm-theme-Bg0pl-eA.js → use-live-xterm-theme-BT8isURw.js} +1 -1
- package/dist/public/assets/{use-open-skill-CAdcxfnz.js → use-open-skill-D96TChRC.js} +1 -1
- package/dist/public/assets/{use-popular-skills-DyxaSas-.js → use-popular-skills-BvPp-gxD.js} +1 -1
- package/dist/public/assets/{use-settings-route-CQWgqLVD.js → use-settings-route-BNd_oo0M.js} +1 -1
- package/dist/public/assets/{use-skill-origin-DschKPDB.js → use-skill-origin-BenKziPn.js} +1 -1
- package/dist/public/assets/{use-skills-RGrgR7Ae.js → use-skills-bayaEv_Y.js} +1 -1
- package/dist/public/assets/{use-terminal-enabled-DRFMuFx0.js → use-terminal-enabled-CX-aqvuQ.js} +1 -1
- package/dist/public/assets/{use-timeline-entry-diff-Cndr8_xa.js → use-timeline-entry-diff-BbNfyqQd.js} +1 -1
- package/dist/public/assets/{use-workspace-CTox7-Ea.js → use-workspace-tdp7vU_c.js} +1 -1
- package/dist/public/index.html +45 -45
- package/dist/public/uninstall.html +3 -3
- package/dist/{repair-launch-json-DFAcawUg.mjs → repair-launch-json-Z9hZ2Ecf.mjs} +2 -2
- package/dist/{repair-mcp-configs-DQxJe8ZH.mjs → repair-mcp-configs-BFWH-O-X.mjs} +2 -2
- package/dist/{repair-skills-B1yLGVCl.mjs → repair-skills-GEvrJzaq.mjs} +2 -2
- package/dist/repair-skills-dpqiLSBb.mjs +1 -0
- package/dist/schemas/v0/config.user.schema.json +1 -2
- package/dist/server-lock-BJIPnZ6Y.mjs +1 -0
- package/dist/{server-lock-BHY1C3dW.mjs → server-lock-C-cXu0qQ.mjs} +2 -2
- package/dist/{skill-teardown-CJl8M28h.mjs → skill-teardown-D1piAzOB.mjs} +2 -2
- package/dist/{sleep-D_nNc7T_.mjs → sleep-OHCt3UoV.mjs} +2 -2
- package/dist/{src-BfZxol1g.mjs → src-BljoChXq.mjs} +2 -2
- package/dist/src-BtcwR3z-.mjs +1 -0
- package/dist/{src--C17TQmO.mjs → src-DHp3eXPs.mjs} +1 -1
- package/dist/{src-DMi2O7yV.mjs → src-DQgEWrUq.mjs} +2 -2
- package/dist/{src-C6s1YGEs.mjs → src-Dhqa-DT-.mjs} +6 -6
- package/dist/{start-D0oAvpwd.mjs → start-Byz-i73C.mjs} +4 -4
- package/dist/start-wRJOuq9q.mjs +1 -0
- package/dist/{ui-CSid4Ybi.mjs → ui-vKry5mIJ.mjs} +3 -3
- package/dist/{write-project-skill-G2p_hc1u.mjs → write-project-skill-BfsBXTaY.mjs} +2 -2
- package/package.json +4 -4
- package/dist/constants-B7Ama35H.mjs +0 -2
- package/dist/fs-traced-BEuPZxxL.mjs +0 -1
- package/dist/git-handle-DQRBUWfE.mjs +0 -1
- package/dist/init-BUCGvAOn.mjs +0 -1
- package/dist/loader-BX5BiEGp.mjs +0 -1
- package/dist/md-manager-IForifhX.mjs +0 -2
- package/dist/preview-CqdkGO4h.mjs +0 -1
- package/dist/public/assets/FeedbackForm-DN6bfc_e.js +0 -1
- package/dist/public/assets/ManagedArtifactProperties-IThNpL1R.js +0 -1
- package/dist/public/assets/client-version-CvdpPTtb.js +0 -1
- package/dist/public/assets/i18n-C-GzCn3p.js +0 -1
- package/dist/public/assets/messages-CuB-3U4F.js +0 -1
- package/dist/repair-skills-nLLLv3za.mjs +0 -1
- package/dist/server-lock-CXt9yQWS.mjs +0 -1
- package/dist/src-DvWh73sV.mjs +0 -1
- package/dist/start-rWOiwMcT.mjs +0 -1
- /package/dist/public/assets/{__vite-browser-external-N4Ia604h.js → __vite-browser-external-DD8Jl_VU.js} +0 -0
- /package/dist/public/assets/{messages-DwQQdLmE.js → messages--jxWd8S9.js} +0 -0
- /package/dist/public/assets/{messages-DDp8k2cy.js → messages-B0JNOJmY.js} +0 -0
- /package/dist/public/assets/{messages-BNVZJyDD.js → messages-CzCSQgXH.js} +0 -0
- /package/dist/public/assets/{messages-DmcPLWJb.js → messages-pZwFjfzt.js} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,At as i,Bt as a,C as o,Ct as s,Et as c,F as l,Ft as u,Gt as d,I as f,It as p,Jt as m,Kt as h,L as g,Lt as _,Mt as v,N as y,Nt as b,Ot as x,P as S,Pt as C,Q as w,Qt as T,R as E,Rt as ee,S as te,St as D,T as ne,Tt as O,U as re,V as k,Vt as A,Wt as ie,Xt as ae,Yt as oe,Zt as se,_t as ce,a as le,at as ue,d as de,dt as j,en as fe,ft as pe,ht as me,i as he,it as ge,j as _e,jt as M,kt as ve,lt as ye,m as be,mt as xe,o as Se,ot as Ce,p as we,qt as Te,s as Ee,st as De,t as Oe,tn as ke,tt as Ae,ut as je,vt as Me,w as Ne,wt as Pe,x as Fe,xt as N,yt as Ie,z as Le,zt as Re}from"./sleep-D_nNc7T_.mjs";import{$ as ze,$a as Be,$i as Ve,$n as He,$o as Ue,$r as We,$s as Ge,$t as Ke,A as qe,Aa as Je,Ai as Ye,An as Xe,Ao as Ze,Ar as Qe,As as $e,At as et,B as tt,Ba as nt,Bi as rt,Bn as it,Bo as at,Br as ot,Bs as st,Bt as ct,C as lt,Ca as ut,Ci as dt,Cn as ft,Co as pt,Cr as mt,Cs as ht,Ct as gt,D as _t,Da as vt,Di as yt,Dn as bt,Do as xt,Dr as St,Ds as Ct,Dt as wt,E as Tt,Ea as Et,Ei as Dt,En as Ot,Eo as kt,Er as At,Es as jt,Et as Mt,F as Nt,Fa as Pt,Fi as Ft,Fn as It,Fo as Lt,Fr as Rt,Fs as zt,Ft as Bt,Ga as Vt,Gi as Ht,Gn as Ut,Go as Wt,Gr as Gt,Gs as Kt,Gt as qt,H as Jt,Ha as Yt,Hi as Xt,Hn as Zt,Ho as Qt,Hr as $t,Hs as en,Ht as tn,I as nn,Ia as rn,Ii as an,In as on,Io as sn,Ir as cn,Is as ln,It as un,J as dn,Ja as fn,Ji as pn,Jn as mn,Jo as hn,Jr as gn,Js as _n,Jt as vn,K as yn,Ka as bn,Ki as xn,Kn as Sn,Ko as Cn,Kr as wn,Ks as Tn,Kt as En,L as Dn,La as On,Li as kn,Ln as An,Lr as jn,Ls as Mn,M as Nn,Ma as Pn,Mi as eee,Mn as tee,Mo as Fn,Mr as In,Ms as Ln,Mt as Rn,N as zn,Na as Bn,Ni as nee,Nn as ree,No as iee,Nr as aee,Nt as Vn,O as Hn,Oa as Un,Oi as Wn,On as Gn,Oo as Kn,Or as qn,Os as Jn,Ot as Yn,P as Xn,Pa as Zn,Pi as Qn,Pn as $n,Po as er,Pr as oee,Ps as tr,Pt as see,Q as nr,Qa as rr,Qi as ir,Qn as cee,Qr as ar,Qs as or,Qt as lee,R as sr,Ra as cr,Ri as lr,Rn as ur,Ro as dr,Rr as fr,Rs as pr,S as mr,Sa as hr,Si as gr,Sn as _r,So as vr,Sr as yr,Ss as br,St as xr,T as Sr,Ta as Cr,Ti as wr,Tn as uee,To as dee,Tr as fee,Ts as Tr,Tt as Er,U as Dr,Ua as Or,Ui as kr,Un as pee,Ur as mee,Us as Ar,Ut as jr,V as Mr,Va as Nr,Vi as Pr,Vn as Fr,Vr as Ir,Vt as Lr,Wa as Rr,Wi as zr,Wn as Br,Wr as Vr,Ws as Hr,Wt as Ur,X as Wr,Xa as Gr,Xi as Kr,Xn as qr,Xo as Jr,Xr as Yr,Xs as Xr,Xt as Zr,Y as Qr,Ya as $r,Yi as ei,Yn as ti,Yr as ni,Ys as ri,Yt as ii,Z as ai,Za as oi,Zi as si,Zn as ci,Zo as li,Zr as ui,Zs as di,Zt as hee,_ as fi,_a as gee,_c as pi,_i as mi,_n as _ee,_o as hi,_r as vee,_s as gi,_t as _i,a as vi,aa as yi,ai as bi,an as yee,ao as xi,ar as Si,as as Ci,at as wi,b as Ti,ba as bee,bi as xee,bn as See,bo as Cee,br as Ei,bt as Di,c as Oi,ca as ki,ci as Ai,cn as ji,co as Mi,cr as Ni,cs as Pi,ct as Fi,d as Ii,da as Li,dc as Ri,di as zi,dn as Bi,do as Vi,dr as Hi,ds as Ui,dt as Wi,ea as Gi,ec as Ki,ei as qi,en as Ji,eo as Yi,er as Xi,es as Zi,et as Qi,f as $i,fa as ea,fc as ta,fi as na,fn as ra,fo as ia,fr as aa,fs as oa,ft as sa,g as ca,ga as la,gi as ua,gn as da,go as wee,gr as Tee,gt as fa,h as pa,ha as ma,hi as Eee,hn as ha,ho as Dee,hr as Oee,hs as ga,ht as _a,i as va,ia as ya,ic as ba,ii as xa,in as kee,ir as Sa,is as Ca,j as wa,ja as Aee,ji as Ta,jn as jee,jo as Mee,jr as Nee,js as Ea,jt as Da,k as Oa,ka as Pee,ki as ka,kn as Fee,ko as Iee,kr as Lee,ks as Aa,kt as ja,l as Ma,la as Na,li as Pa,ln as Ree,lo as Fa,lr as zee,ls as Ia,lt as La,m as Ra,ma as za,mc as Ba,mi as Va,mn as Ha,mo as Ua,mr as Wa,ms as Ga,mt as Ka,n as qa,na as Ja,nc as Ya,ni as Xa,nn as Za,no as Qa,nr as $a,ns as eo,nt as to,o as no,oa as ro,oi as io,on as ao,oo,or as so,os as co,ot as lo,p as uo,pa as fo,pc as po,pi as mo,pn as ho,pr as go,pt as _o,q as vo,qa as yo,qi as bo,qn as xo,qo as So,qr as Co,qs as wo,qt as To,r as Eo,ra as Do,rc as Oo,ri as ko,rn as Ao,ro as jo,rr as Mo,rs as No,s as Po,sa as Fo,si as Io,sn as Bee,so as Lo,sr as Vee,st as Ro,t as zo,ta as Bo,ti as Hee,tn as Uee,to as Vo,tr as Wee,tt as Ho,u as Uo,ua as Wo,ui as Gee,un as Kee,uo as Go,ur as qee,us as Ko,ut as qo,v as Jo,va as Jee,vi as Yee,vn as Xee,vo as Zee,vr as Yo,vs as Xo,vt as Zo,w as Qo,wa as Qee,wi as $o,wn as $ee,wo as ete,wr as tte,wt as es,x as ts,xa as nte,xi as ns,xn as rs,xo as rte,xr as ite,xs as is,xt as as,y as os,ya as ss,yi as ate,yn as ote,yo as cs,yr as ste,ys as ls,yt as us,z as ds,za as cte,zi as fs,zn as lte,zo as ps,zr as ms,zs as hs,zt as gs}from"./src-DMi2O7yV.mjs";import{c as _s,i as vs,l as ys,n as bs,s as xs}from"./esm-DxvI2ZVA.mjs";import{n as Ss,t as Cs}from"./md-manager-IForifhX.mjs";import{A as ws,C as Ts,E as Es,I as Ds,M as Os,O as ks,P as As,S as js,T as Ms,_ as Ns,a as Ps,b as Fs,c as Is,d as Ls,f as Rs,g as zs,h as Bs,i as Vs,j as Hs,k as Us,l as Ws,m as Gs,n as Ks,o as qs,p as Js,r as Ys,s as Xs,t as Zs,u as Qs,v as $s,w as ec,x as tc,y as nc}from"./fs-traced-xJfl5Rxd.mjs";import{D as rc,E as ic,S as ac,T as oc,a as sc,b as cc,l as lc,p as uc,r as P,s as dc,x as fc,y as pc}from"./logger-DFxEUjvj.mjs";import{a as mc,i as hc,o as gc,r as _c,s as vc,t as yc}from"./git-handle-B0tCzHAN.mjs";import{C as bc,S as xc,_ as Sc,a as Cc,b as wc,c as Tc,f as Ec,g as Dc,h as Oc,i as kc,l as Ac,n as jc,p as Mc,r as Nc,u as Pc,x as Fc}from"./server-lock-BHY1C3dW.mjs";import{t as Ic}from"./libesm-DzwC_yFw.mjs";import{t as Lc}from"./yazl-DZr4PyKA.mjs";import{n as Rc,t as zc}from"./build-CJW5ggp6.mjs";import{t as Bc}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Vc,c as Hc,d as Uc,f as Wc,h as Gc,i as Kc,l as qc,m as Jc,n as Yc,o as Xc,p as Zc,r as Qc,s as $c,t as el,u as tl}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as nl,B as rl,C as il,D as al,E as ol,F as sl,H as cl,I as ll,L as ul,M as dl,N as fl,O as pl,P as ml,S as hl,T as gl,V as _l,_ as vl,a as yl,b as bl,c as xl,d as Sl,f as Cl,g as wl,h as Tl,i as El,j as Dl,k as Ol,l as kl,m as Al,n as jl,o as Ml,p as Nl,r as Pl,s as Fl,t as Il,u as Ll,v as Rl,w as zl,x as Bl,y as Vl,z as Hl}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Ul,c as Wl,d as Gl,i as Kl,l as ql,n as Jl,o as Yl,r as Xl,s as Zl,t as Ql,u as $l}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as eu,r as tu,t as nu}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as ru}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as iu}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as au,t as ou}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as su,t as cu}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as lu,r as uu,t as du}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as fu,t as pu}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as mu}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as hu}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as gu}from"./wrapper-BcpqREsI.mjs";import{createRequire as _u}from"node:module";import{execFile as vu,execFileSync as yu,spawn as bu,spawnSync as xu}from"node:child_process";import*as Su from"node:path";import{basename as Cu,delimiter as wu,dirname as F,extname as Tu,isAbsolute as Eu,join as I,normalize as Du,parse as Ou,posix as ku,relative as L,resolve as R,sep as z,win32 as Au}from"node:path";import{URLSearchParams as ju,fileURLToPath as Mu,pathToFileURL as Nu}from"node:url";import*as Pu from"node:fs";import{appendFileSync as Fu,chmodSync as Iu,closeSync as Lu,constants as Ru,createReadStream as zu,createWriteStream as Bu,existsSync as B,fstatSync as ute,lstatSync as Vu,mkdirSync as Hu,mkdtempSync as Uu,openSync as Wu,opendirSync as Gu,readFile as dte,readFileSync as V,readSync as Ku,readdirSync as qu,readlinkSync as Ju,realpathSync as H,renameSync as Yu,rmSync as Xu,rmdirSync as Zu,statSync as Qu,unlinkSync as $u,writeFileSync as ed,writeSync as fte}from"node:fs";import{arch as td,availableParallelism as pte,homedir as nd,hostname as rd,platform as id,tmpdir as ad}from"node:os";import{access as od,chmod as mte,constants as sd,lstat as cd,readFile as ld,readdir as ud,realpath as dd,stat as fd,writeFile as hte}from"node:fs/promises";import{Readable as pd,Transform as gte,Writable as _te}from"node:stream";import md,{createHash as hd,randomUUID as gd,webcrypto as _d}from"node:crypto";import vte from"crypto";import{Readable as vd}from"stream";import{EventEmitter as yte}from"node:events";import{Worker as bte}from"node:worker_threads";import{monitorEventLoopDelay as xte,performance as yd}from"node:perf_hooks";import{createInterface as Ste}from"node:readline";import{pipeline as bd}from"node:stream/promises";import{setImmediate as Cte,setTimeout as xd}from"node:timers/promises";import{promisify as Sd}from"node:util";import{request as wte}from"node:http";import{Http2ServerRequest as Cd,constants as Tte}from"node:http2";import{lookup as Ete}from"node:dns/promises";import{request as Dte}from"node:https";import{createBrotliDecompress as Ote,createGunzip as kte,createInflate as Ate}from"node:zlib";import{Http2ServerRequest as wd,constants as jte}from"http2";import{AsyncLocalStorage as Mte}from"node:async_hooks";import{lookup as Nte}from"node:dns";import Pte from"node:tls";function Fte(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Ite(n)}function Ite(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 Td=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=V(I(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Eu(t)?t:R(this.gitDir,t))}catch(e){if(!kd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=V(I(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return kd(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]}:jd(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=V(I(t.path,`config`),`utf-8`)}catch(e){return kd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Lte(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Ad(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=R(t.path,e),r=L(t.path,n);if(r.startsWith(`..`)||Eu(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Bte(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!kd(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(I(t.path,`packed-refs`),`utf-8`)}catch(e){return kd(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 jd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Ed(e){return Od(R(e),``)}function Dd(e){let t=R(e),n=R(nd());if(t===n)return{kind:`absent`};let r=Od(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=F(i);if(e===i||e===n)return{kind:`absent`};let r=Od(e,L(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Od(e,t){let n=I(e,`.git`),r;try{r=Qu(n)}catch(e){return kd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Td(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=V(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Eu(o)?o:R(e,o);try{if(!Qu(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Td(`linked`,e,t,n,s)}}function Lte(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Rte(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=zte(i[1]);if(a.length>0)return a}return null}function Rte(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function zte(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function kd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Ad(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Bte(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Ad(t[1])?{kind:`symbolic`,target:t[1]}:null:jd(e)?{kind:`oid`,oid:e}:null}function jd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}const Md=`ok-generator`;function Vte(e){return`git-author-${Rn(e.trim().toLowerCase())}`}const Hte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service|ok-generator)$/;function Nd(e){let t=Dd(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 Pd(e){let t=Nd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function Fd(e){let t=Nd(e);switch(t.kind){case`directory`:return R(t.path,Id(t.projectSubPath));case`linked`:if(!B(t.path))throw new Ld(t.gitPath,t.path);return R(t.path,Id(t.projectSubPath));case`malformed-pointer`:throw new Ld(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Rd(t.gitPath,{cause:t.cause});case`absent`:return R(e,`.git/ok`)}}function Id(e){return e===``?`ok`:`ok-${Ute(e)}`}function Ute(e){let t=e.split(z).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Wte(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Wte(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var Ld=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}},Rd=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 Gte(e){let t;try{t=Fd(e)}catch(e){if(e instanceof Ld||e instanceof Rd)return null;throw e}return B(R(t,`HEAD`))?t:null}function zd(e){return`refs/wip/${e}/`}function Kte(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{$t as r,At as i,Bt as a,C as o,Ct as s,Et as c,F as l,Ft as u,Gt as d,I as f,It as p,Jt as m,Kt as h,L as g,Lt as _,Mt as v,N as y,Nt as b,Ot as x,P as S,Pt as C,Q as w,Qt as T,R as E,Rt as ee,S as te,St as D,T as ne,Tt as O,U as re,V as k,Vt as A,Wt as ie,Xt as ae,Yt as oe,Zt as se,_t as ce,a as le,at as ue,d as de,dt as j,en as fe,ft as pe,ht as me,i as he,it as ge,j as _e,jt as M,kt as ve,lt as ye,m as be,mt as xe,o as Se,ot as Ce,p as we,qt as Te,s as Ee,st as De,t as Oe,tn as ke,tt as Ae,ut as je,vt as Me,w as Ne,wt as Pe,x as Fe,xt as N,yt as Ie,z as Le,zt as Re}from"./sleep-OHCt3UoV.mjs";import{$ as ze,$a as Be,$i as Ve,$n as He,$o as Ue,$r as We,$s as Ge,$t as Ke,A as qe,Aa as Je,Ai as Ye,An as Xe,Ao as Ze,Ar as Qe,As as $e,At as et,B as tt,Ba as nt,Bi as rt,Bn as it,Bo as at,Br as ot,Bs as st,Bt as ct,C as lt,Ca as ut,Ci as dt,Cn as ft,Co as pt,Cr as mt,Cs as ht,Ct as gt,D as _t,Da as vt,Di as yt,Dn as bt,Do as xt,Dr as St,Ds as Ct,Dt as wt,E as Tt,Ea as Et,Ei as Dt,En as Ot,Eo as kt,Er as At,Es as jt,Et as Mt,F as Nt,Fa as Pt,Fi as Ft,Fn as It,Fo as Lt,Fr as Rt,Fs as zt,Ft as Bt,Ga as Vt,Gi as Ht,Gn as Ut,Go as Wt,Gr as Gt,Gs as Kt,Gt as qt,H as Jt,Ha as Yt,Hi as Xt,Hn as Zt,Ho as Qt,Hr as $t,Hs as en,Ht as tn,I as nn,Ia as rn,Ii as an,In as on,Io as sn,Ir as cn,Is as ln,It as un,J as dn,Ja as fn,Ji as pn,Jn as mn,Jo as hn,Jr as gn,Js as _n,Jt as vn,K as yn,Ka as bn,Ki as xn,Kn as Sn,Ko as Cn,Kr as wn,Ks as Tn,Kt as En,L as Dn,La as On,Li as kn,Ln as An,Lr as jn,Ls as Mn,M as Nn,Ma as Pn,Mi as eee,Mn as tee,Mo as Fn,Mr as In,Ms as Ln,Mt as Rn,N as zn,Na as Bn,Ni as nee,Nn as ree,No as iee,Nr as aee,Nt as Vn,O as Hn,Oa as Un,Oi as Wn,On as Gn,Oo as Kn,Or as qn,Os as Jn,Ot as Yn,P as Xn,Pa as Zn,Pi as Qn,Pn as $n,Po as er,Pr as oee,Ps as tr,Pt as see,Q as nr,Qa as rr,Qi as ir,Qn as cee,Qr as ar,Qs as or,Qt as lee,R as sr,Ra as cr,Ri as lr,Rn as ur,Ro as dr,Rr as fr,Rs as pr,S as mr,Sa as hr,Si as gr,Sn as _r,So as vr,Sr as yr,Ss as br,St as xr,T as Sr,Ta as Cr,Ti as wr,Tn as uee,To as dee,Tr as fee,Ts as Tr,Tt as Er,U as Dr,Ua as Or,Ui as kr,Un as pee,Ur as mee,Us as Ar,Ut as jr,V as Mr,Va as Nr,Vi as Pr,Vn as Fr,Vr as Ir,Vt as Lr,Wa as Rr,Wi as zr,Wn as Br,Wr as Vr,Ws as Hr,Wt as Ur,X as Wr,Xa as Gr,Xi as Kr,Xn as qr,Xo as Jr,Xr as Yr,Xs as Xr,Xt as Zr,Y as Qr,Ya as $r,Yi as ei,Yn as ti,Yr as ni,Ys as ri,Yt as ii,Z as ai,Za as oi,Zi as si,Zn as ci,Zo as li,Zr as ui,Zs as di,Zt as hee,_ as fi,_a as gee,_c as pi,_i as mi,_n as _ee,_o as hi,_r as vee,_s as gi,_t as _i,a as vi,aa as yi,ai as bi,an as yee,ao as xi,ar as Si,as as Ci,at as wi,b as Ti,ba as bee,bi as xee,bn as See,bo as Cee,br as Ei,bt as Di,c as Oi,ca as ki,ci as Ai,cn as ji,co as Mi,cr as Ni,cs as Pi,ct as Fi,d as Ii,da as Li,dc as Ri,di as zi,dn as Bi,do as Vi,dr as Hi,ds as Ui,dt as Wi,ea as Gi,ec as Ki,ei as qi,en as Ji,eo as Yi,er as Xi,es as Zi,et as Qi,f as $i,fa as ea,fc as ta,fi as na,fn as ra,fo as ia,fr as aa,fs as oa,ft as sa,g as ca,ga as la,gi as ua,gn as da,go as wee,gr as Tee,gt as fa,h as pa,ha as ma,hi as Eee,hn as ha,ho as Dee,hr as Oee,hs as ga,ht as _a,i as va,ia as ya,ic as ba,ii as xa,in as kee,ir as Sa,is as Ca,j as wa,ja as Aee,ji as Ta,jn as jee,jo as Mee,jr as Nee,js as Ea,jt as Da,k as Oa,ka as Pee,ki as ka,kn as Fee,ko as Iee,kr as Lee,ks as Aa,kt as ja,l as Ma,la as Na,li as Pa,ln as Ree,lo as Fa,lr as zee,ls as Ia,lt as La,m as Ra,ma as za,mc as Ba,mi as Va,mn as Ha,mo as Ua,mr as Wa,ms as Ga,mt as Ka,n as qa,na as Ja,nc as Ya,ni as Xa,nn as Za,no as Qa,nr as $a,ns as eo,nt as to,o as no,oa as ro,oi as io,on as ao,oo,or as so,os as co,ot as lo,p as uo,pa as fo,pc as po,pi as mo,pn as ho,pr as go,pt as _o,q as vo,qa as yo,qi as bo,qn as xo,qo as So,qr as Co,qs as wo,qt as To,r as Eo,ra as Do,rc as Oo,ri as ko,rn as Ao,ro as jo,rr as Mo,rs as No,s as Po,sa as Fo,si as Io,sn as Bee,so as Lo,sr as Vee,st as Ro,t as zo,ta as Bo,ti as Hee,tn as Uee,to as Vo,tr as Wee,tt as Ho,u as Uo,ua as Wo,ui as Gee,un as Kee,uo as Go,ur as qee,us as Ko,ut as qo,v as Jo,va as Jee,vi as Yee,vn as Xee,vo as Zee,vr as Yo,vs as Xo,vt as Zo,w as Qo,wa as Qee,wi as $o,wn as $ee,wo as ete,wr as tte,wt as es,x as ts,xa as nte,xi as ns,xn as rs,xo as rte,xr as ite,xs as is,xt as as,y as os,ya as ss,yi as ate,yn as ote,yo as cs,yr as ste,ys as ls,yt as us,z as ds,za as cte,zi as fs,zn as lte,zo as ps,zr as ms,zs as hs,zt as gs}from"./src-DQgEWrUq.mjs";import{c as _s,i as vs,l as ys,n as bs,s as xs}from"./esm-DxvI2ZVA.mjs";import{n as Ss,t as Cs}from"./md-manager-Q1tI0hzy.mjs";import{A as ws,C as Ts,E as Es,I as Ds,M as Os,O as ks,P as As,S as js,T as Ms,_ as Ns,a as Ps,b as Fs,c as Is,d as Ls,f as Rs,g as zs,h as Bs,i as Vs,j as Hs,k as Us,l as Ws,m as Gs,n as Ks,o as qs,p as Js,r as Ys,s as Xs,t as Zs,u as Qs,v as $s,w as ec,x as tc,y as nc}from"./fs-traced-uUie5siN.mjs";import{D as rc,E as ic,S as ac,T as oc,a as sc,b as cc,l as lc,p as uc,r as P,s as dc,x as fc,y as pc}from"./logger-DFxEUjvj.mjs";import{a as mc,i as hc,o as gc,r as _c,s as vc,t as yc}from"./git-handle-BI3zkVk-.mjs";import{C as bc,S as xc,_ as Sc,a as Cc,b as wc,c as Tc,f as Ec,g as Dc,h as Oc,i as kc,l as Ac,n as jc,p as Mc,r as Nc,u as Pc,x as Fc}from"./server-lock-C-cXu0qQ.mjs";import{t as Ic}from"./libesm-DzwC_yFw.mjs";import{t as Lc}from"./yazl-DZr4PyKA.mjs";import{n as Rc,t as zc}from"./build-CJW5ggp6.mjs";import{t as Bc}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Vc,c as Hc,d as Uc,f as Wc,h as Gc,i as Kc,l as qc,m as Jc,n as Yc,o as Xc,p as Zc,r as Qc,s as $c,t as el,u as tl}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as nl,B as rl,C as il,D as al,E as ol,F as sl,H as cl,I as ll,L as ul,M as dl,N as fl,O as pl,P as ml,S as hl,T as gl,V as _l,_ as vl,a as yl,b as bl,c as xl,d as Sl,f as Cl,g as wl,h as Tl,i as El,j as Dl,k as Ol,l as kl,m as Al,n as jl,o as Ml,p as Nl,r as Pl,s as Fl,t as Il,u as Ll,v as Rl,w as zl,x as Bl,y as Vl,z as Hl}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Ul,c as Wl,d as Gl,i as Kl,l as ql,n as Jl,o as Yl,r as Xl,s as Zl,t as Ql,u as $l}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as eu,r as tu,t as nu}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as ru}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as iu}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as au,t as ou}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as su,t as cu}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as lu,r as uu,t as du}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as fu,t as pu}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as mu}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as hu}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as gu}from"./wrapper-BcpqREsI.mjs";import{createRequire as _u}from"node:module";import{execFile as vu,execFileSync as yu,spawn as bu,spawnSync as xu}from"node:child_process";import*as Su from"node:path";import{basename as Cu,delimiter as wu,dirname as F,extname as Tu,isAbsolute as Eu,join as I,normalize as Du,parse as Ou,posix as ku,relative as L,resolve as R,sep as z,win32 as Au}from"node:path";import{URLSearchParams as ju,fileURLToPath as Mu,pathToFileURL as Nu}from"node:url";import*as Pu from"node:fs";import{appendFileSync as Fu,chmodSync as Iu,closeSync as Lu,constants as Ru,createReadStream as zu,createWriteStream as Bu,existsSync as B,fstatSync as ute,lstatSync as Vu,mkdirSync as Hu,mkdtempSync as Uu,openSync as Wu,opendirSync as Gu,readFile as dte,readFileSync as V,readSync as Ku,readdirSync as qu,readlinkSync as Ju,realpathSync as H,renameSync as Yu,rmSync as Xu,rmdirSync as Zu,statSync as Qu,unlinkSync as $u,writeFileSync as ed,writeSync as fte}from"node:fs";import{arch as td,availableParallelism as pte,homedir as nd,hostname as rd,platform as id,tmpdir as ad}from"node:os";import{access as od,chmod as mte,constants as sd,lstat as cd,readFile as ld,readdir as ud,realpath as dd,stat as fd,writeFile as hte}from"node:fs/promises";import{Readable as pd,Transform as gte,Writable as _te}from"node:stream";import md,{createHash as hd,randomUUID as gd,webcrypto as _d}from"node:crypto";import vte from"crypto";import{Readable as vd}from"stream";import{EventEmitter as yte}from"node:events";import{Worker as bte}from"node:worker_threads";import{monitorEventLoopDelay as xte,performance as yd}from"node:perf_hooks";import{createInterface as Ste}from"node:readline";import{pipeline as bd}from"node:stream/promises";import{setImmediate as Cte,setTimeout as xd}from"node:timers/promises";import{promisify as Sd}from"node:util";import{request as wte}from"node:http";import{Http2ServerRequest as Cd,constants as Tte}from"node:http2";import{lookup as Ete}from"node:dns/promises";import{request as Dte}from"node:https";import{createBrotliDecompress as Ote,createGunzip as kte,createInflate as Ate}from"node:zlib";import{Http2ServerRequest as wd,constants as jte}from"http2";import{AsyncLocalStorage as Mte}from"node:async_hooks";import{lookup as Nte}from"node:dns";import Pte from"node:tls";function Fte(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Ite(n)}function Ite(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 Td=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=V(I(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Eu(t)?t:R(this.gitDir,t))}catch(e){if(!kd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=V(I(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return kd(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]}:jd(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=V(I(t.path,`config`),`utf-8`)}catch(e){return kd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Lte(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Ad(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=R(t.path,e),r=L(t.path,n);if(r.startsWith(`..`)||Eu(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Bte(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!kd(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(I(t.path,`packed-refs`),`utf-8`)}catch(e){return kd(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 jd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Ed(e){return Od(R(e),``)}function Dd(e){let t=R(e),n=R(nd());if(t===n)return{kind:`absent`};let r=Od(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=F(i);if(e===i||e===n)return{kind:`absent`};let r=Od(e,L(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Od(e,t){let n=I(e,`.git`),r;try{r=Qu(n)}catch(e){return kd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Td(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=V(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Eu(o)?o:R(e,o);try{if(!Qu(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Td(`linked`,e,t,n,s)}}function Lte(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Rte(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=zte(i[1]);if(a.length>0)return a}return null}function Rte(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function zte(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function kd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Ad(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Bte(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Ad(t[1])?{kind:`symbolic`,target:t[1]}:null:jd(e)?{kind:`oid`,oid:e}:null}function jd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}const Md=`ok-generator`;function Vte(e){return`git-author-${Rn(e.trim().toLowerCase())}`}const Hte=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service|ok-generator)$/;function Nd(e){let t=Dd(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 Pd(e){let t=Nd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function Fd(e){let t=Nd(e);switch(t.kind){case`directory`:return R(t.path,Id(t.projectSubPath));case`linked`:if(!B(t.path))throw new Ld(t.gitPath,t.path);return R(t.path,Id(t.projectSubPath));case`malformed-pointer`:throw new Ld(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Rd(t.gitPath,{cause:t.cause});case`absent`:return R(e,`.git/ok`)}}function Id(e){return e===``?`ok`:`ok-${Ute(e)}`}function Ute(e){let t=e.split(z).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Wte(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Wte(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var Ld=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}},Rd=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 Gte(e){let t;try{t=Fd(e)}catch(e){if(e instanceof Ld||e instanceof Rd)return null;throw e}return B(R(t,`HEAD`))?t:null}function zd(e){return`refs/wip/${e}/`}function Kte(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 Bd=`ok-actor: `;function Vd(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),`${Bd}${JSON.stringify(i)}`}function Hd(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=qte(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 qte(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 Jte(e){if(!e)return null;for(let t of e.split(`
|
|
3
3
|
`)){let e=t.trim();if(!e.startsWith(Bd))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:Hd(n)}return null}function Ud(e){if(!e)return[];let t=[];for(let n of e.split(`
|
|
4
|
-
`)){let e=n.trim();if(!e.startsWith(Bd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=Hd(r);i&&t.push(i)}return t}function Wd(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 Gd(e){let t=Ud(e);return t.length>0?t.map(Wd):Kte(e)}function Kd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function qd(e){return`reconcile: ${e}`}function Jd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Yd(e,t){return`park: ${e} -> ${t}`}function Xd(e,t){return`rename: ${e} -> ${t}`}function Zd(e){return`checkpoint: ${e}`}function Qd(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const $d=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function ef(e){return e.replace($d,` `)}function tf(e,t){let n=ef(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=ef(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 nf(e){return Hte.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}:e===`ok-generator`?{id:e,classification:`classified-ok-generator`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function rf(e){let t=Nd(e);if(t.kind!==`linked`)return R(e);try{let n=V(I(t.path,`commondir`),`utf-8`).trim();return n===``?R(e):R(F(R(t.path,n)),t.projectSubPath)}catch{return R(e)}}function af(e){return e.kind??`other`}function of(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var sf=class{filePath;log;grants=null;constructor(e,t){this.filePath=I(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=af(t),i=of(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=af(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-BEuPZxxL.mjs`);await e(I(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(V(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const cf=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],lf={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},uf=`acp-agents.json`,df=`acp-registry-cache.json`;function ff(){let e=id(),t=td(),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}`}const pf=new Set([`goose`,`fast-agent`,`crow-cli`]);function mf(e,t){let n=t.trim();return n.length===0?e:pf.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function hf(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 gf(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(hf).map(e=>({...e,name:mf(e.id,e.name)})):null}var _f=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=gf(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-BEuPZxxL.mjs`);await e(this.localDir,{recursive:!0}),await n(I(this.localDir,df),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=gf(await ld(I(this.localDir,df),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function vf(e,t){let n;try{n=await ld(I(e,uf),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${uf} 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 ${uf} entry`)}return i}const U={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`},yf={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`},bf={cancel_request:`$/cancel_request`},xf=Symbol(`skippedItem`);function W(e,t){return e.catch(t)}function Sf(e,t){let n=e.catch(t);return _().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),ke):n.parse(e))}function Cf(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function wf(e,t,n){return e.superRefine((e,r)=>{let i=Cf(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 Tf(e,t,n){return _().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return ke}let o=a.data,s=Cf(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 Ef(e){return N(e.catch(xf)).transform(e=>e.filter(e=>e!==xf))}const Df=p([i(),u()]).nullable(),Of=u(),kf=M({sessionId:Of,path:u(),content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Af=M({sessionId:Of,path:u(),line:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jf=u(),Mf=p([x(`read`),x(`edit`),x(`delete`),x(`move`),x(`search`),x(`execute`),x(`think`),x(`fetch`),x(`switch_mode`),x(`other`)]),Nf=p([x(`pending`),x(`in_progress`),x(`completed`),x(`failed`)]),Pf=M({audience:W(Ef(p([x(`assistant`),x(`user`)])).nullish(),()=>void 0),lastModified:W(u().nullish(),()=>void 0),priority:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ff=M({annotations:W(Pf.nullish(),()=>void 0),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),If=M({annotations:W(Pf.nullish(),()=>void 0),data:u(),mimeType:u(),uri:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lf=M({annotations:W(Pf.nullish(),()=>void 0),data:u(),mimeType:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rf=M({annotations:W(Pf.nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),mimeType:W(u().nullish(),()=>void 0),name:u(),size:W(i().nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zf=p([M({mimeType:W(u().nullish(),()=>void 0),text:u(),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),M({blob:u(),mimeType:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})]),Bf=M({annotations:W(Pf.nullish(),()=>void 0),resource:zf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vf=p([Ff.and(M({type:x(`text`)})),If.and(M({type:x(`image`)})),Lf.and(M({type:x(`audio`)})),Rf.and(M({type:x(`resource_link`)})),Bf.and(M({type:x(`resource`)}))]),Hf=M({content:Vf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Uf=M({path:u(),oldText:W(u().nullish(),()=>void 0),newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wf=u(),Gf=M({terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kf=p([Hf.and(M({type:x(`content`)})),Uf.and(M({type:x(`diff`)})),Gf.and(M({type:x(`terminal`)}))]),qf=M({path:u(),line:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jf=M({toolCallId:jf,kind:W(Mf.nullish(),()=>void 0),status:W(Nf.nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),content:W(Ef(Kf).nullish(),()=>void 0),locations:W(Ef(qf).nullish(),()=>void 0),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yf=u(),Xf=p([x(`allow_once`),x(`allow_always`),x(`reject_once`),x(`reject_always`)]),Zf=M({sessionId:Of,toolCall:Jf,options:N(M({optionId:Yf,name:u(),kind:Xf,_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qf=M({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$f=M({sessionId:Of,command:u(),args:W(Ef(u()).optional(),()=>[]),env:W(Ef(Qf).optional(),()=>[]),cwd:W(u().nullish(),()=>void 0),outputByteLimit:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ep=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tp=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),np=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),rp=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ip=M({sessionId:Of,toolCallId:W(jf.nullish(),()=>void 0)}),ap=M({requestId:Df}),op=x(`object`),sp=p([x(`email`),x(`uri`),x(`date`),x(`date-time`)]),cp=M({const:u(),title:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minLength:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:u().nullish(),format:sp.nullish(),default:W(u().nullish(),()=>void 0),enum:N(u()).nullish(),oneOf:N(cp).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),up=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),dp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),fp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),default:W(D().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pp=M({enum:N(u()),_meta:W(C(u(),_()).nullish(),()=>void 0)}),mp=M({anyOf:N(cp),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hp=Tf(p([pp.and(M({type:x(`string`)})),wf(M({type:u()}),`type`,[`string`]),mp]),`type`,[`string`]),gp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minItems:i().nullish(),maxItems:i().nullish(),items:hp,default:W(Ef(u()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_p=Tf(p([lp.and(M({type:x(`string`)})),up.and(M({type:x(`number`)})),dp.and(M({type:x(`integer`)})),fp.and(M({type:x(`boolean`)})),gp.and(M({type:x(`array`)})),wf(M({type:u()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),vp=M({type:W(op.optional().default(`object`),()=>`object`),title:W(u().nullish(),()=>void 0),properties:C(u(),_p).optional().default({}),required:N(u()).nullish(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yp=c(p([ip,ap]),M({requestedSchema:vp})),bp=u(),xp=c(p([ip,ap]),M({elicitationId:bp,url:ee()})),Sp=Tf(c(p([yp.and(M({mode:x(`form`)})),xp.and(M({mode:x(`url`)})),wf(c(p([ip,ap]),M({mode:u()})),`mode`,[`form`,`url`])]),M({message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Cp=u(),wp=M({serverId:Cp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tp=u(),Ep=M({connectionId:Tp,method:u(),params:C(u(),_()).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dp=M({connectionId:Tp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Op=_();M({id:Df,method:u(),params:p([kf,Af,Zf,$f,ep,tp,np,rp,Sp,wp,Ep,Dp,Op]).nullish()});const kp=O().gte(0).lte(65535),Ap=M({image:W(D().optional().default(!1),()=>!1),audio:W(D().optional().default(!1),()=>!1),embeddedContext:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jp=M({http:W(D().optional().default(!1),()=>!1),sse:W(D().optional().default(!1),()=>!1),acp:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Np=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ip=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rp=M({list:W(Mp.nullish(),()=>void 0),delete:W(Np.nullish(),()=>void 0),additionalDirectories:W(Pp.nullish(),()=>void 0),fork:W(Fp.nullish(),()=>void 0),resume:W(Ip.nullish(),()=>void 0),close:W(Lp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yte=M({logout:W(M({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xte=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zte=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qte=M({syncKind:p([x(`full`),x(`incremental`)]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$te=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ene=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),tne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),nne=M({document:W(M({didOpen:W(Zte.nullish(),()=>void 0),didChange:W(Qte.nullish(),()=>void 0),didClose:W($te.nullish(),()=>void 0),didSave:W(ene.nullish(),()=>void 0),didFocus:W(tne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rne=M({maxCount:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ine=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ane=M({maxCount:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),one=M({maxCount:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),sne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),cne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),lne=M({recentFiles:W(rne.nullish(),()=>void 0),relatedSnippets:W(ine.nullish(),()=>void 0),editHistory:W(ane.nullish(),()=>void 0),userActions:W(one.nullish(),()=>void 0),openFiles:W(sne.nullish(),()=>void 0),diagnostics:W(cne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),une=M({events:W(nne.nullish(),()=>void 0),context:W(lne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zp=p([x(`utf-16`),x(`utf-32`),x(`utf-8`)]),dne=M({loadSession:W(D().optional().default(!1),()=>!1),promptCapabilities:W(Ap.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(jp.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(Rp.optional().default({}),()=>({})),auth:W(Yte.optional().default({}),()=>({})),providers:W(Xte.nullish(),()=>void 0),nes:W(une.nullish(),()=>void 0),positionEncoding:W(zp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bp=u(),fne=M({name:u(),label:W(u().nullish(),()=>void 0),secret:W(D().optional().default(!0),()=>!0),optional:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pne=M({id:Bp,name:u(),description:W(u().nullish(),()=>void 0),vars:Sf(Ef(fne),()=>[]),link:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),mne=M({id:Bp,name:u(),description:W(u().nullish(),()=>void 0),args:W(Ef(u()).optional(),()=>[]),env:W(C(u(),u()).optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hne=M({id:Bp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),gne=p([pne.and(M({type:x(`env_var`)})),mne.and(M({type:x(`terminal`)})),hne]),Vp=M({name:u(),title:W(u().nullish(),()=>void 0),version:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_ne=M({protocolVersion:kp,agentCapabilities:W(dne.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:W(Ef(gne).optional().default([]),()=>[]),agentInfo:W(Vp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hp=u(),Up=p([x(`anthropic`),x(`openai`),x(`azure`),x(`vertex`),x(`bedrock`),u()]),yne=M({apiType:Up,baseUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bne=M({providers:N(M({providerId:Hp,supported:Sf(Ef(Up),()=>[]),required:D(),current:yne.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),xne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wp=u(),Gp=M({currentModeId:Wp,availableModes:Sf(Ef(M({id:Wp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kp=u(),wne=p([x(`mode`),x(`model`),x(`model_config`),x(`thought_level`),u()]),qp=u(),Jp=M({value:qp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tne=M({group:u(),name:u(),options:Sf(Ef(Jp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ene=M({currentValue:qp,options:p([N(Jp),N(Tne)])}),Dne=M({currentValue:D()}),Yp=c(p([Ene.and(M({type:x(`select`)})),Dne.and(M({type:x(`boolean`)}))]),M({id:Kp,name:u(),description:W(u().nullish(),()=>void 0),category:W(wne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),One=M({sessionId:Of,modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),kne=M({modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ane=M({sessions:Sf(Ef(M({sessionId:Of,cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mne=M({sessionId:Of,modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nne=M({modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ine=M({configOptions:Sf(Ef(Yp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lne=M({stopReason:p([x(`end_turn`),x(`max_tokens`),x(`max_turn_requests`),x(`refusal`),x(`cancelled`)]),usage:W(M({totalTokens:i(),inputTokens:i(),outputTokens:i(),thoughtTokens:W(i().nullish(),()=>void 0),cachedReadTokens:W(i().nullish(),()=>void 0),cachedWriteTokens:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rne=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xp=u(),Zp=M({line:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qp=M({start:Zp,end:Zp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),zne=M({range:Qp,newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bne=M({id:Xp,uri:u(),edits:N(zne),cursorPosition:W(Zp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vne=M({id:Xp,uri:u(),position:Zp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hne=M({id:Xp,uri:u(),position:Zp,newName:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Une=M({id:Xp,uri:u(),search:u(),replace:u(),isRegex:D().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wne=M({suggestions:N(p([Bne.and(M({kind:x(`edit`)})),Vne.and(M({kind:x(`jump`)})),Hne.and(M({kind:x(`rename`)})),Une.and(M({kind:x(`searchAndReplace`)}))])),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),$p=_(),em=_(),tm=M({code:p([x(-32700),x(-32600),x(-32601),x(-32602),x(-32603),x(-32800),x(-32e3),x(-32002),O().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:u(),data:W(_().optional(),()=>void 0)});p([M({id:Df,result:p([_ne,vne,bne,xne,Sne,Cne,One,kne,Ane,jne,Mne,Nne,Pne,Fne,Ine,Lne,Rne,Wne,Gne,$p,em])}),M({id:Df,error:tm})]);const nm=M({content:Vf,messageId:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kne=M({toolCallId:jf,title:u(),kind:W(Mf.optional(),()=>void 0),status:W(Nf.optional(),()=>void 0),content:W(Ef(Kf).optional(),()=>[]),locations:W(Ef(qf).optional(),()=>[]),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qne=p([x(`high`),x(`medium`),x(`low`)]),Jne=p([x(`pending`),x(`in_progress`),x(`completed`)]),rm=M({content:u(),priority:qne,status:Jne,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yne=M({entries:Sf(Ef(rm),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),im=u(),Xne=M({planId:im,entries:Sf(Ef(rm),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zne=M({planId:im,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qne=M({planId:im,content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$ne=M({plan:p([Xne.and(M({type:x(`items`)})),Zne.and(M({type:x(`file`)})),Qne.and(M({type:x(`markdown`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ere=M({planId:im,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tre=M({hint:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),nre=M({availableCommands:Sf(Ef(M({name:u(),description:u(),input:W(tre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rre=M({currentModeId:Wp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ire=M({configOptions:Sf(Ef(Yp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),are=M({title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ore=M({amount:i(),currency:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),sre=M({used:i(),size:i(),cost:W(ore.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),am=M({sessionId:Of,update:p([nm.and(M({sessionUpdate:x(`user_message_chunk`)})),nm.and(M({sessionUpdate:x(`agent_message_chunk`)})),nm.and(M({sessionUpdate:x(`agent_thought_chunk`)})),Kne.and(M({sessionUpdate:x(`tool_call`)})),Jf.and(M({sessionUpdate:x(`tool_call_update`)})),Yne.and(M({sessionUpdate:x(`plan`)})),$ne.and(M({sessionUpdate:x(`plan_update`)})),ere.and(M({sessionUpdate:x(`plan_removed`)})),nre.and(M({sessionUpdate:x(`available_commands_update`)})),rre.and(M({sessionUpdate:x(`current_mode_update`)})),ire.and(M({sessionUpdate:x(`config_option_update`)})),are.and(M({sessionUpdate:x(`session_info_update`)})),sre.and(M({sessionUpdate:x(`usage_update`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),om=M({elicitationId:bp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),sm=M({connectionId:Tp,method:u(),params:W(C(u(),_()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cm=_();M({method:u(),params:p([am,om,sm,cm]).nullish()});const cre=M({readTextFile:W(D().optional().default(!1),()=>!1),writeTextFile:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lre=M({configOptions:W(M({boolean:W(M({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ure=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),dre=M({terminal:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),fre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),pre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),mre=M({form:W(fre.nullish(),()=>void 0),url:W(pre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),gre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),_re=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),vre=M({jump:W(hre.nullish(),()=>void 0),rename:W(gre.nullish(),()=>void 0),searchAndReplace:W(_re.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lm=M({protocolVersion:kp,clientCapabilities:W(M({fs:W(cre.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(D().optional().default(!1),()=>!1),session:W(lre.nullish(),()=>void 0),plan:W(ure.nullish(),()=>void 0),auth:W(dre.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(mre.nullish(),()=>void 0),nes:W(vre.nullish(),()=>void 0),positionEncodings:W(Ef(zp).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:W(Vp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),um=M({methodId:Bp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),dm=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),fm=M({providerId:Hp,apiType:Up,baseUrl:u(),headers:C(u(),u()).optional(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pm=M({providerId:Hp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),mm=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),hm=M({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yre=M({name:u(),url:u(),headers:N(hm),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bre=M({name:u(),url:u(),headers:N(hm),_meta:W(C(u(),_()).nullish(),()=>void 0)}),xre=M({name:u(),serverId:Cp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sre=M({name:u(),command:u(),args:N(u()),env:N(Qf),_meta:W(C(u(),_()).nullish(),()=>void 0)}),gm=p([yre.and(M({type:x(`http`)})),bre.and(M({type:x(`sse`)})),xre.and(M({type:x(`acp`)})),Sre]),_m=M({cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),mcpServers:Sf(Ef(gm),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vm=M({mcpServers:Sf(Ef(gm),()=>[]),cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ym=M({cwd:u().nullish(),cursor:u().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bm=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),xm=M({sessionId:Of,cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),mcpServers:W(Ef(gm).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sm=M({sessionId:Of,cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),mcpServers:W(Ef(gm).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cm=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),wm=M({sessionId:Of,modeId:Wp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tm=c(p([M({value:D(),type:x(`boolean`)}),M({value:qp})]),M({sessionId:Of,configId:Kp,_meta:W(C(u(),_()).nullish(),()=>void 0)})),Em=M({sessionId:Of,prompt:N(Vf),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cre=M({uri:u(),name:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wre=M({name:u(),owner:u(),remoteUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dm=M({workspaceUri:W(u().nullish(),()=>void 0),workspaceFolders:N(Cre).nullish(),repository:W(wre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tre=p([x(`automatic`),x(`diagnostic`),x(`manual`)]),Ere=M({uri:u(),languageId:u(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dre=M({startLine:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ore=M({uri:u(),excerpts:N(Dre),_meta:W(C(u(),_()).nullish(),()=>void 0)}),kre=M({uri:u(),diff:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Are=M({action:u(),uri:u(),position:Zp,timestampMs:i(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jre=M({uri:u(),languageId:u(),visibleRange:W(Qp.nullish(),()=>void 0),lastFocusedMs:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mre=p([x(`error`),x(`warning`),x(`information`),x(`hint`)]),Nre=M({uri:u(),range:Qp,severity:Mre,message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pre=M({recentFiles:N(Ere).nullish(),relatedSnippets:N(Ore).nullish(),editHistory:N(kre).nullish(),userActions:N(Are).nullish(),openFiles:N(jre).nullish(),diagnostics:N(Nre).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Om=M({sessionId:Of,uri:u(),version:i(),position:Zp,selection:Qp.nullish(),triggerKind:Tre,context:Pre.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),km=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)});M({id:Df,method:u(),params:p([lm,um,dm,fm,pm,mm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Ep,Op]).nullish()});const Fre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ire=M({content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lre=M({optionId:Yf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rre=M({outcome:p([M({outcome:x(`cancelled`)}),Lre.and(M({outcome:x(`selected`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zre=M({terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bre=M({exitCode:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vre=M({output:u(),truncated:D(),exitStatus:W(Bre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ure=M({exitCode:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gre=p([u(),i(),i(),D(),N(u())]),Am=M({content:C(u(),Gre).nullish()});p([M({id:Df,result:p([Fre,Ire,Rre,zre,Vre,Hre,Ure,Wre,Tf(c(p([Am.and(M({action:x(`accept`)})),M({action:x(`decline`)}),M({action:x(`cancel`)}),wf(M({action:u()}),`action`,[`accept`,`cancel`,`decline`])]),M({_meta:W(C(u(),_()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),M({connectionId:Tp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),em,$p])}),M({id:Df,error:tm})]);const jm=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mm=M({sessionId:Of,uri:u(),languageId:u(),version:i(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kre=M({range:Qp.nullish(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nm=M({sessionId:Of,uri:u(),version:i(),contentChanges:Sf(Ef(Kre),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pm=M({sessionId:Of,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fm=M({sessionId:Of,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Im=M({sessionId:Of,uri:u(),version:i(),position:Zp,visibleRange:Qp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lm=M({sessionId:Of,id:Xp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rm=M({sessionId:Of,id:Xp,reason:W(p([x(`rejected`),x(`ignored`),x(`replaced`),x(`cancelled`)]).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)});M({method:u(),params:p([jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,sm,cm]).nullish()}),M({requestId:Df,_meta:W(C(u(),_()).nullish(),()=>void 0)}),yp.and(M({mode:x(`form`)})).and(M({message:u()})),xp.and(M({mode:x(`url`)})).and(M({message:u()})),p([ip,ap]).and(M({message:u()})),lp.and(M({type:x(`string`)})),up.and(M({type:x(`number`)})),dp.and(M({type:x(`integer`)})),fp.and(M({type:x(`boolean`)})),gp.and(M({type:x(`array`)})),pp.and(M({type:x(`string`)})),Am.and(M({action:x(`accept`)})),M({action:x(`decline`)}),M({action:x(`cancel`)});const zm=`$/cancel_request`;function Bm(e){return typeof e==`object`&&!!e}function qre(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Jre(e){if(!(!Bm(e)||!qre(e.requestId)))return e.requestId}const Vm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Hm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Yre(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Xre(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 Um(e){if(e instanceof Km)return e.toResult();if(Xre(e))return Km.invalidParams(e.format()).toResult();let t=Yre(e);try{return Km.internalError(t?JSON.parse(t):{}).toResult()}catch{return Km.internalError({details:t}).toResult()}}function Zre(e){return e instanceof Km&&e.code===-32800?e:Km.requestCancelled(e)}function Qre(e,t){let n=$re(e,t);return n?n.toResult():Um(e)}function $re(e,t){if(!(!t.aborted||!eie(e)))return Zre(t.reason)}function eie(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var tie=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 Km?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Hm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Wm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},nie=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}},Gm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new nie(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 rie}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 Wm(()=>{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 Hm(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(zm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Hm(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 Vm.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(!Bm(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(Km.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Qre(n,t.responder.signal));else{let t=Um(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 tie(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&&Bm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new Km(n,r,i))}else t.reject(Km.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==zm)return;let t=Jre(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(Km.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?Hm(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)}},rie=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)??Vm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?Vm.no(r):await n(t(r.params),r.responder,i)??Vm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?Vm.no(r):await n(t(r.params),i)??Vm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Gm(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},Km=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}}},iie=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 aie(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new iie,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);Bm(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(Bd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=Hd(r);i&&t.push(i)}return t}function Wd(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 Gd(e){let t=Ud(e);return t.length>0?t.map(Wd):Kte(e)}function Kd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function qd(e){return`reconcile: ${e}`}function Jd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Yd(e,t){return`park: ${e} -> ${t}`}function Xd(e,t){return`rename: ${e} -> ${t}`}function Zd(e){return`checkpoint: ${e}`}function Qd(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const $d=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function ef(e){return e.replace($d,` `)}function tf(e,t){let n=ef(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=ef(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 nf(e){return Hte.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}:e===`ok-generator`?{id:e,classification:`classified-ok-generator`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function rf(e){let t=Nd(e);if(t.kind!==`linked`)return R(e);try{let n=V(I(t.path,`commondir`),`utf-8`).trim();return n===``?R(e):R(F(R(t.path,n)),t.projectSubPath)}catch{return R(e)}}function af(e){return e.kind??`other`}function of(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var sf=class{filePath;log;grants=null;constructor(e,t){this.filePath=I(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=af(t),i=of(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=af(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-DN8Ne6OV.mjs`);await e(I(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(V(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const cf=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],lf={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},uf=`acp-agents.json`,df=`acp-registry-cache.json`;function ff(){let e=id(),t=td(),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}`}const pf=new Set([`goose`,`fast-agent`,`crow-cli`]);function mf(e,t){let n=t.trim();return n.length===0?e:pf.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function hf(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 gf(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(hf).map(e=>({...e,name:mf(e.id,e.name)})):null}var _f=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=gf(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-DN8Ne6OV.mjs`);await e(this.localDir,{recursive:!0}),await n(I(this.localDir,df),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=gf(await ld(I(this.localDir,df),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function vf(e,t){let n;try{n=await ld(I(e,uf),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${uf} 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 ${uf} entry`)}return i}const U={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`},yf={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`},bf={cancel_request:`$/cancel_request`},xf=Symbol(`skippedItem`);function W(e,t){return e.catch(t)}function Sf(e,t){let n=e.catch(t);return _().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),ke):n.parse(e))}function Cf(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function wf(e,t,n){return e.superRefine((e,r)=>{let i=Cf(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 Tf(e,t,n){return _().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return ke}let o=a.data,s=Cf(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 Ef(e){return N(e.catch(xf)).transform(e=>e.filter(e=>e!==xf))}const Df=p([i(),u()]).nullable(),Of=u(),kf=M({sessionId:Of,path:u(),content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Af=M({sessionId:Of,path:u(),line:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jf=u(),Mf=p([x(`read`),x(`edit`),x(`delete`),x(`move`),x(`search`),x(`execute`),x(`think`),x(`fetch`),x(`switch_mode`),x(`other`)]),Nf=p([x(`pending`),x(`in_progress`),x(`completed`),x(`failed`)]),Pf=M({audience:W(Ef(p([x(`assistant`),x(`user`)])).nullish(),()=>void 0),lastModified:W(u().nullish(),()=>void 0),priority:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ff=M({annotations:W(Pf.nullish(),()=>void 0),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),If=M({annotations:W(Pf.nullish(),()=>void 0),data:u(),mimeType:u(),uri:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lf=M({annotations:W(Pf.nullish(),()=>void 0),data:u(),mimeType:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rf=M({annotations:W(Pf.nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),mimeType:W(u().nullish(),()=>void 0),name:u(),size:W(i().nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zf=p([M({mimeType:W(u().nullish(),()=>void 0),text:u(),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),M({blob:u(),mimeType:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})]),Bf=M({annotations:W(Pf.nullish(),()=>void 0),resource:zf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vf=p([Ff.and(M({type:x(`text`)})),If.and(M({type:x(`image`)})),Lf.and(M({type:x(`audio`)})),Rf.and(M({type:x(`resource_link`)})),Bf.and(M({type:x(`resource`)}))]),Hf=M({content:Vf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Uf=M({path:u(),oldText:W(u().nullish(),()=>void 0),newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wf=u(),Gf=M({terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kf=p([Hf.and(M({type:x(`content`)})),Uf.and(M({type:x(`diff`)})),Gf.and(M({type:x(`terminal`)}))]),qf=M({path:u(),line:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jf=M({toolCallId:jf,kind:W(Mf.nullish(),()=>void 0),status:W(Nf.nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),content:W(Ef(Kf).nullish(),()=>void 0),locations:W(Ef(qf).nullish(),()=>void 0),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yf=u(),Xf=p([x(`allow_once`),x(`allow_always`),x(`reject_once`),x(`reject_always`)]),Zf=M({sessionId:Of,toolCall:Jf,options:N(M({optionId:Yf,name:u(),kind:Xf,_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qf=M({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$f=M({sessionId:Of,command:u(),args:W(Ef(u()).optional(),()=>[]),env:W(Ef(Qf).optional(),()=>[]),cwd:W(u().nullish(),()=>void 0),outputByteLimit:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ep=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tp=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),np=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),rp=M({sessionId:Of,terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ip=M({sessionId:Of,toolCallId:W(jf.nullish(),()=>void 0)}),ap=M({requestId:Df}),op=x(`object`),sp=p([x(`email`),x(`uri`),x(`date`),x(`date-time`)]),cp=M({const:u(),title:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minLength:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:u().nullish(),format:sp.nullish(),default:W(u().nullish(),()=>void 0),enum:N(u()).nullish(),oneOf:N(cp).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),up=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),dp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),fp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),default:W(D().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pp=M({enum:N(u()),_meta:W(C(u(),_()).nullish(),()=>void 0)}),mp=M({anyOf:N(cp),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hp=Tf(p([pp.and(M({type:x(`string`)})),wf(M({type:u()}),`type`,[`string`]),mp]),`type`,[`string`]),gp=M({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minItems:i().nullish(),maxItems:i().nullish(),items:hp,default:W(Ef(u()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_p=Tf(p([lp.and(M({type:x(`string`)})),up.and(M({type:x(`number`)})),dp.and(M({type:x(`integer`)})),fp.and(M({type:x(`boolean`)})),gp.and(M({type:x(`array`)})),wf(M({type:u()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),vp=M({type:W(op.optional().default(`object`),()=>`object`),title:W(u().nullish(),()=>void 0),properties:C(u(),_p).optional().default({}),required:N(u()).nullish(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yp=c(p([ip,ap]),M({requestedSchema:vp})),bp=u(),xp=c(p([ip,ap]),M({elicitationId:bp,url:ee()})),Sp=Tf(c(p([yp.and(M({mode:x(`form`)})),xp.and(M({mode:x(`url`)})),wf(c(p([ip,ap]),M({mode:u()})),`mode`,[`form`,`url`])]),M({message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Cp=u(),wp=M({serverId:Cp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tp=u(),Ep=M({connectionId:Tp,method:u(),params:C(u(),_()).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dp=M({connectionId:Tp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Op=_();M({id:Df,method:u(),params:p([kf,Af,Zf,$f,ep,tp,np,rp,Sp,wp,Ep,Dp,Op]).nullish()});const kp=O().gte(0).lte(65535),Ap=M({image:W(D().optional().default(!1),()=>!1),audio:W(D().optional().default(!1),()=>!1),embeddedContext:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jp=M({http:W(D().optional().default(!1),()=>!1),sse:W(D().optional().default(!1),()=>!1),acp:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Np=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ip=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lp=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rp=M({list:W(Mp.nullish(),()=>void 0),delete:W(Np.nullish(),()=>void 0),additionalDirectories:W(Pp.nullish(),()=>void 0),fork:W(Fp.nullish(),()=>void 0),resume:W(Ip.nullish(),()=>void 0),close:W(Lp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yte=M({logout:W(M({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xte=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zte=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qte=M({syncKind:p([x(`full`),x(`incremental`)]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$te=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ene=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),tne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),nne=M({document:W(M({didOpen:W(Zte.nullish(),()=>void 0),didChange:W(Qte.nullish(),()=>void 0),didClose:W($te.nullish(),()=>void 0),didSave:W(ene.nullish(),()=>void 0),didFocus:W(tne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rne=M({maxCount:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ine=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ane=M({maxCount:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),one=M({maxCount:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),sne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),cne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),lne=M({recentFiles:W(rne.nullish(),()=>void 0),relatedSnippets:W(ine.nullish(),()=>void 0),editHistory:W(ane.nullish(),()=>void 0),userActions:W(one.nullish(),()=>void 0),openFiles:W(sne.nullish(),()=>void 0),diagnostics:W(cne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),une=M({events:W(nne.nullish(),()=>void 0),context:W(lne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zp=p([x(`utf-16`),x(`utf-32`),x(`utf-8`)]),dne=M({loadSession:W(D().optional().default(!1),()=>!1),promptCapabilities:W(Ap.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(jp.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(Rp.optional().default({}),()=>({})),auth:W(Yte.optional().default({}),()=>({})),providers:W(Xte.nullish(),()=>void 0),nes:W(une.nullish(),()=>void 0),positionEncoding:W(zp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bp=u(),fne=M({name:u(),label:W(u().nullish(),()=>void 0),secret:W(D().optional().default(!0),()=>!0),optional:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pne=M({id:Bp,name:u(),description:W(u().nullish(),()=>void 0),vars:Sf(Ef(fne),()=>[]),link:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),mne=M({id:Bp,name:u(),description:W(u().nullish(),()=>void 0),args:W(Ef(u()).optional(),()=>[]),env:W(C(u(),u()).optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hne=M({id:Bp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),gne=p([pne.and(M({type:x(`env_var`)})),mne.and(M({type:x(`terminal`)})),hne]),Vp=M({name:u(),title:W(u().nullish(),()=>void 0),version:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_ne=M({protocolVersion:kp,agentCapabilities:W(dne.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:W(Ef(gne).optional().default([]),()=>[]),agentInfo:W(Vp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hp=u(),Up=p([x(`anthropic`),x(`openai`),x(`azure`),x(`vertex`),x(`bedrock`),u()]),yne=M({apiType:Up,baseUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bne=M({providers:N(M({providerId:Hp,supported:Sf(Ef(Up),()=>[]),required:D(),current:yne.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),xne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wp=u(),Gp=M({currentModeId:Wp,availableModes:Sf(Ef(M({id:Wp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kp=u(),wne=p([x(`mode`),x(`model`),x(`model_config`),x(`thought_level`),u()]),qp=u(),Jp=M({value:qp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tne=M({group:u(),name:u(),options:Sf(Ef(Jp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ene=M({currentValue:qp,options:p([N(Jp),N(Tne)])}),Dne=M({currentValue:D()}),Yp=c(p([Ene.and(M({type:x(`select`)})),Dne.and(M({type:x(`boolean`)}))]),M({id:Kp,name:u(),description:W(u().nullish(),()=>void 0),category:W(wne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),One=M({sessionId:Of,modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),kne=M({modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ane=M({sessions:Sf(Ef(M({sessionId:Of,cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mne=M({sessionId:Of,modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nne=M({modes:W(Gp.nullish(),()=>void 0),configOptions:W(Ef(Yp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ine=M({configOptions:Sf(Ef(Yp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lne=M({stopReason:p([x(`end_turn`),x(`max_tokens`),x(`max_turn_requests`),x(`refusal`),x(`cancelled`)]),usage:W(M({totalTokens:i(),inputTokens:i(),outputTokens:i(),thoughtTokens:W(i().nullish(),()=>void 0),cachedReadTokens:W(i().nullish(),()=>void 0),cachedWriteTokens:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rne=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xp=u(),Zp=M({line:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qp=M({start:Zp,end:Zp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),zne=M({range:Qp,newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bne=M({id:Xp,uri:u(),edits:N(zne),cursorPosition:W(Zp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vne=M({id:Xp,uri:u(),position:Zp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hne=M({id:Xp,uri:u(),position:Zp,newName:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Une=M({id:Xp,uri:u(),search:u(),replace:u(),isRegex:D().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wne=M({suggestions:N(p([Bne.and(M({kind:x(`edit`)})),Vne.and(M({kind:x(`jump`)})),Hne.and(M({kind:x(`rename`)})),Une.and(M({kind:x(`searchAndReplace`)}))])),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gne=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),$p=_(),em=_(),tm=M({code:p([x(-32700),x(-32600),x(-32601),x(-32602),x(-32603),x(-32800),x(-32e3),x(-32002),O().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:u(),data:W(_().optional(),()=>void 0)});p([M({id:Df,result:p([_ne,vne,bne,xne,Sne,Cne,One,kne,Ane,jne,Mne,Nne,Pne,Fne,Ine,Lne,Rne,Wne,Gne,$p,em])}),M({id:Df,error:tm})]);const nm=M({content:Vf,messageId:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kne=M({toolCallId:jf,title:u(),kind:W(Mf.optional(),()=>void 0),status:W(Nf.optional(),()=>void 0),content:W(Ef(Kf).optional(),()=>[]),locations:W(Ef(qf).optional(),()=>[]),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qne=p([x(`high`),x(`medium`),x(`low`)]),Jne=p([x(`pending`),x(`in_progress`),x(`completed`)]),rm=M({content:u(),priority:qne,status:Jne,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yne=M({entries:Sf(Ef(rm),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),im=u(),Xne=M({planId:im,entries:Sf(Ef(rm),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zne=M({planId:im,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qne=M({planId:im,content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$ne=M({plan:p([Xne.and(M({type:x(`items`)})),Zne.and(M({type:x(`file`)})),Qne.and(M({type:x(`markdown`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ere=M({planId:im,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tre=M({hint:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),nre=M({availableCommands:Sf(Ef(M({name:u(),description:u(),input:W(tre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rre=M({currentModeId:Wp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ire=M({configOptions:Sf(Ef(Yp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),are=M({title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ore=M({amount:i(),currency:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),sre=M({used:i(),size:i(),cost:W(ore.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),am=M({sessionId:Of,update:p([nm.and(M({sessionUpdate:x(`user_message_chunk`)})),nm.and(M({sessionUpdate:x(`agent_message_chunk`)})),nm.and(M({sessionUpdate:x(`agent_thought_chunk`)})),Kne.and(M({sessionUpdate:x(`tool_call`)})),Jf.and(M({sessionUpdate:x(`tool_call_update`)})),Yne.and(M({sessionUpdate:x(`plan`)})),$ne.and(M({sessionUpdate:x(`plan_update`)})),ere.and(M({sessionUpdate:x(`plan_removed`)})),nre.and(M({sessionUpdate:x(`available_commands_update`)})),rre.and(M({sessionUpdate:x(`current_mode_update`)})),ire.and(M({sessionUpdate:x(`config_option_update`)})),are.and(M({sessionUpdate:x(`session_info_update`)})),sre.and(M({sessionUpdate:x(`usage_update`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),om=M({elicitationId:bp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),sm=M({connectionId:Tp,method:u(),params:W(C(u(),_()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cm=_();M({method:u(),params:p([am,om,sm,cm]).nullish()});const cre=M({readTextFile:W(D().optional().default(!1),()=>!1),writeTextFile:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lre=M({configOptions:W(M({boolean:W(M({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ure=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),dre=M({terminal:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),fre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),pre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),mre=M({form:W(fre.nullish(),()=>void 0),url:W(pre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),gre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),_re=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),vre=M({jump:W(hre.nullish(),()=>void 0),rename:W(gre.nullish(),()=>void 0),searchAndReplace:W(_re.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lm=M({protocolVersion:kp,clientCapabilities:W(M({fs:W(cre.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(D().optional().default(!1),()=>!1),session:W(lre.nullish(),()=>void 0),plan:W(ure.nullish(),()=>void 0),auth:W(dre.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(mre.nullish(),()=>void 0),nes:W(vre.nullish(),()=>void 0),positionEncodings:W(Ef(zp).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:W(Vp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),um=M({methodId:Bp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),dm=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),fm=M({providerId:Hp,apiType:Up,baseUrl:u(),headers:C(u(),u()).optional(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pm=M({providerId:Hp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),mm=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),hm=M({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yre=M({name:u(),url:u(),headers:N(hm),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bre=M({name:u(),url:u(),headers:N(hm),_meta:W(C(u(),_()).nullish(),()=>void 0)}),xre=M({name:u(),serverId:Cp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sre=M({name:u(),command:u(),args:N(u()),env:N(Qf),_meta:W(C(u(),_()).nullish(),()=>void 0)}),gm=p([yre.and(M({type:x(`http`)})),bre.and(M({type:x(`sse`)})),xre.and(M({type:x(`acp`)})),Sre]),_m=M({cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),mcpServers:Sf(Ef(gm),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vm=M({mcpServers:Sf(Ef(gm),()=>[]),cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ym=M({cwd:u().nullish(),cursor:u().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bm=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),xm=M({sessionId:Of,cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),mcpServers:W(Ef(gm).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sm=M({sessionId:Of,cwd:u(),additionalDirectories:W(Ef(u()).optional(),()=>[]),mcpServers:W(Ef(gm).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cm=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),wm=M({sessionId:Of,modeId:Wp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tm=c(p([M({value:D(),type:x(`boolean`)}),M({value:qp})]),M({sessionId:Of,configId:Kp,_meta:W(C(u(),_()).nullish(),()=>void 0)})),Em=M({sessionId:Of,prompt:N(Vf),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cre=M({uri:u(),name:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wre=M({name:u(),owner:u(),remoteUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dm=M({workspaceUri:W(u().nullish(),()=>void 0),workspaceFolders:N(Cre).nullish(),repository:W(wre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tre=p([x(`automatic`),x(`diagnostic`),x(`manual`)]),Ere=M({uri:u(),languageId:u(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dre=M({startLine:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ore=M({uri:u(),excerpts:N(Dre),_meta:W(C(u(),_()).nullish(),()=>void 0)}),kre=M({uri:u(),diff:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Are=M({action:u(),uri:u(),position:Zp,timestampMs:i(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jre=M({uri:u(),languageId:u(),visibleRange:W(Qp.nullish(),()=>void 0),lastFocusedMs:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mre=p([x(`error`),x(`warning`),x(`information`),x(`hint`)]),Nre=M({uri:u(),range:Qp,severity:Mre,message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pre=M({recentFiles:N(Ere).nullish(),relatedSnippets:N(Ore).nullish(),editHistory:N(kre).nullish(),userActions:N(Are).nullish(),openFiles:N(jre).nullish(),diagnostics:N(Nre).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Om=M({sessionId:Of,uri:u(),version:i(),position:Zp,selection:Qp.nullish(),triggerKind:Tre,context:Pre.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),km=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)});M({id:Df,method:u(),params:p([lm,um,dm,fm,pm,mm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Ep,Op]).nullish()});const Fre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ire=M({content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lre=M({optionId:Yf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rre=M({outcome:p([M({outcome:x(`cancelled`)}),Lre.and(M({outcome:x(`selected`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zre=M({terminalId:Wf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bre=M({exitCode:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vre=M({output:u(),truncated:D(),exitStatus:W(Bre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ure=M({exitCode:W(O().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wre=M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gre=p([u(),i(),i(),D(),N(u())]),Am=M({content:C(u(),Gre).nullish()});p([M({id:Df,result:p([Fre,Ire,Rre,zre,Vre,Hre,Ure,Wre,Tf(c(p([Am.and(M({action:x(`accept`)})),M({action:x(`decline`)}),M({action:x(`cancel`)}),wf(M({action:u()}),`action`,[`accept`,`cancel`,`decline`])]),M({_meta:W(C(u(),_()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),M({connectionId:Tp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),M({_meta:W(C(u(),_()).nullish(),()=>void 0)}),em,$p])}),M({id:Df,error:tm})]);const jm=M({sessionId:Of,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mm=M({sessionId:Of,uri:u(),languageId:u(),version:i(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kre=M({range:Qp.nullish(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nm=M({sessionId:Of,uri:u(),version:i(),contentChanges:Sf(Ef(Kre),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pm=M({sessionId:Of,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fm=M({sessionId:Of,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Im=M({sessionId:Of,uri:u(),version:i(),position:Zp,visibleRange:Qp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lm=M({sessionId:Of,id:Xp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rm=M({sessionId:Of,id:Xp,reason:W(p([x(`rejected`),x(`ignored`),x(`replaced`),x(`cancelled`)]).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)});M({method:u(),params:p([jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,sm,cm]).nullish()}),M({requestId:Df,_meta:W(C(u(),_()).nullish(),()=>void 0)}),yp.and(M({mode:x(`form`)})).and(M({message:u()})),xp.and(M({mode:x(`url`)})).and(M({message:u()})),p([ip,ap]).and(M({message:u()})),lp.and(M({type:x(`string`)})),up.and(M({type:x(`number`)})),dp.and(M({type:x(`integer`)})),fp.and(M({type:x(`boolean`)})),gp.and(M({type:x(`array`)})),pp.and(M({type:x(`string`)})),Am.and(M({action:x(`accept`)})),M({action:x(`decline`)}),M({action:x(`cancel`)});const zm=`$/cancel_request`;function Bm(e){return typeof e==`object`&&!!e}function qre(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Jre(e){if(!(!Bm(e)||!qre(e.requestId)))return e.requestId}const Vm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Hm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Yre(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Xre(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 Um(e){if(e instanceof Km)return e.toResult();if(Xre(e))return Km.invalidParams(e.format()).toResult();let t=Yre(e);try{return Km.internalError(t?JSON.parse(t):{}).toResult()}catch{return Km.internalError({details:t}).toResult()}}function Zre(e){return e instanceof Km&&e.code===-32800?e:Km.requestCancelled(e)}function Qre(e,t){let n=$re(e,t);return n?n.toResult():Um(e)}function $re(e,t){if(!(!t.aborted||!eie(e)))return Zre(t.reason)}function eie(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var tie=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 Km?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Hm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Wm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},nie=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}},Gm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new nie(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 rie}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 Wm(()=>{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 Hm(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(zm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Hm(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 Vm.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(!Bm(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(Km.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Qre(n,t.responder.signal));else{let t=Um(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 tie(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&&Bm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new Km(n,r,i))}else t.reject(Km.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==zm)return;let t=Jre(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(Km.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?Hm(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)}},rie=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)??Vm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?Vm.no(r):await n(t(r.params),r.responder,i)??Vm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?Vm.no(r):await n(t(r.params),i)??Vm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Gm(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},Km=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}}},iie=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 aie(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new iie,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);Bm(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 qm(e){return e??{}}function oie(e){return typeof e==`object`&&!!e&&`readable`in e&&`writable`in e}function sie(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}const Jm={agent:{initialize:U.initialize,authenticate:U.authenticate,logout:U.logout,providers:{list:U.providers_list,set:U.providers_set,disable:U.providers_disable},session:{new:U.session_new,load:U.session_load,list:U.session_list,delete:U.session_delete,fork:U.session_fork,resume:U.session_resume,close:U.session_close,setMode:U.session_set_mode,setConfigOption:U.session_set_config_option,prompt:U.session_prompt,cancel:U.session_cancel},nes:{start:U.nes_start,suggest:U.nes_suggest,accept:U.nes_accept,reject:U.nes_reject,close:U.nes_close},document:{didOpen:U.document_did_open,didChange:U.document_did_change,didClose:U.document_did_close,didSave:U.document_did_save,didFocus:U.document_did_focus}},client:{session:{requestPermission:yf.session_request_permission,update:yf.session_update},fs:{writeTextFile:yf.fs_write_text_file,readTextFile:yf.fs_read_text_file},terminal:{create:yf.terminal_create,output:yf.terminal_output,release:yf.terminal_release,waitForExit:yf.terminal_wait_for_exit,kill:yf.terminal_kill},elicitation:{create:yf.elicitation_create,complete:yf.elicitation_complete}},protocol:{cancelRequest:bf.cancel_request}},Ym=Symbol(`startActiveSession`);var Xm=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)}},cie=class e extends Xm{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}request(e,t,n){let r=ah[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},Zm=class e extends Xm{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}[Ym](e,t){return this.sendRequest(U.session_new,e,e=>this.attachSession(e),t)}buildSession(e){return typeof e==`string`?eh.create(this,{cwd:e,mcpServers:[]}):eh.create(this,e)}attachSession(e){let t=new pie,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error(`ACP connection closed`))};n.aborted?r():n.addEventListener(`abort`,r);let i=sh(this.connectionContext).attach(e,t),a=new Wm(()=>{n.removeEventListener(`abort`,r)});return mie.create(this,e,t,[i,a])}request(e,t,n){let r=xie[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},Qm=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)}},lie=class extends Qm{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=cie.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,ch(this,this.connectHandlers))}},uie=class extends Qm{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=Zm.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,ch(this,this.connectHandlers))}};function die(e,t=[]){return new lie(e,t)}function fie(e,t=[]){return new uie(e,t)}var pie=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 $m(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}var eh=class e{cx;request;constructor(e,t){this.cx=e,this.request=$m(t)}static create(t,n){return new e(t,n)}toRequest(){return $m(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[Ym](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},mie=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(U.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 th(e,t){return e?typeof e==`function`?e(t):e.parse(t):t}function nh(e,t,n){return{method:e,params:t,mapResponse:n}}function rh(e,t){return{method:e,params:t}}function hie(e,t,n,r){e.onReceiveRequest(t.method,e=>th(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 gie(e,t,n,r){e.onReceiveNotification(t.method,e=>th(t.params,e),(e,t)=>r(n(e,t,t.signal)))}function ih(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}const _ie={initialize:nh(U.initialize,lm),newSession:nh(U.session_new,_m),loadSession:nh(U.session_load,vm,qm),unstable_forkSession:nh(U.session_fork,xm),listSessions:nh(U.session_list,ym),deleteSession:nh(U.session_delete,bm,qm),resumeSession:nh(U.session_resume,Sm),closeSession:nh(U.session_close,Cm,qm),setSessionMode:nh(U.session_set_mode,wm,qm),setSessionConfigOption:nh(U.session_set_config_option,Tm),authenticate:nh(U.authenticate,um,qm),unstable_listProviders:nh(U.providers_list,dm),unstable_setProvider:nh(U.providers_set,fm,qm),unstable_disableProvider:nh(U.providers_disable,pm,qm),logout:nh(U.logout,mm,qm),prompt:nh(U.session_prompt,Em),unstable_startNes:nh(U.nes_start,Dm),unstable_suggestNes:nh(U.nes_suggest,Om),unstable_closeNes:nh(U.nes_close,km,qm)},vie={cancel:rh(U.session_cancel,jm),unstable_didOpenDocument:rh(U.document_did_open,Mm),unstable_didChangeDocument:rh(U.document_did_change,Nm),unstable_didCloseDocument:rh(U.document_did_close,Pm),unstable_didSaveDocument:rh(U.document_did_save,Fm),unstable_didFocusDocument:rh(U.document_did_focus,Im),unstable_acceptNes:rh(U.nes_accept,Lm),unstable_rejectNes:rh(U.nes_reject,Rm)},yie={requestPermission:nh(yf.session_request_permission,Zf),writeTextFile:nh(yf.fs_write_text_file,kf,qm),readTextFile:nh(yf.fs_read_text_file,Af),createTerminal:nh(yf.terminal_create,$f),terminalOutput:nh(yf.terminal_output,ep),releaseTerminal:nh(yf.terminal_release,tp,qm),waitForTerminalExit:nh(yf.terminal_wait_for_exit,np),killTerminal:nh(yf.terminal_kill,rp,qm),unstable_createElicitation:nh(yf.elicitation_create,Sp)},bie={sessionUpdate:rh(yf.session_update,am),unstable_completeElicitation:rh(yf.elicitation_complete,om)},xie=ih(_ie);ih(vie);const ah=ih(yie),Sie=ih(bie);function Cie(e,t,n,r){return{params:e,requestId:r,signal:n,agent:t}}function wie(e,t,n){return{params:e,signal:n,agent:t}}var Tie=class{activeSessions=new Map;handleMessage(e){if(e.kind!==`notification`||e.method!==yf.session_update)return Vm.no(e);let t=am.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 Vm.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 Wm(()=>{n.delete(t),n.size===0&&this.activeSessions.delete(e.sessionId)})}};const oh=new WeakMap;function sh(e){let t=oh.get(e);return t||(t=new Tie,oh.set(e,t)),t}function ch(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 lh=Symbol(`appBuilder`),Eie=Symbol(`runAgentConnectHandlers`),uh=Symbol(`runClientConnectHandlers`);function Die(e){return new Oie(e)}var Oie=class{builder=Gm.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(e,t)=>sh(t).handleMessage(e),describe:()=>`client-session-update-router`})}[lh](){return this.builder}[uh](e){ch(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=ah[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=Sie[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 hie(this.builder,e,(e,t,n,r)=>Cie(e,Zm.create(t,r),n,r),t),this}notification(e,t){return gie(this.builder,e,(e,t,n)=>wie(e,Zm.create(t),n),t),this}connectConnection(e){if(oie(e)){let t=this.openStreamConnection(e);return this[uh](t.connection),t}let[t,n]=sie(),r=e[lh]().connect(n),i=die(r),a=this.openStreamConnection(t);a.rawConnection.closed.then(()=>i.close()),r.closed.then(()=>a.connection.close());try{e[Eie](i),this[uh](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:fie(t,this.connectHandlers)}}};new Set([U.initialize,U.authenticate,U.providers_list,U.providers_set,U.providers_disable,U.session_new,U.session_load,U.session_set_mode,U.session_set_config_option,U.session_prompt,U.session_list,U.session_delete,U.session_fork,U.session_resume,U.session_close,U.logout,U.nes_start,U.nes_suggest,U.nes_close]),new Set([U.session_cancel,U.nes_accept,U.nes_reject,U.document_did_open,U.document_did_change,U.document_did_close,U.document_did_save,U.document_did_focus]),new Set([yf.session_request_permission,yf.fs_write_text_file,yf.fs_read_text_file,yf.terminal_create,yf.terminal_output,yf.terminal_release,yf.terminal_wait_for_exit,yf.terminal_kill,yf.elicitation_create]),new Set([yf.session_update,yf.elicitation_complete]);function dh(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const fh=/^[a-zA-Z0-9_-]+$/,kie=64;function ph(e){return typeof e!=`string`||e.length===0||e.length>64||!fh.test(e)?null:e}function mh(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function hh(e){return!e.startsWith(`principal-`)}function gh(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 _h(e){let t=ph(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:mh(t),displayName:typeof e.agentName==`string`?dh(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?dh(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?dh(e.clientVersion):void 0,label:typeof e.label==`string`?dh(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}function vh(e){let t=So(e);return t.frontmatter===``?t:Io(hn(t.frontmatter)).map===null?{frontmatter:``,body:e}:t}const yh=()=>new Map,bh=e=>{let t=yh();return e.forEach((e,n)=>{t.set(n,e)}),t},xh=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},Aie=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Sh=()=>new Set,Ch=e=>e[e.length-1],jie=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},wh=Array.from,Mie=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},Th=Array.isArray;var Eh=class{constructor(){this._observers=yh()}on(e,t){return xh(this._observers,e,Sh).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 wh((this._observers.get(e)||yh()).values()).forEach(e=>e(...t))}destroy(){this._observers=yh()}};const Dh=Math.floor,Oh=Math.abs,kh=(e,t)=>e<t?e:t,Ah=(e,t)=>e>t?e:t;Number.isNaN;const jh=e=>e===0?1/e<0:e<0,Mh=2**53-1,Nie=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&Dh(e)===e);Number.isNaN,Number.parseInt;const Nh=String.fromCharCode;String.fromCodePoint,Nh(65535);const Pie=e=>e.toLowerCase(),Fie=/^\s*/g,Iie=e=>e.replace(Fie,``),Ph=/([A-Z])/g,Fh=(e,t)=>Iie(e.replace(Ph,e=>`${t}${Pie(e)}`)),Ih=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},Lh=typeof TextEncoder<`u`?new TextEncoder:null,Rh=Lh?e=>Lh.encode(e):Ih;let zh=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});zh&&zh.decode(new Uint8Array).length===1&&(zh=null);var Bh=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Vh=()=>new Bh,Hh=e=>{let t=Vh();return e(t),Wh(t)},Uh=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Wh=e=>{let t=new Uint8Array(Uh(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},Gh=(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(Ah(n,t)*2),e.cpos=0)},Kh=(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},qh=Kh,Jh=(e,t)=>{for(;t>127;)Kh(e,128|127&t),t=Dh(t/128);Kh(e,127&t)},Yh=(e,t)=>{let n=jh(t);for(n&&(t=-t),Kh(e,(t>63?128:0)|(n?64:0)|63&t),t=Dh(t/64);t>0;)Kh(e,(t>127?128:0)|127&t),t=Dh(t/128)},Xh=new Uint8Array(3e4),Zh=Xh.length/3,Qh=Lh&&Lh.encodeInto?(e,t)=>{if(t.length<Zh){let n=Lh.encodeInto(t,Xh).written||0;Jh(e,n);for(let t=0;t<n;t++)Kh(e,Xh[t])}else eg(e,Rh(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Jh(e,r);for(let t=0;t<r;t++)Kh(e,n.codePointAt(t))},$h=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=kh(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(Ah(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},eg=(e,t)=>{Jh(e,t.byteLength),$h(e,t)},tg=(e,t)=>{Gh(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},ng=(e,t)=>tg(e,4).setFloat32(0,t,!1),rg=(e,t)=>tg(e,8).setFloat64(0,t,!1),ig=(e,t)=>tg(e,8).setBigInt64(0,t,!1),ag=new DataView(new ArrayBuffer(4)),og=e=>(ag.setFloat32(0,e),ag.getFloat32(0)===e),sg=(e,t)=>{switch(typeof t){case`string`:Kh(e,119),Qh(e,t);break;case`number`:Nie(t)&&Oh(t)<=2147483647?(Kh(e,125),Yh(e,t)):og(t)?(Kh(e,124),ng(e,t)):(Kh(e,123),rg(e,t));break;case`bigint`:Kh(e,122),ig(e,t);break;case`object`:if(t===null)Kh(e,126);else if(Th(t)){Kh(e,117),Jh(e,t.length);for(let n=0;n<t.length;n++)sg(e,t[n])}else if(t instanceof Uint8Array)Kh(e,116),eg(e,t);else{Kh(e,118);let n=Object.keys(t);Jh(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Qh(e,i),sg(e,t[i])}}break;case`boolean`:Kh(e,t?120:121);break;default:Kh(e,127)}};var cg=class extends Bh{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Jh(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const lg=e=>{e.count>0&&(Yh(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Jh(e.encoder,e.count-2))};var ug=class{constructor(){this.encoder=new Bh,this.s=0,this.count=0}write(e){this.s===e?this.count++:(lg(this),this.count=1,this.s=e)}toUint8Array(){return lg(this),Wh(this.encoder)}};const dg=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Yh(e.encoder,t),e.count>1&&Jh(e.encoder,e.count-2)}};var fg=class{constructor(){this.encoder=new Bh,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(dg(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return dg(this),Wh(this.encoder)}},pg=class{constructor(){this.sarr=[],this.s=``,this.lensE=new ug}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 Bh;return this.sarr.push(this.s),this.s=``,Qh(e,this.sarr.join(``)),$h(e,this.lensE.toUint8Array()),Wh(e)}};const mg=e=>Error(e),hg=()=>{throw mg(`Method unimplemented`)},gg=()=>{throw mg(`Unexpected case`)},_g=mg(`Unexpected end of array`),vg=mg(`Integer out of Range`);var yg=class{constructor(e){this.arr=e,this.pos=0}};const bg=e=>new yg(e),xg=e=>e.pos!==e.arr.length,Sg=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Cg=e=>Sg(e,Tg(e)),wg=e=>e.arr[e.pos++],Tg=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>Mh)throw vg}throw _g},Eg=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>Mh)throw vg}throw _g},Dg=zh?e=>zh.decode(Cg(e)):e=>{let t=Tg(e);if(t===0)return``;{let n=String.fromCodePoint(wg(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(wg(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))}},Og=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},kg=[e=>void 0,e=>null,Eg,e=>Og(e,4).getFloat32(0,!1),e=>Og(e,8).getFloat64(0,!1),e=>Og(e,8).getBigInt64(0,!1),e=>!1,e=>!0,Dg,e=>{let t=Tg(e),n={};for(let r=0;r<t;r++){let t=Dg(e);n[t]=Ag(e)}return n},e=>{let t=Tg(e),n=[];for(let r=0;r<t;r++)n.push(Ag(e));return n},Cg],Ag=e=>kg[127-wg(e)](e);var jg=class extends yg{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),xg(this)?this.count=Tg(this)+1:this.count=-1),this.count--,this.s}},Mg=class extends yg{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Eg(this);let e=jh(this.s);this.count=1,e&&(this.s=-this.s,this.count=Tg(this)+2)}return this.count--,this.s}},Ng=class extends yg{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=Eg(this),t=e&1;this.diff=Dh(e/2),this.count=1,t&&(this.count=Tg(this)+2)}return this.s+=this.diff,this.count--,this.s}},Pg=class{constructor(e){this.decoder=new Mg(e),this.str=Dg(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}};_d.subtle;const Fg=_d.getRandomValues.bind(_d),Ig=()=>Fg(new Uint32Array(1))[0],Lg=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^Ig()&15>>e/4).toString(16)),Rg=Date.now,zg=e=>new Promise(e);Promise.all.bind(Promise);const Bg=e=>e===void 0?null:e;let Vg=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&&(Vg=localStorage)}catch{}const Hg=Vg,Ug=Symbol(`Equality`),Wg=(e,t)=>e===t||!!e?.[Ug]?.(t)||!1,Gg=Object.assign,Kg=Object.keys,qg=(e,t)=>{for(let n in e)t(e[n],n)},Jg=e=>Kg(e).length,Yg=e=>{for(let t in e)return!1;return!0},Xg=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Zg=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Qg=(e,t)=>e===t||Jg(e)===Jg(t)&&Xg(e,(e,n)=>(e!==void 0||Zg(t,n))&&Wg(t[n],e)),$g=Object.freeze,e_=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&e_(e[t])}return $g(e)},t_=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&t_(e,t,n+1)}},n_=e=>e,r_=(e,t)=>t.includes(e),i_=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,a_=typeof window<`u`&&typeof document<`u`&&!i_;typeof navigator<`u`&&/Mac/.test(navigator.platform);let o_;const s_=[],c_=()=>{if(o_===void 0)if(i_){o_=yh();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&o_.set(t,``),t=r):t===null?s_.push(r):(o_.set(t,r),t=null)}t!==null&&o_.set(t,``)}else typeof location==`object`?(o_=yh(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);o_.set(`--${Fh(t,`-`)}`,n),o_.set(`-${Fh(t,`-`)}`,n)}})):o_=yh();return o_},l_=e=>c_().has(e),u_=e=>Bg(i_?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:Hg.getItem(e)),d_=e=>l_(`--`+e)||u_(e)!==null;d_(`production`);const f_=i_&&r_(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!l_(`--no-colors`)&&!d_(`no-color`)&&(!i_||process.stdout.isTTY)&&(!i_||l_(`--color`)||u_(`COLORTERM`)!==null||(u_(`TERM`)||``).includes(`color`)),p_=e=>new Uint8Array(e),m_=a_?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=Nh(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),h_=e=>{let t=p_(e.byteLength);return t.set(e),t},g_=e=>Hh(t=>sg(t,e)),__=Symbol,v_=__(),y_=__(),b_=__(),x_=__(),S_=__(),C_=__(),w_=__(),T_=__(),E_=__(),D_=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};Rg();const O_={[v_]:`\x1B[1m`,[y_]:`\x1B[2m`,[b_]:`\x1B[34m`,[S_]:`\x1B[32m`,[x_]:`\x1B[37m`,[C_]:`\x1B[31m`,[w_]:`\x1B[35m`,[T_]:`\x1B[38;5;208m`,[E_]:`\x1B[0m`},k_=f_?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=O_[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}:D_,A_=(...e)=>{console.log(...k_(e))},j_=(...e)=>{console.warn(...k_(e))},M_=e=>({[Symbol.iterator](){return this},next:e}),N_=(e,t)=>M_(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),P_=(e,t)=>M_(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var F_=class{constructor(e,t){this.clock=e,this.len=t}},I_=class{constructor(){this.clients=new Map}};const L_=(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])Jv(e,i,o.clock,o.len,n)}}),R_=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=Dh((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},z_=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&R_(n,t.clock)!==null},B_=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 F_(r.clock,Ah(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},V_=e=>{let t=new I_;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++)jie(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return B_(t),t},H_=(e,t,n,r)=>{xh(e.clients,t,()=>[]).push(new F_(n,r))},U_=()=>new I_,W_=e=>{let t=U_();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 F_(i,a))}}r.length>0&&t.clients.set(n,r)}),t},G_=(e,t)=>{Jh(e.restEncoder,t.clients.size),wh(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Jh(e.restEncoder,t);let r=n.length;Jh(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},K_=e=>{let t=new I_,n=Tg(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=Tg(e.restDecoder),r=Tg(e.restDecoder);if(r>0){let i=xh(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new F_(e.readDsClock(),e.readDsLen()))}}return t},q_=(e,t,n)=>{let r=new I_,i=Tg(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=Tg(e.restDecoder),a=Tg(e.restDecoder),o=n.clients.get(i)||[],s=Vv(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&H_(r,i,s,a-s);let e=Uv(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,lb(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,lb(t,c,a-c.id.clock)),c.delete(t))}else H_(r,i,n,a-n)}}if(r.clients.size>0){let e=new iv;return Jh(e.restEncoder,0),G_(e,r),e.toUint8Array()}return null},J_=(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},Y_=Ig;var X_=class e extends Eh{constructor({guid:e=Lg(),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=Y_(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new zv,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=zg(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>zg(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&&$v(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(wh(this.subdocs).map(e=>e.guid))}transact(e,t=null){return $v(this,e,t)}get(e,t=gy){let n=xh(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==gy&&r!==t)if(r===gy){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,My)}getText(e=``){return this.get(e,Ky)}getMap(e=``){return this.get(e,Ny)}getXmlElement(e=``){return this.get(e,Yy)}getXmlFragment(e=``){return this.get(e,Jy)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,wh(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,$v(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()}},Z_=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Tg(this.restDecoder)}readDsLen(){return Tg(this.restDecoder)}},Q_=class extends Z_{readLeftID(){return kv(Tg(this.restDecoder),Tg(this.restDecoder))}readRightID(){return kv(Tg(this.restDecoder),Tg(this.restDecoder))}readClient(){return Tg(this.restDecoder)}readInfo(){return wg(this.restDecoder)}readString(){return Dg(this.restDecoder)}readParentInfo(){return Tg(this.restDecoder)===1}readTypeRef(){return Tg(this.restDecoder)}readLen(){return Tg(this.restDecoder)}readAny(){return Ag(this.restDecoder)}readBuf(){return h_(Cg(this.restDecoder))}readJSON(){return JSON.parse(Dg(this.restDecoder))}readKey(){return Dg(this.restDecoder)}},$_=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Tg(this.restDecoder),this.dsCurrVal}readDsLen(){let e=Tg(this.restDecoder)+1;return this.dsCurrVal+=e,e}},ev=class extends $_{constructor(e){super(e),this.keys=[],Tg(e),this.keyClockDecoder=new Ng(Cg(e)),this.clientDecoder=new Mg(Cg(e)),this.leftClockDecoder=new Ng(Cg(e)),this.rightClockDecoder=new Ng(Cg(e)),this.infoDecoder=new jg(Cg(e),wg),this.stringDecoder=new Pg(Cg(e)),this.parentInfoDecoder=new jg(Cg(e),wg),this.typeRefDecoder=new Mg(Cg(e)),this.lenDecoder=new Mg(Cg(e))}readLeftID(){return new Dv(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Dv(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 Ag(this.restDecoder)}readBuf(){return Cg(this.restDecoder)}readJSON(){return Ag(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}}},tv=class{constructor(){this.restEncoder=Vh()}toUint8Array(){return Wh(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Jh(this.restEncoder,e)}writeDsLen(e){Jh(this.restEncoder,e)}},nv=class extends tv{writeLeftID(e){Jh(this.restEncoder,e.client),Jh(this.restEncoder,e.clock)}writeRightID(e){Jh(this.restEncoder,e.client),Jh(this.restEncoder,e.clock)}writeClient(e){Jh(this.restEncoder,e)}writeInfo(e){qh(this.restEncoder,e)}writeString(e){Qh(this.restEncoder,e)}writeParentInfo(e){Jh(this.restEncoder,+!!e)}writeTypeRef(e){Jh(this.restEncoder,e)}writeLen(e){Jh(this.restEncoder,e)}writeAny(e){sg(this.restEncoder,e)}writeBuf(e){eg(this.restEncoder,e)}writeJSON(e){Qh(this.restEncoder,JSON.stringify(e))}writeKey(e){Qh(this.restEncoder,e)}},rv=class{constructor(){this.restEncoder=Vh(),this.dsCurrVal=0}toUint8Array(){return Wh(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Jh(this.restEncoder,t)}writeDsLen(e){e===0&&gg(),Jh(this.restEncoder,e-1),this.dsCurrVal+=e}},iv=class extends rv{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new fg,this.clientEncoder=new ug,this.leftClockEncoder=new fg,this.rightClockEncoder=new fg,this.infoEncoder=new cg(qh),this.stringEncoder=new pg,this.parentInfoEncoder=new cg(qh),this.typeRefEncoder=new ug,this.lenEncoder=new ug}toUint8Array(){let e=Vh();return Jh(e,0),eg(e,this.keyClockEncoder.toUint8Array()),eg(e,this.clientEncoder.toUint8Array()),eg(e,this.leftClockEncoder.toUint8Array()),eg(e,this.rightClockEncoder.toUint8Array()),eg(e,Wh(this.infoEncoder)),eg(e,this.stringEncoder.toUint8Array()),eg(e,Wh(this.parentInfoEncoder)),eg(e,this.typeRefEncoder.toUint8Array()),eg(e,this.lenEncoder.toUint8Array()),$h(e,Wh(this.restEncoder)),Wh(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){sg(this.restEncoder,e)}writeBuf(e){eg(this.restEncoder,e)}writeJSON(e){sg(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 av=(e,t,n,r)=>{r=Ah(r,t[0].id.clock);let i=Uv(t,r);Jh(e.restEncoder,t.length-i),e.writeClient(n),Jh(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)},ov=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{Vv(t,n)>e&&r.set(n,e)}),Bv(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Jh(e.restEncoder,r.size),wh(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{av(e,t.clients.get(n),n,r)})},sv=(e,t)=>{let n=yh(),r=Tg(e.restDecoder);for(let i=0;i<r;i++){let r=Tg(e.restDecoder),i=Array(r),a=e.readClient(),o=Tg(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 Qy(kv(a,o),t),o+=t;break}case 10:{let t=Tg(e.restDecoder);i[n]=new mb(kv(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new fb(kv(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,pb(e,r));i[n]=c,o+=c.length}}}}return n},cv=(e,t,n)=>{let r=[],i=wh(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 zv,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!==mb){let i=xh(d,u.id.client,()=>Vv(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,Vv(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 iv;return ov(e,s,new Map),Jh(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},lv=(e,t)=>ov(e,t.doc.store,t.beforeState),uv=(e,t,n,r=new ev(e))=>$v(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=cv(e,i,sv(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<Vv(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=iy([o.update,a.update])}}else i.pendingStructs=a;let s=q_(r,e,i);if(i.pendingDs){let t=new ev(bg(i.pendingDs));Tg(t.restDecoder);let n=q_(t,e,i);s&&n?i.pendingDs=iy([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,dv(e.doc,t)}},n,!1),dv=(e,t,n,r=ev)=>{let i=bg(t);uv(i,e,n,new r(i))},fv=(e,t,n)=>dv(e,t,n,Q_),pv=(e,t,n=new Map)=>{ov(e,t.store,n),G_(e,W_(t.store))},mv=(e,t=new Uint8Array([0]),n=new iv)=>{pv(n,e,_v(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Kie(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===nv)return Wie(r.map((e,t)=>t===0?e:Jie(e)));if(n.constructor===iv)return iy(r)}return r[0]},hv=(e,t)=>mv(e,t,new nv),gv=e=>{let t=new Map,n=Tg(e.restDecoder);for(let r=0;r<n;r++){let n=Tg(e.restDecoder),r=Tg(e.restDecoder);t.set(n,r)}return t},_v=e=>gv(new Z_(bg(e))),vv=(e,t)=>(Jh(e.restEncoder,t.size),wh(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Jh(e.restEncoder,t),Jh(e.restEncoder,n)}),e),yv=(e,t)=>vv(e,Bv(t.store)),bv=(e,t=new rv)=>(e instanceof Map?vv(t,e):yv(t,e),t.toUint8Array()),xv=e=>bv(e,new tv);var Sv=class{constructor(){this.l=[]}};const Cv=()=>new Sv,wv=(e,t)=>e.l.push(t),Tv=(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.`)},Ev=(e,t,n)=>t_(e.l,[t,n]);var Dv=class{constructor(e,t){this.client=e,this.clock=t}};const Ov=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,kv=(e,t)=>new Dv(e,t),Av=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw gg()},jv=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var Mv=class{constructor(e,t){this.ds=e,this.sv=t}};const Nv=(e,t)=>new Mv(e,t);Nv(U_(),new Map);const Pv=e=>Nv(W_(e.store),Bv(e.store)),Fv=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!z_(t.ds,e.id),Iv=(e,t)=>{let n=xh(e.meta,Iv,Sh),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Vv(r,n)&&Kv(e,kv(n,t))}),L_(e,t.ds,e=>{}),n.add(t))},Lv=(e,t,n=ev)=>{let r=new n(bg(t)),i=new ny(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=V_([e.ds,K_(r)]);return J_(e.ds,a)},Rv=(e,t)=>Lv(e,t,Q_);var zv=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const Bv=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},Vv=(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},Hv=(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 gg()}n.push(t)},Uv=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=Dh(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=Dh((n+r)/2)}throw gg()},Wv=(e,t)=>{let n=e.clients.get(t.client);return n[Uv(n,t.clock)]},Gv=(e,t,n)=>{let r=Uv(t,n),i=t[r];return i.id.clock<n&&i instanceof fb?(t.splice(r+1,0,lb(e,i,n-i.id.clock)),r+1):r},Kv=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Gv(e,n,t.clock)]},qv=(e,t,n)=>{let r=t.clients.get(n.client),i=Uv(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==Qy&&r.splice(i+1,0,lb(e,a,n.clock-a.id.clock+1)),a},Lie=(e,t,n)=>{let r=e.clients.get(t.id.client);r[Uv(r,t.id.clock)]=n},Jv=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Gv(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Gv(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Rie=class{constructor(e,t,n){this.doc=e,this.deleteSet=new I_,this.beforeState=Bv(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 Yv=(e,t)=>t.deleteSet.clients.size===0&&!Aie(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(B_(t.deleteSet),lv(e,t),G_(e,t.deleteSet),!0),Xv=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&xh(e.changed,t,Sh).add(n)},Zv=(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 fb&&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},zie=(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=Uv(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 fb&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Bie=(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=kh(r.length-1,1+Uv(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+Zv(r,e)}})},Qv=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{B_(a),n.afterState=Bv(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(()=>{Ev(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&lae(n)})}),t_(e,[])}finally{r.gc&&zie(a,i,r.gcFilter),Bie(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=Ah(Uv(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Zv(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=Uv(r,n);a+1<r.length&&Zv(r,a+1)>1||a>0&&Zv(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(A_(T_,v_,`[yjs] `,y_,C_,`Changed the client-id because another client seems to be using it.`),r.clientID=Y_()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new nv;Yv(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new iv;Yv(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])):Qv(e,t+1)}}},$v=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Rie(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&&Qv(i,0)}}return o};var Vie=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const ey=(e,t,n)=>{L_(e,n.deletions,n=>{n instanceof fb&&t.scope.some(t=>t===e.doc||jv(t,n))&&cb(n,!1)})},ty=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;$v(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;L_(n,o.insertions,e=>{if(e instanceof fb){if(e.redone!==null){let{item:t,diff:i}=Lae(r,e.id);i>0&&(t=Kv(n,kv(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||jv(t,e))&&c.push(e)}}),L_(n,o.deletions,e=>{e instanceof fb&&a.some(t=>t===n.doc||jv(t,e))&&!z_(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=db(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 Hie=class extends Eh{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=Th(e)?e[0].doc:e instanceof X_?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 I_;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&H_(i,n,r,a)});let a=Rg(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=V_([t.deletions,e.deleteSet]),t.insertions=V_([t.insertions,i])}else r.push(new Vie(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),L_(e,e.deleteSet,t=>{t instanceof fb&&this.scope.some(n=>n===e.doc||jv(n,t))&&cb(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=Th(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof gy?e.doc!==this.doc:e!==this.doc)&&j_(`[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=>ey(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>ey(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=ty(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=ty(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*Uie(e){let t=Tg(e.restDecoder);for(let n=0;n<t;n++){let t=Tg(e.restDecoder),n=e.readClient(),r=Tg(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=Tg(e.restDecoder);yield new mb(kv(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new fb(kv(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,pb(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new Qy(kv(n,r),t),r+=t}}}}var ny=class{constructor(e,t){this.gen=Uie(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===mb);return this.curr}},ry=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Wie=e=>iy(e,Q_,nv),Gie=(e,t)=>{if(e.constructor===Qy){let{client:n,clock:r}=e.id;return new Qy(kv(n,r+t),e.length-t)}else if(e.constructor===mb){let{client:n,clock:r}=e.id;return new mb(kv(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new fb(kv(r,i+t),null,kv(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},iy=(e,t=ev,n=iv)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(bg(e))),i=r.map(e=>new ny(e,!0)),a=null,o=new n,s=new ry(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===mb?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)oy(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===mb)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{oy(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new mb(kv(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===mb?a.struct.length-=t:n=Gie(n,t)),a.struct.mergeWith(n)||(oy(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!==mb;n=e.next())oy(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(oy(s,a.struct,a.offset),a=null),sy(s),G_(o,V_(r.map(e=>K_(e)))),o.toUint8Array()},Kie=(e,t,n=ev,r=iv)=>{let i=_v(t),a=new r,o=new ry(a),s=new n(bg(e)),c=new ny(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===mb){c.next();continue}if(e.id.clock+e.length>n)for(oy(o,e,Ah(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)oy(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 sy(o),G_(a,K_(s)),a.toUint8Array()},ay=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Wh(e.encoder.restEncoder)}),e.encoder.restEncoder=Vh(),e.written=0)},oy=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ay(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Jh(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},sy=e=>{ay(e);let t=e.encoder.restEncoder;Jh(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Jh(t,r.written),$h(t,r.restEncoder)}},qie=(e,t,n,r)=>{let i=new n(bg(e)),a=new ny(i,!1),o=new r,s=new ry(o);for(let e=a.curr;e!==null;e=a.next())oy(s,t(e),0);return sy(s),G_(o,K_(i)),o.toUint8Array()},Jie=e=>qie(e,n_,ev,nv),cy=`You must not compute changes after the event-handler fired.`;var ly=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||=Yie(this.currentTarget,this.target)}deletes(e){return z_(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw mg(cy);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=Ch(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=Ch(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=Ch(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 mg(cy);let t=this.target,n=Sh(),r=Sh(),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 Yie=(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},uy=()=>{j_(`Invalid access: Add Yjs type to a document before reading data.`)};let dy=0;var Xie=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=dy++}};const Zie=e=>{e.timestamp=dy++},fy=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=dy++},Qie=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return fy(r,t,n),r}else{let r=new Xie(t,n);return e.push(r),r}},py=(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)=>Oh(t-e.index)<Oh(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,Zie(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&&Oh(n.index-i)<r.parent.length/80?(fy(n,r,i),n):Qie(e._searchMarker,r,i)},my=(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=Ah(t,i.index+n))}},hy=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;xh(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Ev(r._eH,n,t)};var gy=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Cv(),this._dEH=Cv(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw hg()}clone(){throw hg()}_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){wv(this._eH,e)}observeDeep(e){wv(this._dEH,e)}unobserve(e){Tv(this._eH,e)}unobserveDeep(e){Tv(this._dEH,e)}toJSON(){}};const _y=(e,t,n)=>{e.doc??uy(),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},vy=e=>{e.doc??uy();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},$ie=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&Fv(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},yy=(e,t)=>{let n=0,r=e._start;for(e.doc??uy();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}},by=(e,t)=>{let n=[];return yy(e,(r,i)=>{n.push(t(r,i,e))}),n},eae=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}}}},xy=(e,t)=>{e.doc??uy();let n=py(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}},Sy=(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 fb(kv(o,Vv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ab(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 fb(kv(o,Vv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new $y(new Uint8Array(n))),i.integrate(e,0);break;case X_:i=new fb(kv(o,Vv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new nb(n)),i.integrate(e,0);break;default:if(n instanceof gy)i=new fb(kv(o,Vv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new sb(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},Cy=()=>mg(`Length exceeded!`),wy=(e,t,n,r)=>{if(n>t._length)throw Cy();if(n===0)return t._searchMarker&&my(t._searchMarker,n,r.length),Sy(e,t,null,r);let i=n,a=py(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&&Kv(e,kv(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&my(t._searchMarker,i,r.length),Sy(e,t,o,r)},tae=(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 Sy(e,t,r,n)},Ty=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=py(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&&Kv(e,kv(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Kv(e,kv(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw Cy();t._searchMarker&&my(t._searchMarker,i,-a+r)},Ey=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Dy=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new ab([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new ab([r]);break;case Uint8Array:s=new $y(r);break;case X_:s=new nb(r);break;default:if(r instanceof gy)s=new sb(r);else throw Error(`Unexpected content type`)}new fb(kv(o,Vv(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},Oy=(e,t)=>{e.doc??uy();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ky=e=>{let t={};return e.doc??uy(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Ay=(e,t)=>{e.doc??uy();let n=e._map.get(t);return n!==void 0&&!n.deleted},nae=(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&&Fv(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},jy=e=>(e.doc??uy(),N_(e._map.entries(),e=>!e[1].deleted));var rae=class extends ly{},My=class e extends gy{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 gy?e.clone():e)),t}get length(){return this.doc??uy(),this._length}_callObserver(e,t){super._callObserver(e,t),hy(this,e,new rae(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):$v(this.doc,n=>{wy(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):$v(this.doc,t=>{tae(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):$v(this.doc,n=>{Ty(n,this,e,t)})}get(e){return xy(this,e)}toArray(){return vy(this)}slice(e=0,t=this.length){return _y(this,e,t)}toJSON(){return this.map(e=>e instanceof gy?e.toJSON():e)}map(e){return by(this,e)}forEach(e){yy(this,e)}[Symbol.iterator](){return eae(this)}_write(e){e.writeTypeRef(kae)}};const iae=e=>new My;var aae=class extends ly{constructor(e,t,n){super(e,t),this.keysChanged=n}},Ny=class e extends gy{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 gy?e.clone():e)}),t}_callObserver(e,t){hy(this,e,new aae(this,e,t))}toJSON(){this.doc??uy();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof gy?r.toJSON():r}}),e}get size(){return[...jy(this)].length}keys(){return P_(jy(this),e=>e[0])}values(){return P_(jy(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return P_(jy(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??uy(),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):$v(this.doc,t=>{Ey(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):$v(this.doc,n=>{Dy(n,this,e,t)}),t}get(e){return Oy(this,e)}has(e){return Ay(this,e)}clear(){this.doc===null?this._prelimContent.clear():$v(this.doc,e=>{this.forEach(function(t,n,r){Ey(e,r,n)})})}_write(e){e.writeTypeRef(Aae)}};const oae=e=>new Ny,Py=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&Qg(e,t);var Fy=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&gg(),this.right.content.constructor){case ib:this.right.deleted||zy(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 Iy=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case ib:t.right.deleted||zy(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Kv(e,kv(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},Ly=(e,t,n,r)=>{let i=new Map,a=r?py(t,n):null;return a?Iy(e,new Fy(a.p.left,a.p,a.index,i),n-a.index):Iy(e,new Fy(null,t._start,0,i),n)},Ry=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===ib&&Py(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 fb(kv(a,Vv(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new ib(o,r));l.integrate(e,0),n.right=l,n.forward()})},zy=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},By=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===ib&&Py(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Vy=(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(!Py(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new fb(kv(a,Vv(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new ib(s,c)),n.right.integrate(e,0),n.forward()}}return o},Hy=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;By(n,i);let s=Vy(e,t,n,i),c=r.constructor===String?new ob(r):r instanceof gy?new sb(r):new rb(r),{left:l,right:u,index:d}=n;t._searchMarker&&my(t._searchMarker,n.index,c.getLength()),u=new fb(kv(o,Vv(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(),Ry(e,t,n,s)},Uy=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;By(n,i);let s=Vy(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===ib));){if(!n.right.deleted)switch(n.right.content.constructor){case ib:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Py(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&&Kv(e,kv(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 fb(kv(o,Vv(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new ob(i)),n.right.integrate(e,0),n.forward()}Ry(e,t,n,s)},Wy=(e,t,n,r,i)=>{let a=t,o=yh();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===ib){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 ib:{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&&zy(i,n);break}}}t=t.right}return s},sae=(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===ib){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},cae=e=>{let t=0;return $v(e.doc,n=>{let r=e._start,i=e._start,a=yh(),o=bh(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case ib:zy(o,i.content);break;default:t+=Wy(n,r,i,a,o),a=bh(o),r=i;break}i=i.right}}),t},lae=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&&Jv(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===ib&&e.constructor!==Qy&&t.add(e.parent)})}$v(n,n=>{L_(e,e.deleteSet,e=>{if(e instanceof Qy||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===ib?t.add(r):sae(n,e)});for(let e of t)cae(e)})},Gy=(e,t,n)=>{let r=n,i=bh(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case sb:case rb:case ob:n<t.right.length&&Kv(e,kv(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Wy(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&my(o._searchMarker,t.index,-r+n),t};var uae=class extends ly{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=[];$v(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},Yg(o)||(e.attributes=Gg({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case sb:case rb: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 ob: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 ib:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Py(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Py(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;Py(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Py(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),zy(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}},Ky=class e extends gy{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??uy(),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 uae(this,e,t);hy(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??uy();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===ob&&(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)):$v(this.doc,n=>{let r=new Fy(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)&&Hy(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&Gy(n,r,a.delete):Uy(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??uy();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(Fv(s,e)||t!==void 0&&Fv(s,t))switch(s.content.constructor){case ob:{let r=i.get(`ychange`);e!==void 0&&!Fv(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&&!Fv(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 sb:case rb:{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 ib:Fv(s,e)&&(c(),zy(i,s.content));break}s=s.right}c()};return e||t?$v(a,n=>{e&&Iv(n,e),t&&Iv(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)):$v(r,r=>{let i=Ly(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Hy(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):$v(r,r=>{let i=Ly(r,this,e,!n);Hy(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)):$v(n,n=>{Gy(n,Ly(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)):$v(r,r=>{let i=Ly(r,this,e,!1);i.right!==null&&Uy(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):$v(this.doc,t=>{Ey(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):$v(this.doc,n=>{Dy(n,this,e,t)})}getAttribute(e){return Oy(this,e)}getAttributes(){return ky(this)}_write(e){e.writeTypeRef(jae)}};const dae=e=>new Ky;var qy=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??uy()}[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===Yy||t.constructor===Jy)&&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})}},Jy=class e extends gy{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 gy?e.clone():e)),t}get length(){return this.doc??uy(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new qy(this,e)}querySelector(e){e=e.toUpperCase();let t=new qy(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),wh(new qy(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){hy(this,e,new mae(this,t,e))}toString(){return by(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),yy(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):$v(this.doc,n=>{wy(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)$v(this.doc,n=>{let r=e&&e instanceof gy?e._item:e;Sy(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 mg(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):$v(this.doc,n=>{Ty(n,this,e,t)})}toArray(){return vy(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return xy(this,e)}slice(e=0,t=this.length){return _y(this,e,t)}forEach(e){yy(this,e)}_write(e){e.writeTypeRef(Nae)}};const fae=e=>new Jy;var Yy=class e extends Jy{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 qg(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof gy?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):$v(this.doc,t=>{Ey(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):$v(this.doc,n=>{Dy(n,this,e,t)})}getAttribute(e){return Oy(this,e)}hasAttribute(e){return Ay(this,e)}getAttributes(e){return e?nae(this,e):ky(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 yy(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Mae),e.writeKey(this.nodeName)}};const pae=e=>new Yy(e.readKey());var mae=class extends ly{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)})}},hae=class e extends Ny{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(Pae),e.writeKey(this.hookName)}};const gae=e=>new hae(e.readKey());var Xy=class e extends Ky{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(Fae)}};const _ae=e=>new Xy;var Zy=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw hg()}mergeWith(e){return!1}write(e,t,n){throw hg()}integrate(e,t){throw hg()}},Qy=class extends Zy{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),Hv(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},$y=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 hg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const vae=e=>new $y(e.readBuf());var eb=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){H_(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 yae=e=>new eb(e.readLen()),tb=(e,t)=>new X_({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var nb=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(tb(this.doc.guid,this.opts))}splice(e){throw hg()}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 bae=e=>new nb(tb(e.readString(),e.readAny()));var rb=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 hg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const xae=e=>new rb(e.readJSON());var ib=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 hg()}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 Sae=e=>new ib(e.readKey(),e.readJSON());var Cae=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 wae=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 Cae(n)},Tae=u_(`node_env`)===`development`;var ab=class e{constructor(e){this.arr=e,Tae&&e_(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 Eae=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new ab(n)};var ob=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 Dae=e=>new ob(e.readString()),Oae=[iae,oae,dae,pae,fae,gae,_ae],kae=0,Aae=1,jae=2,Mae=3,Nae=4,Pae=5,Fae=6;var sb=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 hg()}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 Iae=e=>new sb(Oae[e.readTypeRef()](e)),Lae=(e,t)=>{let n=t,r=0,i;do r>0&&(n=kv(n.client,n.clock+r)),i=Wv(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof fb);return{item:i,diff:r}},cb=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},lb=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new fb(kv(r,i+n),t,kv(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=kv(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},ub=(e,t)=>Mie(e,e=>z_(e.deletions,t)),db=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Kv(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||db(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Kv(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:Kv(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:Kv(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||z_(r,d.right.id)||ub(a.undoStack,d.right.id)||ub(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Kv(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=kv(c,Vv(s,c)),h=new fb(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,cb(h,!0),h.integrate(e,0),h};var fb=class e extends Zy{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>=Vv(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Vv(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Dv&&this.id.client!==this.parent.client&&this.parent.clock>=Vv(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=qv(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Kv(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===Qy||this.right&&this.right.constructor===Qy)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===Dv){let e=Wv(n,this.parent);e.constructor===Qy?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=qv(e,e.doc.store,kv(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),Ov(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(Ov(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Wv(e.doc.store,n.origin)))r.has(Wv(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),Hv(e.doc.store,this),this.content.integrate(e,this),Xv(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Qy(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:kv(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ov(e.origin,this.lastId)&&this.right===e&&Ov(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(),H_(e.deleteSet,this.id.client,this.id.clock,this.length),Xv(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw gg();this.content.gc(e),t?Lie(e,this,new Qy(this.id,this.length)):this.content=new eb(this.length)}write(e,t){let n=t>0?kv(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=Av(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===Dv?(e.writeParentInfo(!1),e.writeLeftID(t)):gg();i!==null&&e.writeString(i)}this.content.write(e,t)}};const pb=(e,t)=>Rae[t&31](e),Rae=[()=>{gg()},yae,wae,vae,Dae,xae,Sae,Iae,Eae,bae,()=>{gg()}];var mb=class extends Zy{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){gg()}write(e,t){e.writeInfo(10),Jh(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const hb=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},gb=`__ $YJS$ __`;hb[gb]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),hb[gb]=!0;const zae=/[\uD800-\uDBFF]/,Bae=/[\uDC00-\uDFFF]/,Vae=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&zae.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&&Bae.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Hae=e=>{let t=hd(`sha256`);return t.update(e),t.digest()},Uae=new Jr(`y-sync`);new Jr(`y-undo`),new Jr(`yjs-cursor`);const Wae=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},Gae=e=>m_(Wae(Hae(g_(e)))),Kae=()=>({mapping:new Map,isOMark:new Map}),_b=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!z_(t.ds,e.id),qae=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof Yy)return vb(e,t,n,r,i,a);throw hg()}return o},vb=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof Yy){let s=qae(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof Ky&&!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=Jae(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):$ie(e,new Mv(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(_b(e._item,r)?_b(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=Tb(s),l=Ab(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}},Jae=(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,Ab(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},Yae=(e,t)=>{let n=new Xy,r=e.map(e=>({insert:e.text,attributes:jb(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Xae=(e,t)=>{let n=new Yy(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}let r=jb(e.marks||[],t);for(let e in r)n.setAttribute(wb+e,{...r[e]});return n.insert(0,Sb(e).map(e=>yb(e,t))),t.mapping.set(n,e),n},yb=(e,t)=>e instanceof Array?Yae(e,t):Xae(e,t),bb=e=>typeof e==`object`&&!!e,xb=(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||bb(o)&&bb(s)&&xb(o,s)}return r},Sb=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},Cb=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&Kg(e.attributes||{}).length===t[n].marks.length&&Xg(e.attributes,(e,r)=>{let i=kb(r),a=t[n].marks;return a.find(e=>e.type.name===i)?xb(e,a.find(e=>e.type.name===i)?.attrs):!1}))},wb=`ymark:`,Tb=e=>{let t={},n={};for(let r in e)r.startsWith(wb)?n[r.slice(6)]=e[r]:t[r]=e[r];return{plain:t,marks:n}},Zae=(e,t)=>{let n=Object.keys(e);return n.length===t.length?n.every(n=>{let r=kb(n),i=t.find(e=>e.type.name===r);return i?xb(e[n],i.attrs):!1}):!1},Eb=(e,t)=>{if(e instanceof Yy&&!(t instanceof Array)&&Nb(e,t)){let n=Sb(t),r=Tb(e.getAttributes());return e._length===n.length&&Zae(r.marks,t.marks)&&xb(r.plain,t.attrs)&&e.toArray().every((e,t)=>Eb(e,n[t]))}return e instanceof Xy&&t instanceof Array&&Cb(e,t)},Db=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),Ob=(e,t,n)=>{let r=e.toArray(),i=Sb(t),a=i.length,o=r.length,s=kh(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(Db(n.mapping.get(e),t))u=!0;else if(!Eb(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(Db(n.mapping.get(e),t))u=!0;else if(!Eb(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},Qae=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof ob?t+=n.content.str:n.content instanceof ib&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},$ae=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=Qae(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,jb(e.marks,n))})),{insert:o,remove:s,index:c}=Vae(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})))},eoe=/(.*)(--[a-zA-Z0-9+/=]{8})$/,kb=e=>eoe.exec(e)?.[1]??e,Ab=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(kb(r),e[r]));return n},jb=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=xh(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${Gae(e.toJSON())}`:e.type.name]=e.attrs}}),n},Mb=(e,t,n,r)=>{if(t instanceof Yy&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof Yy){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(wb)&&t.removeAttribute(n);let a=jb(n.marks||[],r);for(let n in a){let r=e[wb+n];(r===void 0||!xb(r,a[n]))&&t.setAttribute(wb+n,{...a[n]})}for(let n in e)n.startsWith(wb)&&a[n.slice(6)]===void 0&&t.removeAttribute(n)}let i=Sb(n),a=i.length,o=t.toArray(),s=o.length,c=kh(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!Db(r.mapping.get(e),t))if(Eb(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(!Db(r.mapping.get(e),t))if(Eb(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 Xy&&c instanceof Array)Cb(n,c)||$ae(n,c,r),l+=1;else{let i=n instanceof Yy&&Nb(n,c),a=d instanceof Yy&&Nb(d,f);if(i&&a){let e=Ob(n,c,r),t=Ob(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Mb(e,n,c,r),l+=1):a?(Mb(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[yb(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof Xy?(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(yb(i[t],r));t.insert(l,e)}},Uae)},Nb=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,toe=(e,t)=>{let n=e.toArray().map(e=>vb(e,t,Kae())).filter(e=>e!==null);return li.fromArray(n)},Pb=(e,t)=>t.topNodeType.create(null,toe(e,t));function Fb(e,t,n,r){let{body:i}=So(t);return r!==void 0&&r.rawContent===t?r.parsedJson:Es(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Cs.parseWithFallback(i,Ib(n)))}function Ib(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function Lb(e){return Cs.serialize(Pb(e,Ss).toJSON())}function Rb(e,t,n,r,i,a){let o=Lb(r),s=Cs.serialize(n),{body:c}=So(e.baselineFullMd),l=Cs.serialize(Cs.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:Vn(i,t).md})}function zb(e,t,n,r,i,a){Es(`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=Fb(e,t,r,i),l=Ss.nodeFromJSON(c),u=a?Lb(n):void 0;if(s!==t&&Bt(o,s,t),Mb(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=So(a.baselineFullMd);Rb(a,u,c,n,e,Ib(r))}})}function Bb(e,t,n,r,i){Es(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=Fb(e,t,n,r),c=Ss.nodeFromJSON(s),l=i?Lb(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),Mb(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=So(i.baselineFullMd);Rb(i,l,s,a,e,Ib(n))}})}function noe(e,t,n){let r=e.getXmlFragment(`default`),{frontmatter:i,body:a}=So(e.getText(`source`).toString()),o=Ib(t),s=Cs.parseWithFallback(a,o),c=Ss.nodeFromJSON(s),l=n?Cs.serialize(Pb(r,Ss).toJSON()):void 0;if(Mb(e,r,c,{mapping:new Map,isOMark:new Map}),n&&l!==void 0){let e=Cs.serialize(Pb(r,Ss).toJSON()),t=Cs.serialize(s),{body:a}=So(n.baselineFullMd),c=Cs.serialize(Cs.parseWithFallback(a,o));n.report({pendingBody:l,baselineBody:c,ytextDerivedBody:t,rebuiltBody:e,restorePayload:Vn(i,l).md})}}const roe=P(`loss-capture`),Vb=`detector-trip`,Hb=`backstop-trip`,Ub=`checkpoint-write`;M({ts:i(),schemaVersion:i(),seq:i(),event:u(),docName:u(),writerId:u().nullable(),site:u().optional(),direction:u().optional(),lostLen:i().optional(),digest:u().optional(),checkpointSha:u().optional(),which:u().optional(),witnessAvailable:D().optional(),connections:i().optional()});const Wb=[`.ok`,`local`,`loss-capture`];function ioe(e){return I(e,...Wb,`loss-current.jsonl`)}function aoe(e){return I(e,...Wb,`loss-prev.jsonl`)}var ooe=class{#e;#t;#n=new Map;constructor(e){this.#e=new dc({currentPath:ioe(e.projectDir),previousPath:aoe(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},...e.which===void 0?{}:{which:e.which},...e.witnessAvailable===void 0?{}:{witnessAvailable:e.witnessAvailable},...e.connections===void 0?{}:{connections:e.connections}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{roe.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const Gb=P(`checkpoint-chain`);async function Kb(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw Gb.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
|
|
@@ -25,7 +25,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,At as i,Bt
|
|
|
25
25
|
`))n.trim()!==``&&(e.stderrTail.push(n.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift(),e.authStderr!==null&&(e.authStderr.push(n.slice(0,500)),e.authStderr.length>6&&e.authStderr.shift(),e.info.signInOutput=[...e.authStderr],this.broadcastInfo(e)))}),o.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),o.on(`exit`,(t,n)=>{if(e.child=null,a.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;if(e.info.status===`error`){this.failPendingPermissions(e);return}let r=e.stderrTail.slice(-10).join(`
|
|
26
26
|
`);this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,code:t,signal:n,machineDetail:nD(e)},`[acp-threads] agent exited unexpectedly`),this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new HE(`spawn-failed`,`agent process has no stdio`);let s=aie(_te.toWeb(o.stdin),pd.toWeb(o.stdout)),c=Die({name:`open-knowledge`}).onRequest(Jm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(Jm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(Jm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(Jm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(Jm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(Jm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(Jm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(Jm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(Jm.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.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 l;try{l=await c.agent.request(Jm.agent.initialize,{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new HE(`spawn-failed`,`initialize failed: ${$E(t)}`)}return e.closed?null:(e.lastInit=l,e.info.promptCapabilities=l.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){let n;try{await PT(t),n=await this.withLoginShellPathIfEligible(t)}catch(r){if(!(r instanceof bT)||r.code!==`command-not-found`)throw r;let i=await this.retryWithLoginShellPath(t);if(i===null)return this.fallbackToManagedRuntime(e,t,r);n=i}return e.closed?null:this.ensureInterpreterRuns(e,n)}async ensureInterpreterRuns(e,t){if(t.kind!==`npx`&&t.kind!==`uvx`)return t;let n=await this.probeInterpreterOnce(t);if(e.closed)return null;if(n===null)return t;this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,cmd:t.cmd,kind:t.kind,detail:n},`[acp-threads] interpreter is installed but failed to run — offering the managed runtime`);let r=new bT(`command-not-found`,IT(t,n));return this.fallbackToManagedRuntime(e,t,r,r)}async fallbackToManagedRuntime(e,t,n,r){if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=iE(t.kind);if(!pE(i))throw n;let a=await this.provideManagedRuntime(e,i,r===void 0?`missing`:`broken`).catch(e=>{throw r!==void 0&&e instanceof bT&&e.code===`command-not-found`?r:e});if(a===null)return null;let o=OT(t,a);await PT(o);let s=await this.probeInterpreterOnce(o);return s===null?o:this.repairManagedRuntime(e,t,i,s)}async repairManagedRuntime(e,t,n,r){let i={threadId:e.info.threadId,agentId:e.info.agent.id,runtime:n,detail:r};if(this.opts.log.warn(i,`[acp-threads] OK's own managed runtime failed to run — replacing it`),!await xE(n,this.opts.log,this.opts.runtimeInstall?.root))throw new bT(`install-failed`,RT(t,r));let a=await this.provideManagedRuntime(e,n,`damaged`).catch(e=>{throw e instanceof bT&&e.code===`command-not-found`?new bT(`command-not-found`,zT(t)):e});if(a===null)return null;let o=OT(t,a);await PT(o);let s=await this.probeInterpreterOnce(o);if(s===null)return o;throw this.opts.log.error({...i,detail:s},`[acp-threads] a freshly downloaded managed runtime failed to run`),new bT(`install-failed`,LT(o,s))}async probeInterpreterOnce(e){let t=JSON.stringify([e.cmd,VT(e.env)??``]);if(this.healthyInterpreters.has(t))return null;let n=await BT(e,void 0,this.opts.log);return n===null&&this.healthyInterpreters.add(t),n}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(VT(t.env)===VT(e.env))return null;try{await PT(t)}catch(t){if(!(t instanceof bT))throw t;return this.opts.log.debug({cmd:e.cmd,kind:e.kind},`[acp] login-shell PATH did not resolve the command either`),null}return this.opts.log.info({cmd:e.cmd,kind:e.kind},`[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer`),t}async withLoginShellPathIfEligible(e){if(e.pathFromOverlay||HT(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:kT(e,t)}async provideManagedRuntime(e,t,n){let r=this.opts.runtimeInstall?.root;await bE(t,this.opts.log,r);let i=await _E(t,r).catch(()=>null);if(i!==null)return i;let a=await this.requestRuntimeConsent(e,t,n);if(a===`closed`||e.closed)return null;if(a!==`granted`)throw new bT(`command-not-found`,ZE(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=aE(t).displayName;throw new bT(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t,n){let r=crypto.randomUUID(),i=aE(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:r,runtime:t,displayName:i.displayName,provides:i.provides,version:i.version,approxSizeMB:i.approxSizeMB,sourceHost:i.sourceHost,agentName:e.info.agent.name,reason:n,ts:Date.now()}),new Promise(t=>{let n=setTimeout(()=>{e.pendingRuntimeConsent.delete(r),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:r,decision:`timeout`,ts:Date.now()}),t(`timeout`)},3e5);n.unref?.(),e.pendingRuntimeConsent.set(r,{resolve:t,timer:n})})}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`;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 SE(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:[{name:Iw,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:oa,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=lf[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 bT||t instanceof HE?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:nD(e)}),await this.teardownFailedAgent(e);return}if(r===null)return;let{conn:i,init:a,launch:o}=r;await this.openSession(e,i,a,t.settings)===!0&&(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!==``||t.attachments!==void 0&&t.attachments.length>0)&&this.sendPrompt(e.info.threadId,t.prompt??``,t.attachments))}async openSession(e,t,n,r,i=`park`){e.info.availableCommands=null;let a=await this.buildMcpServers(e,n);try{let n=await t.agent.request(Jm.agent.session.new,{cwd:e.cwd,mcpServers:a});e.sessionId=n.sessionId,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){if(QE(t)){if(i===`report`)return`auth-required`;this.emitStatus(e,`auth_required`,`sign in required: ${$E(t)}`,{reason:`auth-required`,agentMessage:$E(t),machineDetail:iD(t,e),authMethods:aD(n.authMethods)})}else this.emitStatus(e,`error`,`session setup failed: ${$E(t)}`,{reason:`session-setup`,agentMessage:$E(t),machineDetail:rD(eD(t),nD(e))}),await this.teardownFailedAgent(e);return!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t,n){if(this.destroyed)throw new HE(`capacity`,`server is shutting down`);let r=this.mustGet(e);if(r.info.archived!==!0)throw new HE(`not-ready`,`thread is not archived`);if(r.resumeInFlight)throw new HE(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new HE(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.resumeInFlight=!0;let i=Date.now();try{await this.ensureLogResolved(r);let a=r.sessionId,{info:o,custom:s}=await this.resolveAgentInfo(r.agentRef);if(this.destroyed)throw new HE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new HE(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);r.info.agent=o,r.info.archived=!1,r.info.availableCommands=null,r.stderrTail=[],r.midTurnOnDisk&&(r.midTurnOnDisk=!1,this.appendEvent(r,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}));let c=t!==void 0&&t!==``||n!==void 0&&n.length>0;c&&(this.echoUserMessage(r,t??``,n),this.flushBroadcast(r)),this.emitStatus(r,`installing`);try{if(a===null)throw new HE(`resume-unsupported`,`this thread never completed an agent session`);let o=await this.connectAgent(r,s);if(o===null)throw new HE(`not-ready`,`thread closed during resume`);let{conn:l,init:u}=o,d=await this.buildMcpServers(r,u),f=u.agentCapabilities,p=f?.sessionCapabilities?.resume!=null,m;if(p)m=await l.agent.request(Jm.agent.session.resume,{sessionId:a,cwd:r.cwd,mcpServers:d});else if(f?.loadSession===!0){r.suppressUpdates=!0,r.lastSuppressedAt=Date.now();try{m=await l.agent.request(Jm.agent.session.load,{sessionId:a,cwd:r.cwd,mcpServers:d}),await this.awaitReplayQuiescence(r)}finally{r.suppressUpdates=!1}}else throw new HE(`resume-unsupported`,`${r.info.agent.name} doesn't support resuming previous sessions`);r.sessionId=a;let h=m.modes;h!=null&&(r.info.modes=h);let g=m.configOptions;return g!=null&&(r.info.configOptions=g),this.emitStatus(r,`ready`),this.opts.log.info({threadId:e,agentId:r.info.agent.id,method:p?`session/resume`:`session/load`,msToResumed:Date.now()-i},`[acp-threads] thread resumed`),c&&this.dispatchPrompt(r,t??``,n,{echo:!1}),{...r.info}}catch(t){throw await this.abortResume(r),t instanceof HE?t:t instanceof bT?new HE(t.code===`install-failed`?`install-failed`:`spawn-failed`,t.message):(this.opts.log.warn({err:t,threadId:e},`[acp-threads] resume rejected by the agent`),new HE(`resume-unsupported`,`couldn't resume the previous session: ${$E(t)}`))}}finally{r.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new HE(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new HE(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new HE(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new HE(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new HE(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{yT(),this.healthyInterpreters.clear();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new HE(`spawn-failed`,n)}if(t.closed)throw new HE(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new HE(`spawn-failed`,tD(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new HE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new HE(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new HE(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new HE(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new HE(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new HE(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0,n.authStderr=[],n.info.signInOutput=void 0;try{this.emitStatus(n,`authenticating`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw GE();let t=e instanceof UE?`the sign-in didn't complete in time — try again`:$E(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:iD(e,n),authMethods:aD(i.authMethods)}),new HE(`not-ready`,t)}if(n.closed)throw new HE(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw GE();let a=await this.openSession(n,r,i,n.launchSettings,`report`);if(a===`auth-required`){this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] signed in but session still refused — relaunching the agent`),this.closeSignInCapture(n);try{return await this.retryThread(e)}catch(t){throw this.getInfo(e)?.status===`authenticating`&&this.emitStatus(n,`auth_required`,`sign in required: ${$E(t)}`,{reason:`auth-required`,agentMessage:$E(t),machineDetail:iD(t,n),authMethods:aD(i.authMethods)}),t}}if(a!==!0)throw new HE(`not-ready`,tD(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1,this.closeSignInCapture(n)}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new UE),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(Jm.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}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 QT(t,{graceMs:VE}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(mh(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,n){let r=this.mustGet(e);if(r.info.archived===!0)throw new HE(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new HE(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new HE(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new HE(`not-ready`,`thread has no live agent session`);if(r.turnActive){let e=r.info.queue??[];if(e.length>=20)throw new HE(`not-ready`,`20 messages are already waiting — let the agent catch up`);let i={id:crypto.randomUUID(),content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.queue=[...e,i],r.info.lastActivityAt=Date.now(),this.emitInfo(r);return}this.dispatchPrompt(r,t,n,{echo:!0})}steerPrompt(e,t,n){let r=this.mustGet(e);if(r.info.archived===!0)throw new HE(`not-ready`,`the thread is archived — resume it first`);if(r.resumeInFlight)throw new HE(`not-ready`,`the thread is still resuming`);if(r.authInFlight)throw new HE(`not-ready`,`the thread is still signing in`);if(r.sessionId===null||r.conn===null)throw new HE(`not-ready`,`thread has no live agent session`);if(!r.turnActive){this.dispatchPrompt(r,t,n,{echo:!0});return}this.clearSteer(r);let i={content:t,ts:Date.now()};n!==void 0&&n.length>0&&(i.attachments=n),r.info.steer=i,r.info.lastActivityAt=Date.now(),this.emitInfo(r);let a=setTimeout(()=>this.demoteStalledSteer(r),this.steerStallMs);a.unref?.(),r.steerStallTimer=a,this.cancelTurn(r,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;if(t===void 0||e.closed||!e.turnActive)return;e.info.steer=void 0;let n={id:crypto.randomUUID(),content:t.content,ts:t.ts};t.attachments!==void 0&&t.attachments.length>0&&(n.attachments=t.attachments),e.info.queue=[n,...e.info.queue??[]],this.emitInfo(e)}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(n.info.queue=i.length>0?i:void 0,this.emitInfo(n),!0)}drainIfIdle(e){if(e.turnActive||e.closed||e.resumeInFlight||e.info.archived===!0||e.sessionId===null||e.conn===null)return;let t=this.takeNextQueued(e);t!==null&&this.dispatchPrompt(e,t.content,t.attachments,{echo:!0})}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let n=t.findIndex(e=>e.held!==!0);if(n===-1)return null;let r=t[n],i=[...t.slice(0,n),...t.slice(n+1)];return e.info.queue=i.length>0?i:void 0,r??null}echoUserMessage(e,t,n){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=LE(n),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}let r={kind:`user_message`,content:t,ts:Date.now()};n!==void 0&&n.length>0&&(r.attachments=n),this.appendEvent(e,r)}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new HE(`not-ready`,`the thread is closing`);let r=IE(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,r){if(e.sessionId===null||e.conn===null)throw new HE(`not-ready`,`thread has no live agent session`);r.echo&&this.echoUserMessage(e,t,n);let i=t;e.envNotePending&&!t.startsWith(`/`)&&(e.envNotePending=!1,i=`Note on your environment: you are running inside the OpenKnowledge app, connected over ACP (Agent Client Protocol) — not inside your own terminal app. Your host CLI's terminal UI is not present, so its built-in slash commands (such as /tasks or /bashes) and keyboard shortcuts (such as Ctrl+O) do not exist here; never recommend them. The only slash commands available to the user are the ones you advertise over ACP.\n\n${t}`),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let a=e.sessionId;Hw(i,n,e.info.promptCapabilities,e=>this.confinePath(e).then(({abs:e,rel:t})=>({abs:e,rel:t}))).then(t=>{if(t.dropped.length>0){this.opts.log.warn({threadId:e.info.threadId,dropped:t.dropped.map(e=>({kind:e.part.kind,reason:e.reason}))},`[acp-threads] dropped attachment parts before session/prompt`);let n=Date.now();for(let r of t.dropped){let t=r.part.kind===`image`||r.part.kind===`blob`?r.part.name:r.part.name||r.part.path;this.appendEvent(e,{kind:`agent_stderr`,line:`[attachment dropped] ${t}: ${r.reason}`,ts:n})}}if(e.sessionId===null||e.conn===null)throw new HE(`not-ready`,`thread has no live agent session`);if(e.cancelRequested)throw new WE;return e.conn.agent.request(Jm.agent.session.prompt,{sessionId:a,prompt:[...t.blocks]})}).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.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,t.attachments,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,n.attachments,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,t.attachments,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}this.emitStatus(e,`error`,`prompt failed: ${$E(t)}`,{reason:`prompt`,agentMessage:$E(t),machineDetail:rD(eD(t),nD(e))})}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(Jm.agent.session.cancel,{sessionId:e.sessionId}).catch(t=>{this.opts.log.debug({err:t,threadId:e.info.threadId},`[acp-threads] cancel notification never reached the agent`)}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new HE(`not-ready`,`thread has no live agent session`);n.conn.agent.request(Jm.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 HE(`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(Jm.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||!XE(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(Jm.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(Jm.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`&&XE(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(Jm.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.clearSteer(n),this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await QT(r,{graceMs:t?.killGraceMs??BE})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,n.lastInit=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(mh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){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 HE(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new HE(`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:VE})))}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)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:qw(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await ld(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await ld(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
|
|
27
27
|
`),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
|
|
28
|
-
`)}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=Sw(t.dc.document);xw(t.dc.document,n,`replace`,i,void 0,yw(t));let a=Ki(r,Sw(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,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-
|
|
28
|
+
`)}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=Sw(t.dc.document);xw(t.dc.document,n,`replace`,i,void 0,yw(t));let a=Ki(r,Sw(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,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-DN8Ne6OV.mjs`);await e(F(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return JE(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new HE(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&Qw(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>zE){let t=e.events.length-zE;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,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason,machineDetail:r?.machineDetail},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await QT(t,{graceMs:BE})}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),this.broadcastInfo(e)}broadcastInfo(e){for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}closeSignInCapture(e){e.authStderr=null,e.info.signInOutput!==void 0&&(e.info.signInOutput=void 0,this.broadcastInfo(e))}buildMeta(e){let{queue:t,steer:n,signInOutput:r,...i}=e.info;return{version:1,info:i,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){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=Jo(e.info.agent.id),i=Ra[r]??ca(e.agentSessionId);n.setPresence(mh(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,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 JE(e,t,n){let r=await dd(e),i=Du(Eu(t)?t:R(r,t)),a=i,o=``;for(;;)try{let e=await dd(a),i=o===``?e:I(e,o),s=L(r,i);if(s===``||s.startsWith(`..`)||Eu(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(z).join(`/`),t=s.split(z).join(`/`);!tS(e)&&!nS(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(z).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=F(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):I(a.slice(t.length+1),o),a=t}}function YE(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0,signInOutput:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],authStderr:null,terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1}}function XE(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 ZE(e){let t=aE(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 QE(e){return typeof e==`object`&&!!e&&e.code===-32e3}function $E(e){return e instanceof Error?e.message:String(e)}function eD(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function tD(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function nD(e){let t=e.stderrTail.join(`
|
|
29
29
|
`);return t===``?void 0:t}function rD(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
|
|
30
30
|
`);return t===``?void 0:t}function iD(e,t){let n=t.authStderr===null?void 0:t.authStderr.join(`
|
|
31
31
|
`);return rD(eD(e),n)}function aD(e){return(e??[]).flatMap(e=>{if(typeof e!=`object`||!e)return[];let{id:t,name:n,description:r,type:i}=e;return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,name:n,...typeof r==`string`?{description:r}:{},...typeof i==`string`?{kind:i}:{}}]})}const oD=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`steer`,`queue_edit`,`queue_hold`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`retry`,`authenticate`,`delete`,`list`]);function sD(e){if(e===void 0)return!0;if(!Array.isArray(e))return!1;for(let t of e){if(typeof t!=`object`||!t)return!1;let e=t;if(e.kind===`file`||e.kind===`folder`){if(typeof e.path!=`string`||typeof e.name!=`string`)return!1}else if(e.kind===`image`){if(typeof e.data!=`string`||typeof e.mimeType!=`string`||typeof e.name!=`string`||e.sizeBytes!==void 0&&typeof e.sizeBytes!=`number`)return!1}else if(e.kind===`blob`){if(typeof e.data!=`string`||typeof e.textPayload!=`boolean`||typeof e.mimeType!=`string`||typeof e.name!=`string`||e.sizeBytes!==void 0&&typeof e.sizeBytes!=`number`)return!1}else return!1}return!0}function cD(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`||!oD.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 sD(n.attachments)?n:null}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`||!sD(n.attachments)?null:n;case`steer`:{if(!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`||!sD(n.attachments))return null;let e=Array.isArray(n.attachments)&&n.attachments.length>0;return n.content===``&&!e?null:n}case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)||n.reqId!==void 0&&!r(`reqId`)?null:n;case`queue_hold`:return!r(`threadId`)||!r(`id`)||typeof n.held!=`boolean`?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`?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`||!sD(n.attachments)?null:n;case`retry`:return!r(`threadId`)||!r(`reqId`)?null:n;case`authenticate`:return!r(`threadId`)||!r(`reqId`)||!r(`methodId`)?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function lD(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(uD(e,t,n));e.on(`message`,e=>{let s=cD(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,attachments:s.attachments,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,s.attachments);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});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,s.attachments);return;case`steer`:t.steerPrompt(s.threadId,s.content,s.attachments);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);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 HE?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 HE)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 uD(e,t,n){return{op:`error`,code:e,message:t,...n}}var dD=class{hocuspocus;log=P(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){hh(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){hh(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(Ar);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),fD(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function fD(e){return e?.awareness??null}var pD=class{hocuspocus;log=P(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!hh(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(!hh(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(!hh(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(!hh(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 wse(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Ar);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),mD(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function mD(e){return e?.awareness??null}var hD=class extends Error{};const gD=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],_D=1024*1024;async function vD(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 hD(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new hD(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new hD(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new hD(`Website skill fetch exceeded 5 redirects: ${t}`)}function yD(e){let t;try{t=new URL(e)}catch{throw new hD(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new hD(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new hD(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function bD(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function xD(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`||!bD(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&bD(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function SD(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 gD){let a=new URL(i,e).href;try{let o=await vD(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)>_D){r.push(`${i}: index exceeds ${_D} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=xD(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 hD(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function wD(e,t={}){let{skills:n}=t.index??await TD(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function TD(e,t={}){let n=yD(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new hD(`No fetch implementation available.`);return CD(n,r,t.timeoutMs??15e3)}async function ED(e,t={}){if(!bD(e.skill)||e.skill.includes(`/`))throw new hD(`Invalid website skill name: ${e.skill}`);let n=yD(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new hD(`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 hD(`Website skill index does not contain ${e.skill}`);let c=Uu(I(ad(),`ok-skill-site-`)),l=I(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await vD(r,SD(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new hD(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new hD(`Website skill file exceeds ${Dn} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new hD(`Website skill file exceeds ${Dn} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new hD(`Website skill bundle exceeds ${sr} bytes.`);let d=I(l,...e.split(`/`));Hu(F(d),{recursive:!0}),ed(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:()=>Xu(c,{recursive:!0,force:!0})}}catch(t){throw Xu(c,{recursive:!0,force:!0}),t instanceof hD?t:new hD(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const DD=Sd(vu),OD=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,kD=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function AD(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 kD.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=OD.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function jD(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 MD(e,t={}){if(e.kind===`well-known`)return ED(e,t);if(e.kind===`local`){let t=R(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!B(t))throw new hD(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!kD.some(t=>t.test(e.url)))throw new hD(`Unsupported git transport: ${e.url}`);let n=Uu(I(ad(),`ok-skill-import-`));try{await DD(`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){Xu(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new hD(`git clone failed for ${e.url}: ${r}`)}let r;try{r=yu(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?R(n,e.subpath):n,a=L(n,i);if(a.startsWith(`..`)||Eu(a))throw Xu(n,{recursive:!0,force:!0}),new hD(`subpath escapes the clone: ${e.subpath}`);if(!B(i))throw Xu(n,{recursive:!0,force:!0}),new hD(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>Xu(n,{recursive:!0,force:!0})}}const ND=[`.ok`,`skills-lock.json`],PD=ve({source:u(),pluginProvider:u().optional(),skill:u().optional(),ref:u().optional(),contentHash:u(),files:N(u()).optional(),localHash:u().optional(),baselineRef:u().optional(),publisher:u().optional(),importedAt:a(),autoUpdate:D().optional()}),FD=ve({schema:x(1),skills:C(u(),PD).default({})});function ID(){return{schema:1,skills:{}}}function LD(e){let t;try{t=JSON.parse(e)}catch{return null}let n=FD.safeParse(t);return n.success?n.data:null}function RD(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}const zD=new Set(Object.values(eo));function BD(e,t,n,r){return e.startsWith(`open-knowledge-pack-`)?VD(e,t,n):!zD.has(e)||r?.selfIdentifiesAsPack!==!0?null:VD(e,t,n)}function VD(e,t,n){return{source:Zi,skill:e,contentHash:t,importedAt:n}}function HD(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function UD(e,t){let n=t,r=``,{frontmatter:i}=So(e);if(i!==``){let{map:e}=Io(hn(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 WD=new Set([`.git`,`node_modules`]),GD=new Set([...WD,`scripts`,`references`]);function KD(e){let t=[],n=r=>{for(let i of qu(r,{withFileTypes:!0})){let a=I(r,i.name);if(i.isDirectory()){WD.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=L(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=V(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 qD(e){let t=I(e,`SKILL.md`);return B(t)?UD(V(t,`utf-8`),Cu(e)):null}function JD(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=B(I(e,`SKILL.md`))?Qu(I(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 ${Dn}.`;if(n>67108864)return`Skill exceeds ${sr} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=qu(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=I(o,c.name);if(c.isDirectory()){WD.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=L(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=Qu(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${Dn}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${sr} 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 YD(e){let t=I(e,`SKILL.md`);if(!B(t))return null;let n=V(t,`utf-8`),{name:r,description:i}=UD(n,Cu(e)),a=KD(e),o=hd(`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(`
|
|
@@ -1170,7 +1170,7 @@ tags: [lore, history]
|
|
|
1170
1170
|
`);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{X.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Re.release(Pi))}),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()),Re.release(Pi))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),Re.release(Pi))})}let ba=`local-op-auth-signout`,Sa=q(na,async(e,t,n)=>{let r=n.host??Ui();if(!Re.tryAcquire(Fi)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:ba,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ce,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=bu(e,i,YM({...yi,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,zi,{},{handler:ba})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:ba,cause:e})}finally{Re.release(Fi)}},{handler:ba,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ba})}),wa=`/api/local-op/auth/set-identity`,Ea=`local-op-auth-set-identity`,Da=q(Eee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!j){K(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ea});return}if(!Re.tryAcquire(wa)){K(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ea,extraHeaders:{"Retry-After":`5`}});return}try{_B(j,r,i),se?.()?.refreshIdentity().catch(()=>{}),J(t,200,zi,{},{handler:Ea})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ea,cause:e})}finally{Re.release(wa)}},{handler:Ea,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ea})});async function Aa(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=se?.();if(!e){J(t,200,Yo,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),J(t,200,Yo,e.getStatus(),{handler:`sync-status`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let ja=q(ste,async(e,t,n)=>{let r=se?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;J(t,202,Ei,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?se?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Ma(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=se?.();J(t,200,Oee,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Na=q(Tee,async(e,t,n)=>{let r=se?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),J(t,200,vee,{},{handler:`sync-resolve-conflict`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?se?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Pa(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!j){K(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){K(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=Gx(i),o=s.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=se?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!o&&!l){K(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=mc({baseDir:j,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=Gx(i),o=s.documents.get(a),c=``,l=!1,u=null;if(o){let e=o.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Te?Te(a):null;t!==null&&(c=t,l=!0)}else{gL(I(j,i),j);try{c=V(I(j,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;J(t,200,Wa,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),a=e.present?e.content:``,o=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=Gx(i),t=s.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=Te?Te(e):null;t!==null&&!X_e(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else X.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}J(t,200,Wa,{file:i,base:a,ours:l,theirs:o,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function Fa(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=JJ(a);if(a!==null&&a!==``&&o===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,go,{plan:await tY({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof FJ){K(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof IJ){K(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Ia=q(Ni,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){K(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=JJ(a);if(typeof a==`string`&&a.length>0&&o===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,zee,{result:await $J(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})}),La=q(qee,async(e,t,n)=>{let r=JJ(n.packId);if(r===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-install-pack-skill`,detail:`Pack id "${n.packId}" is not registered.`});return}try{J(t,200,Hi,await PJ(l,r),{handler:`seed-install-pack-skill`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install pack skill.`,{handler:`seed-install-pack-skill`,cause:e})}},{handler:`seed-install-pack-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-install-pack-skill`})});async function za(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}J(t,200,aa,{packs:YJ()},{handler:`seed-packs`})}}let Ba=q(so,async(e,t,n)=>{if(n.out!==void 0&&!IG(n.out)){K(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{J(t,200,Vee,await kI({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function Ga(e,t){if(r(e,t,{handler:`installed-agents`}))try{await $de(e,t,at.probeAll)}catch(n){t.headersSent||(X.error({err:n,requestId:fS(e)},`[installed-agents] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}function Ka(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return K(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=R(l),o=i===``?a:R(a,i);return o!==a&&!o.startsWith(`${a}${z}`)?(K(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}function qa(e,t,n=`template`){return!e||!Sn.test(e)?(K(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Ja(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:R(e,i);if(a!==e&&!a.startsWith(`${e}${z}`))continue;let o=R(a,`.ok`,`templates`,`${n}.md`);if(B(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Ya(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 Qa=_W({GET:q(Rt,async(e,t)=>{try{let n=Ka(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await XA(n.folderRel,{projectDir:n.resolvedContentDir}),i=R(R(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,ck.parse)(await ld(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);X.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}J(t,200,Zr,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:q(hee,async(e,t,n)=>{try{if(Pe){K(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Ka(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=fue({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(tr(e,Xn(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await nr(`folder-config-put`))}J(t,200,lee,{applied:i},{handler:`folder-config-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`}),to=q(Rt,async(e,t)=>{try{let{entries:e,truncated:n}=qpe({homedirOverride:me});J(t,200,At,{themes:e,truncated:n},{handler:`saved-themes-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list saved themes.`,{handler:`saved-themes-list`,cause:e})}},{handler:`saved-themes-list`,method:`GET`,skipBodyParse:!0}),no=q(yr,async(e,t,n)=>{try{let e=await Xpe({name:n.name,stem:n.stem,scheme:n.scheme,extension:n.extension,homedirOverride:me,lockTimeoutMs:ge});if(!e.ok){if(e.code===`lock-timeout`){K(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-save`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`name-taken`){K(t,409,`urn:ok:error:theme-name-taken`,`A saved theme with that name already exists.`,{handler:`saved-theme-save`,detail:n.name});return}K(t,400,`urn:ok:error:theme-name-invalid`,`That name cannot be used as a theme id.`,{handler:`saved-theme-save`,detail:e.code});return}J(t,201,mt,{id:e.id,filename:e.filename},{handler:`saved-theme-save`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to save theme.`,{handler:`saved-theme-save`,cause:e})}},{handler:`saved-theme-save`,method:`POST`}),ro=q(Rt,async(e,t)=>{try{let n=Fc(e).get(`id`)??``;if(n===``){K(t,400,`urn:ok:error:invalid-request`,`Missing theme id.`,{handler:`saved-theme-delete`});return}let r=await Qpe({id:n,homedirOverride:me,lockTimeoutMs:ge});if(!r.ok){if(r.code===`lock-timeout`){K(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-delete`,detail:r.code,extraHeaders:{"Retry-After":`5`}});return}K(t,r.code===`invalid-id`?400:409,`urn:ok:error:invalid-request`,`Cannot delete saved theme.`,{handler:`saved-theme-delete`,detail:r.code});return}J(t,200,ite,r.existed?{existed:!0,filename:r.filename,scheme:r.scheme}:{existed:!1},{handler:`saved-theme-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete theme.`,{handler:`saved-theme-delete`,cause:e})}},{handler:`saved-theme-delete`,method:`DELETE`,skipBodyParse:!0}),oo=_W({POST:no,PUT:q(tte,async(e,t,n)=>{try{let e=await Zpe({id:n.id,scheme:n.scheme,homedirOverride:me,lockTimeoutMs:ge});if(!e.ok){if(e.code===`lock-timeout`){K(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-update`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`not-found`){K(t,404,`urn:ok:error:not-found`,`Saved theme not found.`,{handler:`saved-theme-update`});return}if(e.code===`ambiguous-id`||e.code===`unsafe-target`){K(t,409,`urn:ok:error:invalid-request`,e.code===`ambiguous-id`?`Multiple saved theme files claim that id.`:`The saved theme id conflicts with a file that cannot be safely updated.`,{handler:`saved-theme-update`,detail:e.code});return}K(t,400,`urn:ok:error:invalid-request`,`Not a saved theme id.`,{handler:`saved-theme-update`,detail:e.code});return}J(t,200,fee,{id:e.id,filename:e.filename},{handler:`saved-theme-update`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to update theme.`,{handler:`saved-theme-update`,cause:e})}},{handler:`saved-theme-update`,method:`PUT`}),DELETE:ro},{handler:`saved-theme`});function co(e,t,n){let r=s.documents.get(e);return r&&vS(r)?(xS(n,new bS({file:`${e}.md`}),t),!0):!1}function lo(e,t,n){let r=s.documents.get(e);return r&&vS(r)?(xS(n,new bS({file:`${e}.md`}),t),!0):!1}let uo=q(Rt,VB(async(e,t)=>{let n=await Kle(R(l));J(t,200,Mo,{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}),po=e=>{let{body:t}=So(e);return{frontmatter:Ho(e)??{},body:t}},_o=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!qa(r,t,`template-get`))return;let i=Ka(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Ja(o,a,r);if(!s){K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=lt(await ld(c,`utf-8`)),f=d.identity,p=d.starterContent;J(t,200,qr,{template:{name:r,folder:l,scope:u,path:L(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),vo=q(Wee,async(e,t,n)=>{try{if(Pe){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!qa(r,t,`template-put`))return;let i=Ka(n.folder,t,`folder`,`template-put`);if(!i||co(qo(i.folderRel,r),`template-put`,t))return;let a=bj({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Ya(n.frontmatter)});if(!a.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=R(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),s=!B(o),l=L(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=qo(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=zn(n),h=await c.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{zb(h.dc.document,a.content,`agent`)},h.origin);let g=await Lt(u);if(g?.kind===`failure`){Bt(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){Vt(t,`template-put`);return}sn(u,a.content),tr(e,Xn(`template`,i.folderRel,r),`${s?`template-create`:`template-edit`}: ${l}`),await nr(`template-put`),J(t,200,$a,{path:l,created:s,warnings:a.warnings},{handler:`template-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),yo=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!qa(r,t,`template-delete`))return;let i=Ka(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=ko(n,pe);if(a.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(co(qo(i.folderRel,r),`template-delete`,t))return;await fn([qo(i.folderRel,r)],`deleted-upstream`);let o=Cue({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(tr(a,Xn(`template`,i.folderRel,r),`template-delete: ${o.path}`),await nr(`template-delete`),we?.setDeleted(qo(i.folderRel,r))),J(t,200,ti,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),bo=_W({GET:_o,PUT:vo,POST:q(He,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!qa(n.fromName,t,`template-move`)||!qa(n.toName,t,`template-move`))return;let r=Ka(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Ka(n.toFolder,t,`folder`,`template-move`);if(!i||co(qo(r.folderRel,n.fromName),`template-move`,t))return;await fn([qo(r.folderRel,n.fromName)],`renamed`);let a=await wue({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await PZ(j,e,t);return n||NZ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Ja(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){K(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){K(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}we?.setDeleted(qo(r.folderRel,n.fromName));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=mr(V(R(i.resolvedContentDir,a.toPath),`utf-8`))}catch{e=null}if(e===null)o={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=Sue({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Ya(n.frontmatter)});t.ok||(o=t.error)}}try{sn(qo(i.folderRel,n.toName),V(R(i.resolvedContentDir,a.toPath),`utf-8`))}catch{}if(tr(e,Xn(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await nr(`template-move`),A?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}J(t,200,Xi,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:yo},{handler:`template`}),xo=q(ci,async(e,t,n)=>{try{if(Pe){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!LZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=Tt(r);if(tS(i)||nS(i)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let a=yZ(l,`file`,i);if(!B(a)){K(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let o=s.documents.get(i);if(n.deleteSource){let e=se?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=o!==void 0&&vS(o),a=n.has(r);if(i||a){xS(t,new bS({file:r}),`template-import`);return}}let u=``;if(o)u=o.getText(`source`).toString();else{let e=await s.openDirectConnection(i);try{let n=e.document;if(!n){K(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=bZ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!qa(d,t,`template-import`))return;let f=Ka(n.targetFolder,t,`folder`,`template-import`);if(!f||co(qo(f.folderRel,d),`template-import`,t))return;let{frontmatter:p,body:m}=So(u),h=hn(p),g={};try{h.trim()&&(g=(0,ck.parse)(h))}catch{}let v=n.title||g?.title||kA(u,d),y=g?.description||``,b=Array.isArray(g?.tags)?g.tags:[],x={...g};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,ck.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=bj({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){K(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=R(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!B(w),E=L(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),ee=qo(f.folderRel,d),{agentId:te,agentName:D,colorSeed:ne,clientName:O}=zn(n),re=await c.getSession(ee,te,{displayName:D,colorSeed:ne,clientName:O});re.dc.document.transact(()=>{zb(re.dc.document,C.content,`agent`)},re.origin);let k=await Lt(ee);if(k?.kind===`failure`){Bt(t,k.failure,`template-import`);return}if(k?.kind===`divergence`){Vt(t,`template-import`);return}sn(ee,C.content),tr(e,Xn(`template`,f.folderRel,d),`template-import: ${E}`),n.deleteSource&&(await fn([i],`deleted-upstream`),we&&we.setDeleted(i),zs(a),_?.({kind:`delete`,path:a,docName:i})),await nr(`template-import`),A?.(`files`),J(t,200,cee,{path:E,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Co(e,t,n){return!e||e.length>64||!Ji.test(e)?(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function wo(e,t,n){let r=It.safeParse(e??`project`);return r.success?r.data:(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let To=me??nd(),Eo=w_e({contentDir:l,skillsHome:To,effectiveInstallMode:Ro});function Do(e){return R(e===`global`?To:l,`.ok`,`skills`)}function Oo(e,t,n){let r=R(Do(e),t);if(e===`global`){if(n!==void 0){let e=pL(To).find(e=>e.name===t&&e.hosts.includes(n));return e?R(To,e.dir):null}let e=mL(To,t);return e===null?B(I(r,`SKILL.md`))?r:null:e}let i=fL(l).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?R(l,i.dir):n===void 0&&B(I(r,`SKILL.md`))?r:null}function ko(e,t){let n=e.searchParams;return fk({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 jo(e,t){let n=e===`project`?j:To;if(!n)return`symlink`;try{return Ns(I(n,...ND)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function No(e){let t=e===`project`?j:To;return t?I(t,...ND):null}function Po(e,t,n,r={}){let i=No(e);return i?wJ(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 Fo(e,t,n){let r=No(e),i=No(t);if(!r||!i)return!1;let a=SJ(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await wJ(i,e=>({...e,skills:{...e.skills,[n]:o}})),await wJ(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function Io(e,t,n){let r=No(e);return r?wJ(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function Lo(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];K(e,r,i,t.error,{handler:n,detail:t.code})}function Ro(e,t,n){let r=e===`project`?j:To;return(r?S_e(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function zo(e){let t=Oo(`project`,e);return t?L(l,t).split(z).join(`/`):`${hs}/${e}`}let Bo=XF.project;function Vo(e,t,n){let r=[],i=null,a=[...Tr.map(e=>({id:e,root:br[e]??``})),{id:`agents`,root:Ue}];for(let{id:o,root:s}of a){if(!s)continue;let a=R(e,...s.split(`/`),t);B(R(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=R(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:L(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function Uo(e){let t=UO(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 Wo(e,t){if(!QF(t))return null;let n=Vo(e,t);if(!n)return null;let r=YD(n.dir)?.contentHash??``,i;try{i=Qu(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:Zi,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function Go(e,t,n){let r=Vo(e,t);if(!r)return null;let i;try{let{frontmatter:e}=po(V(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=Wo(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:Uo(a)}:{}}}function Ko(e,t,n){return QF(e)?(K(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function qo(e,t){return Ge(e,t)}function Xo(e){return e===`navigation`||e===`relevance`?e:void 0}function Zo(e,t){return L(t===`global`?To:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Qo(e){return e===`global`?To:j}async function $o(e,t,n,r={}){let i=await wN(e,t),a=n===`project`?l:To;if(r.purge!==void 0){qI(t,e,Tr,FI(n));for(let e of the(a,n,t,r.purge.contentHash))Js(e,{recursive:!0,force:!0});return i!==null}if(!B(R(Do(n),t,`SKILL.md`))){let r=(n===`project`?fL(l):pL(To)).find(e=>e.name===t);if(r){let a=n===`project`?l:To,o=R(a,r.dir),s=R(a,`.agents`,`skills`),c=I(s,t);if(B(s)&&!B(I(c,`SKILL.md`))){let e=!1;try{e=H(o)===H(c)}catch{e=!1}e||qs(o,c,{recursive:!0,dereference:!0})}return KI({canonicalAbs:B(I(c,`SKILL.md`))?c:o,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...Tr],roots:FI(n)}),i!==null}}return qI(t,e,Tr,FI(n)),i!==null}function es(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=qu(e,{withFileTypes:!0})}catch(r){return P(`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()||!Ji.test(a.name))continue;if(n.length>=500){i=!0;break}let r=R(e,a.name,`SKILL.md`);if(!B(r))continue;let o;try{let{frontmatter:e}=po(V(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Zo(r,t),absolutePath:r})}return{skills:n,truncated:i}}function ts(e){return`!/${F(e).split(z).join(`/`)}/`}let is=q(lte,VB(async(e,t,n)=>{if(!Co(n.name,t,`skill-track-in-git`))return;if(n.scope!==`project`){K(t,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let r=fL(l).find(e=>e.name===n.name)?.dir??`.ok/skills/${n.name}`,i=lZ(R(l,r,`SKILL.md`),l)??`${r}/SKILL.md`,a=F(i),o=i,s=ts(a),c=`.gitignore`,u=R(l,c);if(be&&!be.isPathIgnored(o)){J(t,200,it,{line:s,gitignorePath:c,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(n.apply!==!0){J(t,200,it,{line:s,gitignorePath:c,applied:!1},{handler:`skill-track-in-git`});return}let d=B(u)?V(u,`utf-8`):null;if((d??``).split(`
|
|
1171
1171
|
`).some(e=>e.trim()===s)){K(t,409,`urn:ok:error:invalid-request`,`"${s}" is already in ${c}, but ${o} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}if(ed(u,`${d===null||d.endsWith(`
|
|
1172
1172
|
`)||d===``?d??``:`${d}\n`}${s}\n`,`utf-8`),await be?.rebuildIgnorePatterns(),be?.isPathIgnored(o)){d===null?Xu(u,{force:!0}):ed(u,d,`utf-8`),await be.rebuildIgnorePatterns(),K(t,409,`urn:ok:error:invalid-request`,`Adding "${s}" did not make ${o} trackable — another .gitignore rule excludes a parent directory. ${c} was left unchanged.`,{handler:`skill-track-in-git`});return}A?.(`files`),J(t,200,it,{line:s,gitignorePath:c,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`}),as={lastKey:null},os=q(Rt,VB(async(e,t)=>{let n=Do(`project`),r=es(n,`project`),i=es(Do(`global`),`global`),a=[...Tr],o=OI(To).map(e=>e.editorId),s=j?xN(j).skills:{},c=xN(To).skills,u=j?LD(B(I(j,...ND))?V(I(j,...ND),`utf-8`):``)??null:null,d=Uo,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&&Ps(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=j?mX(j):{},m=(e,t,n)=>{let r=[];for(let i of t??[]){let t=R(e,i.path);if(n!==void 0&&t===R(n))continue;let a=!1;try{a=Vu(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(H(t)===H(n))continue}catch{}r.push(i.path)}}return{drift:r}},h=j?iL(l,`project`):{},g=cL(h,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=sL(`project`),y=sL(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=j?fL(l).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?u?.skills[e.name]??Wo(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:R(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(j,b(t?p[e.name]:void 0,g),R(l,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...Ro(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...QF(e.name)?{managed:!0}:{}}}):[],C=mX(To),w=Ns(I(To,...ND)),T=iL(To,`global`),E=cL(T,`global`),ee=new Set(pL(To).map(e=>e.name));i.skills=i.skills.filter(e=>!ee.has(e.name));let te=new Set,D=pL(To).map(e=>{let t=!te.has(e.name);te.add(e.name);let n=t?C[e.name]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:R(To,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(To,b(n,E),R(To,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=b(n,E).filter(e=>!_(e.path,y));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...Ro(`global`,e.name,e)===`link`?{linkMode:!0}:{},...QF(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??Wo(To,e.name);return n?{origin:d(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),ne=new Set(S.map(e=>e.name)),O=j&&!r.skills.some(e=>e.name===Bo)&&!ne.has(Bo)?Go(j,Bo,`project`):null,re=new Set(D.map(e=>e.name)),k=tI.map(e=>XF[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!re.has(e)).map(e=>Go(To,e,`global`)).filter(e=>e!==null),A=new Set(S.map(e=>e.name)),ie={skills:[...f(r,s,!0).filter(e=>!A.has(e.name)),...S,...f(i,c,!1),...D,...O?[O]:[],...k].map(e=>{let t=e.scope===`project`&&e.absolutePath?lZ(e.absolutePath,l):null,n=t===null||t===e.path?e:{...e,canonicalPath:t},r=t??e.path;return e.scope===`project`&&be?.isPathIgnored(r)===!0?{...n,ignored:!0}:n}),truncated:r.truncated||i.truncated};await Q_e(S.map(e=>e.path),be??null,as),J(t,200,Ut,ie,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),cs=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Co(r,t,`skill-get`))return;let i=wo(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(QF(r)){let e=i===`global`?To:j,a=e?Vo(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=po(await ld(a.skillMd,`utf-8`));J(t,200,da,{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:YI(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=Oo(i,r,a);if(o===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:a===void 0?`Skill "${r}" not found in ${i} scope.`:`No skill "${r}" (${i}) in ${a}.`});return}let s=R(o,`SKILL.md`),{frontmatter:c,body:l}=po(await ld(s,`utf-8`));J(t,200,da,{skill:{name:r,scope:i,path:Zo(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:YI(o)}},{handler:`skill-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function ls(e,t){if(!(!k||sS(e))){if(be)try{await be.rebuildIgnorePatterns()}catch{}await Yt(e,t,`skill-put`)}}let us=q(bt,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Co(n.name,t,`skill-put`)||Ko(n.name,t,`skill-put`))return;let r=rj({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?l:To,a=Oo(n.scope,n.name);if(a===null){let a=lL(i,n.scope);if(a===null){K(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let o=ij({skillsRoot:R(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:o.error.code,cause:Error(o.error.message)});return}n.scope===`project`&&(tr(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await nr(`skill-put`)),await ls(n.scope===`project`?`${a}/${n.name}/SKILL`:or(`global`,n.name),r.content),A?.(`files`),J(t,200,Gn,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=L(i,a).split(z).join(`/`),s=`${o}/SKILL.md`,u=n.scope===`project`?`${o}/SKILL`:or(n.scope,n.name);if(lo(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=zn(n),h=await c.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{zb(h.dc.document,r.content,`agent`)},h.origin);let g=await Lt(u);if(g?.kind===`failure`){Bt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){Vt(t,`skill-put`);return}n.scope===`project`&&(tr(e,Xn(`skill`,``,n.name),`skill-edit: ${s}`),await nr(`skill-put`)),await ls(u,r.content),A?.(`files`),J(t,200,Gn,{path:s,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function ds(e,t){let n=e===`project`?l:To,r=Oo(e,t);return{root:r===null?Do(e):F(r),dirRel:r===null?`.ok/skills/${t}`:L(n,r).split(z).join(`/`),realDir:r}}function fs(e,t){let n=e===`project`?l:To,r=(e===`project`?fL(l):pL(To)).find(e=>e.name===t);r&&KI({canonicalAbs:R(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>Si(e)),roots:FI(e)})}let gs=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Co(r,t,`skill-delete`))return;let i=wo(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=ds(i,r),s=ko(n,pe);if(s.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await fn(i===`project`?[...new Set([`${o}/SKILL`,or(i,r)])]:[or(i,r)],`deleted-upstream`),fs(i,r);let c=lj({skillsRoot:a,name:r}),l=Do(i);if(c.ok&&l!==a&&B(R(l,r,`SKILL.md`))){let e=lj({skillsRoot:l,name:r});e.ok||X.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(tr(s,o,`skill-delete: ${o}`),await nr(`skill-delete`)),A?.(`files`));let u=Qo(i);u&&await $o(u,r,i),J(t,200,kee,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),_s=q(ft,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Co(n.fromName,t,`skill-move`)||!Co(n.toName,t,`skill-move`)||Ko(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=ds(n.scope,n.fromName);if(Oo(n.scope,n.toName)!==null){K(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=Qo(n.scope),o=a?xN(a).skills[n.fromName]:void 0,s=n.scope===`project`?l:To,c=(n.scope===`project`?fL(l):pL(To)).find(e=>e.name===n.fromName),u=c?F(c.dir):null,d=u===null?[]:Object.entries(iL(s,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?jI(o.hosts):[],...c?jI(c.hosts):[],...jI(d)])];await fn(n.scope===`project`?[...new Set([`${i}/SKILL`,or(n.scope,n.fromName)])]:[or(n.scope,n.fromName)],`renamed`),fs(n.scope,n.fromName);let p=await gue({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await PZ(j,e,t);return n||NZ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){K(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;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:p.error.code,cause:Error(p.error.message)});return}let m=null,h=R(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=po(V(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=ij({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=che({base:n.scope===`project`?l:To,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){P(`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 be?.rebuildIgnorePatterns(),await Ds(r,n.fromName,n.toName),await Os(x,n.toName)}catch(e){P(`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=Zo(R(r,n.fromName),n.scope),C=Zo(R(r,n.toName),n.scope);n.scope===`project`&&(tr(e,Xn(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await nr(`skill-move`));let w=Ps(r,n.toName),T=n.scope===`project`?await Fs(Is(e),C):void 0;if(await Po(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await wN(a,n.fromName),qI(n.fromName,a,f,FI(n.scope));let e=R(r,n.toName);if(f.length>0){let t=BI(e,n.toName,a,f,jo(n.scope,n.toName),FI(n.scope));await CN(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??NI(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(A?.(`files`),m){let e=m.code===`WRITE_ERROR`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:m.code,cause:Error(m.message)});return}J(t,200,Ot,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),vs=q(Bee,async(e,t,n)=>{let{name:r,home:i}=n;if(!Co(r,t,`skill-edit-external`))return;let a;try{a=H(i)}catch{K(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!Qu(a).isDirectory()||!B(R(a,`SKILL.md`))){K(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}az(r,a),J(t,200,ji,{docName:Hr(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),ys=q($ee,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move-scope`});return}let{name:r,fromScope:i,toScope:a}=n;if(!Co(r,t,`skill-move-scope`))return;if(i===a){K(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:s,realDir:c}=ds(i,r),u=R(o,r),d=(()=>{try{return H(u)}catch{return u}})(),f=a===`project`?l:To,p=lL(f,a);if(p===null){K(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available in the destination scope.`,{handler:`skill-move-scope`,detail:`NO_USABLE_SKILL_HOME`});return}let m=R(f,p),h=R(m,r);if(c===null||!B(u)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(R(c)===R(h)||B(h)&&H(c)===H(h)){K(t,409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{handler:`skill-move-scope`,detail:`SAME_STORAGE`});return}if(Oo(a,r)!==null||B(h)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let g=Qo(i),_=Qo(a),v=g?xN(g).skills[r]:void 0,y=i===`project`?l:To,b=(i===`project`?fL(l):pL(To)).find(e=>e.name===r),x=b?F(b.dir):null,S=x===null?[]:Object.entries(iL(y,i)).filter(([,e])=>e===x).map(([e])=>e),C=[...new Set([...v?jI(v.hosts):[],...b?jI(b.hosts):[],...jI(S)])];await fn([...new Set([...i===`project`?[`${s}/SKILL`]:[],or(i,r),or(a,r)])],`renamed`),Ws(m,{recursive:!0}),qs(d,h,{recursive:!0,dereference:!0}),fs(i,r);let w=lj({skillsRoot:o,name:r});if(w.ok&&d!==u){let e=L((()=>{try{return H(y)}catch{return y}})(),d);e!==``&&!e.startsWith(`..`)&&!Eu(e)&&Js(d,{recursive:!0,force:!0})}if(!w.ok){lj({skillsRoot:m,name:r}),K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:w.error.code,cause:Error(w.error.message)});return}let T=await Fo(i,a,r);if(g&&await $o(g,r,i,b?{purge:{contentHash:b.contentHash}}:{}),g&&await C_e(g,r),_&&C.length>0){let e=BI(h,r,_,C,jo(a,n.name),FI(a));await CN(_,r,{...v,scope:a,hosts:e,scripts:v?.scripts??NI(h,r).hasScripts,installedAt:v?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(tr(e,i===`project`?s:L(l,h).split(z).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await nr(`skill-move-scope`)),T){let t=Ps(m,r),n=a===`project`?await Fs(Is(e),L(l,h).split(z).join(`/`)):void 0;await Io(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!B(I(h,`SKILL.md`))){K(t,500,`urn:ok:error:internal-server-error`,`The move did not leave a readable skill at the destination; nothing was reported as moved.`,{handler:`skill-move-scope`,detail:L(f,h).split(z).join(`/`)});return}await be?.rebuildIgnorePatterns(),A?.(`files`),J(t,200,uee,{scope:a,path:L(f,h).split(z).join(`/`)},{handler:`skill-move-scope`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),bs=q(yee,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!Co(n.name,t,`skill-duplicate`)||!Co(n.toName,t,`skill-duplicate`)||Ko(n.toName,t,`skill-duplicate`))return;let r=Oo(n.scope,n.name);if(r===null||!B(I(r,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?l:To,a=lL(i,n.scope);if(a===null){K(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let o=R(i,a),s=R(o,n.toName);if(Oo(n.scope,n.toName)!==null||B(s)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let c=YD(r);if(!c){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}Ws(o,{recursive:!0}),qs(r,s,{recursive:!0,dereference:!0});let{fenced:u,body:d}=bi(c.skillMd),f=xa(u,{name:n.toName});if(!f.ok){lj({skillsRoot:o,name:n.toName}),K(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:f.error.kind});return}try{$s(I(s,`SKILL.md`),`${f.nextFenced}${d}`)}catch(e){throw lj({skillsRoot:o,name:n.toName}),e}if(n.scope===`project`){let t=L(l,s).split(z).join(`/`);tr(e,Xn(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await nr(`skill-duplicate`)}A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,ao,{name:n.toName},{handler:`skill-duplicate`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),xs=_W({GET:cs,PUT:us,POST:_s,DELETE:gs},{handler:`skill`});function Ss(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 Cs(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function ws(e,t){let n=t.replace(/\.md$/i,``);return`${Xr(e).replace(/\/SKILL$/,``)}/${n}`}function Ts(e,t){let n=R(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of qu(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(R(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function Ds(e,t,n){if(!k){P(`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=V(n,`utf-8`)}catch(i){P(`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=L(l,e).split(z).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),R(e,n,`SKILL.md`));for(let r of Ts(e,n))i(o(t,r),o(n,r),R(e,n,r));await k.recordDirectMutations(r)}async function Os(e,t){if(!k||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 k.recordDirectMutations(n)}let ks=_W({GET:q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Co(r,t,`skill-file-get`))return;let i=wo(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=QF(r)?i===`global`?To:j:void 0,s=n.searchParams.get(`host`)??void 0,c=o?Vo(o,r,s):null;if(a===``||a.includes(`\0`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:Ss(a))??`reference`,u=s,d=o?c?.dir??null:Oo(i,r,u);if(d===null&&u!==void 0){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${r}" (${i}) in ${u}.`});return}let f=d??R(Do(i),r),p=R(f,a);if(p!==f&&!p.startsWith(`${f}${z}`)){K(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let m=p,h=a;if(!B(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Ln.map(t=>`${e[1]}${t}`).find(e=>e!==a&&B(R(f,e))):void 0;if(n===void 0){K(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}h=n,m=R(f,n)}let g=await ld(m);if(g.includes(0)){K(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}J(t,200,Kee,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Bi,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Co(n.name,t,`skill-file-put`)||Ko(n.name,t,`skill-file-put`))return;let r=Ss(n.path);if(r===null){K(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){K(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=Oo(n.scope,n.name);if(i===null||!B(I(i,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=L(n.scope===`project`?l:To,i).split(z).join(`/`),o=n.path.replace(/\\/g,`/`),s=Cs(n.scope,r,o),u;if(s){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(lo(e,`skill-file-put`,t))return;if(u=!B(R(i,o)),u&&oj(i)>=50){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:s,colorSeed:l,clientName:d}=zn(n),f=await c.getSession(e,r,{displayName:s,colorSeed:l,clientName:d});f.dc.document.transact(()=>{zb(f.dc.document,n.content,`agent`)},f.origin);let p=await Lt(e);if(p?.kind===`failure`){Bt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){Vt(t,`skill-file-put`);return}}else{let e=sj({skillsRoot:F(i),name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;K(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}u=e.created}n.scope===`project`&&(tr(e,Xn(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),await nr(`skill-file-put`)),A?.(`files`),J(t,200,ra,{path:o,created:u,kind:r,content:s},{handler:`skill-file-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!Co(i,t,`skill-file-delete`)||Ko(i,t,`skill-file-delete`))return;let a=wo(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=Ss(o);if(s===null){K(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=ko(n,pe);if(c.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=Oo(a,i),d=u===null?Do(a):F(u);if(B(R(u??I(d,i),o))&&Cs(a,s,o)){let e=o.replace(/\.md$/i,``);await fn([u===null?ws(i,o):`${L(l,u).split(z).join(`/`)}/${e}`],`deleted-upstream`)}let f=cj({skillsRoot:d,name:i,relPath:o});if(!f.ok){let e=f.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:f.error.code,cause:Error(f.error.message)});return}f.existed&&a===`project`&&(tr(c,Xn(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${L(l,u).split(z).join(`/`)}/${o}`}`),await nr(`skill-file-delete`)),f.existed&&A?.(`files`),J(t,200,Ree,{path:o,existed:f.existed,kind:s},{handler:`skill-file-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),As=q(ho,async(e,t,n)=>{try{if(!Co(n.name,t,`skill-file-rename`)||Ko(n.name,t,`skill-file-rename`))return;let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let r=n.from.replace(/\\/g,`/`),i=n.to.replace(/\\/g,`/`),a=Ss(r),o=Ss(i);if(a===null||o===null){K(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=Oo(n.scope,n.name);if(s===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let c=F(s),u=Cs(n.scope,a,r),d=Cs(n.scope,o,i),f=L(l,s).split(z).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&lo(p,`skill-file-rename`,t))return;p!==null&&await fn([p],`deleted-upstream`);let h=hue({skillsRoot:c,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;K(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(k){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:V(R(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:V(R(c,n.name,i),`utf-8`)})}catch{}await Jt(e,`skill-file-rename`)}n.scope===`project`&&(tr(e,Xn(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await nr(`skill-file-rename`)),A?.(`files`),J(t,200,Ha,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){X.error({err:e},`[skill-file-rename] failed`),t.headersSent||K(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function js(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let Ns=SJ;function Ps(e,t){return YD(R(e,t))?.contentHash}async function Fs(e,t){let n=E?.current;if(!(!n||!e))try{let r=bx(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
|
|
1173
|
-
`).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 nr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Is=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ls(e){try{let t=Qo(e.scope);if(!t)return;let n=PI(t);if(n.length===0)return;let r=BI(R(e.skillsRoot,e.name),e.name,t,n,`copy`,FI(e.scope));if(r.length===0)return;await CN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Rs(e,t){if(t.ok){J(e,200,Xee,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let Bs=g_e({contentDir:l,skillsHome:To,...j===void 0?{}:{projectDir:j},resolveSkillDirForRead:Oo,parseFrontmatterDoc:po,attributeOkArtifactWrite:tr,commitOkArtifactWrite:nr,shadowHeadSha:Fs,artifactWriterId:Is,effectiveInstallMode:Ro,signalFiles:()=>A?.(`files`)}),Vs=q(_ee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await aO(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??AD(d);if(!p){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(xX(t,p,`skill-import`))return;let m=await MD(p);r=m.cleanup,s=m.ref;let h=XD(m.dir);if(h.length===0){K(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=>qD(e.dir)?.name===f)??h.find(e=>e.name===eo[f]);if(!e){K(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){K(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??js(d)}catch(e){if(e instanceof hD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Bs.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||Ca(u))&&TI({source:u,skills:[d.body.name]},uI()),await be?.rebuildIgnorePatterns(),Rs(t,d)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Hs=q(pee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await aO(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??AD(d);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(xX(t,f,`skills-import-bulk`))return;if(l=e?.publisher??js(d),f.kind===`well-known`)a=f,o=await TD(f.origin);else{let e=await MD(f);r=e.cleanup,c=e.ref,s=XD(e.dir)}}catch(e){if(e instanceof hD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await MD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof hD?`not-found`:`failed`,warnings:[],...e instanceof hD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>YD(e.dir)?.name===t)??s.find(e=>e.name===eo[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Bs.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){P(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.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){P(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||Ca(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&TI({source:u,skills:e},uI())}await be?.rebuildIgnorePatterns(),J(t,200,Br,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),Us=8*1024*1024,Gs=32*1024*1024;function Ys(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=R(e,n);return r!==e&&!r.startsWith(e+z)?null:r}function Xs(e){return new Promise((t,n)=>{let r;try{r=Oq(e,{files:200,fields:10,fieldSize:2*1024,fileSize:Us})}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>Gs){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 Qs(e,t){return new Promise((n,r)=>{(0,$ce.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=Ys(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){Ws(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>Us){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>Gs){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{Ws(F(n),{recursive:!0}),$s(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 ec(e,t){let n=Uu(I(ad(),`ok-skill-upload-`)),r=()=>{try{Js(n,{recursive:!0,force:!0})}catch{}};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=wo(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=fk({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},pe);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Xs(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Qs(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Ys(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}Ws(F(r),{recursive:!0}),$s(r,e.data)}let u=XD(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];Rs(t,await Bs.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let tc=q(ote,async(e,t,n)=>{try{let e=Do(n.scope);if(!Co(n.name,t,`skill-install`))return;if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Qo(n.scope),i=R(e,n.name),a=n.scope===`project`?l:To,o=(n.scope===`project`?fL(l):pL(To)).find(e=>e.name===n.name),s=o?R(a,o.dir):i;if(!B(s)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Lt(n.scope===`project`?`${L(a,s).split(z).join(`/`)}/SKILL`:or(n.scope,n.name));let c=NI(s,n.name);if(!c.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=Eo.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:o.hosts.filter(Si),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.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){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await Eo.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?K(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" 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`}):K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(Si),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await Eo.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?j:To;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Ar.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?j:To;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Ar.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?j:To,l=await Ar.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!l.ok)switch(l.kind){case`invalid-location`:K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(l.kind)}`)}A?.(`files`),J(t,200,rs,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f===void 0?OI(To).map(e=>e.editorId).filter(e=>Tr.includes(e)):Tr.filter(e=>f?.some(t=>t===e)):f===void 0?PI(r):Tr.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===void 0?n.scope===`global`&&B(I(To,`.agents`)):f.includes(`agents`))?[...h,`agents`]:[...h],a=n.scope===`project`?j:To,l=d===void 0?Ro(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await Eo.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}A?.(`files`),J(t,200,rs,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await Eo.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:l,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),A?.(`files`),J(t,200,rs,{name:n.name,hosts:v.hosts,scripts:c.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=jI(xN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&qI(n.name,r,v,FI(n.scope));let y=I(r,...ND),b=B(y)?V(y,`utf-8`):null,x=b===null?null:LD(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=BI(s,n.name,r,h,C,FI(n.scope));w.length===0?await wN(r,n.name):await CN(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),A?.(`files`),J(t,200,rs,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),nc=q(Fr,async(e,t,n)=>{try{if(!Co(n.name,t,`skill-uninstall`))return;let e=Qo(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await $o(e,n.name,n.scope);A?.(`files`),J(t,200,Zt,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),rc=_W({GET:q(Rt,async(e,t)=>{try{let e=PI(j??``),n=(e,t)=>{let n=b_e(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,on,{targets:e,configured:!1,folders:[...j?cX(l,oL(l,`project`)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...cX(To,oL(To,`global`)).map(e=>({...e,scope:`global`,...n(To,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(An,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:To;if(e.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await x_e(r,i.join(`/`)),A?.(`files`),J(t,200,ur,{targets:PI(j??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(oL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?y_e({base:r,folderRel:e.root,targetRootRel:a}):uX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await pX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),A?.(`files`),J(t,200,ur,{targets:PI(j??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),ic=q(jee,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Co(n.name,t,`skill-restore`)||Ko(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=E?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await CX({shadow:r,contentDir:l,contentRoot:re??`.`,name:n.name,version:n.version,skillDirRel:zo(n.name)});if(!i.ok){Lo(t,i,`skill-restore`);return}let a=[],o=NI(R(l,zo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),tr(e,Xn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await nr(`skill-restore`),A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,tee,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),ac=q(Fee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Co(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?To:l,{root:a,dirRel:o,realDir:s}=ds(n.scope,n.name),c=!o.startsWith(`${hs}/`);if(s===null||!B(R(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=I(n.scope===`global`?To:j,...ND),d=Ns(u).skills[n.name];if(!d){let e=BD(n.name,YD(R(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:K_e(R(a,n.name))})??Wo(i,n.name);e&&(d=e)}if(!d){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await wJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=eo[e],a=await aO(d.source,e).catch(async e=>{if(i===void 0)throw e;return aO(d.source,i)}),o=a?.source??WO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??AD(o);if(!c){K(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(xX(t,c,`skill-reimport`))return;let l=await MD(c);r=l.cleanup,f=l.ref;let u=XD(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>YD(e.dir)?.name===n.name)??u.find(e=>e.name===eo[s??n.name])??(u.length===1?u[0]:void 0);if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=JD(m.dir);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=YD(m.dir)}catch(e){if(e instanceof hD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=sX(p);if(h){K(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=YD(R(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){await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=po(p.skillMd).body;if(n.dryRun){let e=YD(R(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&j)try{let e=mc({baseDir:j,timeout:{block:15e3}}),t=L(j,R(a,n.name)).split(z).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!0,source:d.source,localBody:po(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 fn(e,`deleted-upstream`)}let x=ij({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=sj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:oX});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=cj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(tr(e,Xn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await nr(`skill-reimport`));let C=Ps(a,n.name),w=n.scope===`project`?await Fs(Is(e),o):void 0;await wJ(u,e=>RD(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 Ls({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),oc=q(ree,async(e,t,n)=>{try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Co(n.name,t,`skill-revert`)||Ko(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=I(j,...ND),i=Ns(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=E?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await CX({shadow:a,contentDir:l,contentRoot:re??`.`,name:n.name,version:i.baselineRef,skillDirRel:zo(n.name)});if(!o.ok){Lo(t,o,`skill-revert`);return}tr(e,Xn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await nr(`skill-revert`);let s=R(l,zo(n.name),`..`),c=Ps(s,n.name);await wJ(r,e=>RD(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Do(`project`)&&await Ls({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),A?.(`files`),J(t,200,$n,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function sc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function cc(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 lc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function uc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let dc=m_e({contentDir:l,projectDir:j,getAllFilesIndex:g,getFileIndexGeneration:v,getSearchMaxEntries:eve,semanticSearch:De,getSemanticSimilarityFloor:Oe,ready:Ce,getProjectSkillsRoot:()=>Do(`project`),parseFrontmatterDoc:po});dc.prewarm();let fc=_W({GET:q(Rt,VB(async(e,t)=>{let n=Fc(e),r=n.get(`limit`),i=n.get(`query`)??``,a=sc(n.get(`intent`)),o=Xo(n.get(`ranking`)),s=cc(n.get(`scope`)??n.get(`scopes`)),c=lc(n.get(`semantic`)),l=uc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,Za,await dc.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Uee,VB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=sc(n.intent),a=Xo(n.ranking),o=cc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=lc(n.semantic),l=uc(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,Za,await dc.buildSearchResponse({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`}),pc=q(Rt,VB(async(e,t)=>{J(t,200,See,{...await SI(nd())},{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 gc(e,t){if(r(e,t,{handler:`handoff`}))try{await ofe(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:at.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:fS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function _c(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await rN(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:fS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let vc=q(kt,async(e,t,n)=>{try{if(!j){NF(`no-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`no-remote`},{handler:MF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!$pe(e,n.kind)){NF(`invalid-path`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`invalid-path`},{handler:MF});return}let r=ime(j);if(r===null){if(LF(j).kind===`no-remote`){NF(`no-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`no-remote`},{handler:MF});return}NF(`detached-head`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`detached-head`},{handler:MF});return}let i=LF(j);if(i.kind===`no-remote`){NF(`no-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`no-remote`},{handler:MF});return}if(i.kind===`non-github`){NF(`non-github-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`non-github-remote`},{handler:MF});return}if(!lme(j,r)){NF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,xt,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:MF});return}let a=OZ(j,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&&P(`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=eme(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=tme(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Fte(s)}`,u=await nme(j,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);NF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,xt,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:MF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:MF,cause:e})}},{handler:MF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:MF})}),yc=q(Rt,async(e,t)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:iB});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(!dr(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:iB});return}if(!nB(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:iB});return}J(t,200,pt,await rB(j,r,i,a),{handler:iB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:iB,cause:e})}},{handler:iB,method:`GET`,skipBodyParse:!0}),bc=q(iee,async(e,t,n)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:YF});return}if(!nB(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:YF});return}let e=OZ(j,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}`;J(t,200,er,await _me(j,n.branch,r,n.kind),{handler:YF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:YF,cause:e})}},{handler:YF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:YF})}),xc=q(ete,async(e,t,n)=>{if(fk(n,pe).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:lB});return}if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lB});return}try{J(t,200,dee,await hc(()=>dB(j,n.branch,{fastForward:n.fastForward===!0})),{handler:lB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lB,cause:e})}},{handler:lB,method:`POST`});async function Sc(e){let[t,...n]=ce,r=[...n,...e];return await new Promise((e,n)=>{let i=bu(t,r,YM({...vi,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},HF),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 ${HF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=JF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Cc=q(Rt,async(e,t)=>{if(!Re.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:zF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Sc([`share`,`owners`,`--json`]),n=ume(GF(e));qF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,Ze,n,{handler:zF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zF,cause:e})}finally{Re.release(`/api/share/publish/owners`)}},{handler:zF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:zF})}),Tc=q(Rt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!WF(r)||!UF(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:BF});return}if(!Re.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:BF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Sc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=dme(GF(e));qF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Iee,n,{handler:BF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BF,cause:e})}finally{Re.release(`/api/share/publish/name-check`)}},{handler:BF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:BF})}),Ec=q(Mee,async(e,t,n)=>{if(!j){qF(`publish-create`,`no-project`),J(t,200,Fn,{ok:!1,error:`no-project`},{handler:VF});return}if(!WF(n.owner)||!UF(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:VF});return}if(!Re.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:VF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,j,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Sc(e),i=mme(GF(r));qF(`publish-create`,i.ok?`ok`:i.error),i.ok&&se?.()?.refreshRemote().catch(()=>{}),J(t,200,Fn,i,{handler:VF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:VF,cause:e})}finally{Re.release(`/api/share/publish`)}},{handler:VF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:VF})}),Dc=q(Kr,async(e,t,n)=>{try{let e=P(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,si,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Oc=j?Bk(j):null;async function Ac(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:ole(e.headers),previewUrl:null,port:Oc?kc(Oc)?.port??0:0,singleFile:Pe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,Ua,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function jc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Le?.()??{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}J(t,200,de,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Mc=`local-op-embeddings-set-key`,Nc=`local-op-embeddings-clear-key`,Pc=`/api/local-op/embeddings`;function Ic(){let e=Ae?.();return{projectDir:j??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Lc=q(Yee,async(e,t,n)=>{if(!Re.tryAcquire(Pc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Mc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Ic();await new $j(ke).setForProject(e,r,n.key),De?.reloadCredential(),J(t,200,mi,{keyPresent:!0},{handler:Mc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Mc,cause:e})}finally{Re.release(Pc)}},{handler:Mc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Mc})}),Rc=q(Rt,async(e,t)=>{if(!Re.tryAcquire(Pc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Nc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Ic();await new $j(ke).clearForProject(e,n),De?.reloadCredential(),J(t,200,mi,{keyPresent:!1},{handler:Nc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Nc,cause:e})}finally{Re.release(Pc)}},{handler:Nc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Nc})}),zc=`local-op-embeddings-test`,Bc=`/api/local-op/embeddings/test`,Vc=q(Rt,async(e,t)=>{if(!Re.tryAcquire(Bc)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:zc,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 Kj(new $j(ke),j??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await nde({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,ate,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:zc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:zc,cause:e})}finally{Re.release(Bc)}},{handler:zc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:zc})}),Hc=q(Rt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(De){let t=De.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Ae?.()?.baseUrl??`https://api.openai.com/v1`,o=await Kj(new $j(ke),j??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of m())!tS(e)&&!nS(e)&&!ps(e)&&(f+=1);J(t,200,Ao,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Uc=0;function Wc(){Uc+=1,A?.(`lint-config`)}let Gc=()=>`${Uc} ${t.getActiveBranch()} ${k?.readLocalTargetGeneration?.()??0}`;async function Kc(e,t){let n=je?.()??Or;try{let r=await ya(e,zP(l,n,{docName:t,projectDir:j??l,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ne?.()??`warning`;if(k&&a!==`off`&&!sS(t)){await Xt(t,e,`lint-validation`);let r=mF({projectDir:j??l,contentDir:l,baseConfig:n,derivedDocumentIndex:k,linksValidation:a,admittedDocNames:qt,docFilePathFor:e=>TZ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:TZ(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}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function qc(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=HP({projectDir:j??l,contentDir:l});return dP(t.schemas,n)}let Jc=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!LZ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=je?.()??Or,i=[],a=IP(l,n??void 0,e=>i.push(e)),o=RP(j??l,LP(r,a),e=>i.push(e));n===null&&i.push(...qc(o)),J(t,200,ss,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Yc=q(ut,async(e,t,n)=>{let r;try{r=QP(R(l),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Wc();try{let e=je?.()??Or,n=[],r=IP(l,void 0,e=>n.push(e)),i=RP(j??l,LP(e,r),e=>n.push(e));n.push(...qc(i)),J(t,200,ss,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Xc=q(la,async(e,t,n)=>{let r;try{let e=R(j??l),t=n.parentPath??[];r=n.delete?ope(e,n.file):n.field!==void 0&&n.removeField?ipe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?ape(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?npe(e,n.file,n.field,n.constraint,t):rpe(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&A?.(`files`),Wc();try{let e=je?.()??Or,n=[],r=IP(l,void 0,e=>n.push(e)),i=RP(j??l,LP(e,r),e=>n.push(e));n.push(...qc(i)),J(t,200,ss,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),Zc=q(Rt,async(e,t)=>{try{let e=R(j??l),{schemas:n,truncated:r}=Mfe(e),i=new Set(n),a=!1;if(be!==void 0){let t=hZ({contentDir:l,contentFilter:be,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&&fo(a)){let t=L(e,R(l,a));!t.startsWith(`..`)&&!Eu(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,gee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Qc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=s.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},$c=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!LZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=TZ(l,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=je?.()??Or,a=[],o=await VP({projectDir:j??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Qc});J(t,200,bee,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof RM){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),el=new sP,tl=bX();function nl(e,t,n){let r=`${n} ${Gc()} ${t??``}`;return tl.run(r,()=>Tpe(e,{targetPath:t})).promise}function rl(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let il=q(Rt,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&&!gZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=je?.()??Or;J(t,200,Jee,await UP({projectDir:j??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:Qc,cache:el,auditGeneration:Gc}),{handler:`lint-audit`})}catch(e){if(e instanceof BP){rl(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),al=q(Rt,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&&!gZ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!gZ(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=TZ(l,o)??`${o}.md`}let s=je?.()??Or,c=await nl(mF({projectDir:j??l,contentDir:l,baseConfig:s,liveSourceFor:Qc,derivedDocumentIndex:k??null,linksValidation:Ne?.(),admittedDocNames:qt,docFilePathFor:e=>TZ(l,e),cache:el,auditGeneration:Gc}),i,sP.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){J(t,200,Qee,wpe(c),{handler:`audit`});return}J(t,200,Cr,c,{handler:`audit`})}catch(e){if(e instanceof BP){rl(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),ol=q(nte,async(t,n,r)=>{try{let t=vZ(r.docName,n,`lint-fix`);if(t===null)return;let i=Tt(t),a=fk(r,pe);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(tS(i)||nS(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=TZ(l,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}qM(R(l,f),l);let p=je?.()??Or,{stored:m}=Hn(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await $fe({projectDir:j??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Jo(d),n=Ra[t]??ca(u??o);ae?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{xw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,yw(h))},h.origin),a.kind!==`anonymous`&&Dj(i,o,s,u,void 0,a.kind===`agent`?Vn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{ae?.touchMode(o,`idle`)}let t=await Lt(i);if(t?.kind===`failure`){Bt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Vt(n,`lint-fix`);return}Mt(i,`lint-fix`);try{b=await ya(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,hr,{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 RM){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof bS){xS(n,e,`lint-fix`);return}if(e instanceof TS){OS(n,e,`lint-fix`);return}if(e instanceof jw){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),sl=`link-preview`,cl=new TG({cacheDir:Pe?null:R(j??l,`.ok`,`local`,`link-previews`)}),ll=null,ul=()=>(ll??=cl.init(),ll),dl=Fe??gG;async function fl(e){let t=await dl(e);return t.ok?{ok:!0,metadata:await xG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:dl})}:{ok:!1,reason:t.reason}}let pl=()=>{try{return Ie?.()===!0}catch{return!1}},ml=q(yt,async(e,t,n)=>{try{if(!pl()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,Wn,{ok:!1,reason:`disabled`},{handler:sl});return}await ul();let e=!1,r=await cl.load(n.url,()=>(e=!0,fl(n.url)));cl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,Wn,i,{handler:sl})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:sl,cause:e})}},{handler:sl,method:`POST`,preBodyGate:(e,t)=>{let n=OG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:sl}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:sl}),!1)}}),hl=gle({service:dt,getPrincipal:pe,onChanged:()=>A?.(`comments`)}),gl=_W({GET:hl.list,POST:hl.create},{handler:`comments`}),_l=_W({GET:hl.read,POST:hl.mutate,DELETE:hl.remove},{handler:`comment`}),{handleSkillsSearch:vl,handleSkillsPopular:yl,handleSkillsPublisher:bl,handleSkillsDetail:xl,handleSkillsPreview:Sl,handleSkillsDiscover:Cl,handleSkillsResolveRef:wl}=A_e({log:X,skillsHome:To,projectDir:j,contentDir:l,resolveSkillDirForRead:Oo}),Tl={"/api/config":Ac,"/api/config/diagnostics":jc,"/api/generated-index/settings":_W({GET:q(Rt,async(e,t)=>{if(!d){K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}J(t,200,FZ,d(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:q(mve,async(e,t,n)=>{if(!f){K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}J(t,200,FZ,await f(n.enabled),{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`}),"/api/comments":gl,"/api/comment":_l,"/api/asset":Qr,"/api/asset-text":ei,"/api/comment-counts":pr,"/api/link-preview":ml,"/api/folder-config":Qa,"/api/saved-themes":to,"/api/saved-theme":oo,"/api/template":bo,"/api/template/import":xo,"/api/templates":uo,"/api/skill":xs,"/api/skill-file":ks,"/api/skill-file/rename":As,"/api/skills":os,"/api/skills/installed":cr,"/api/skills/search":vl,"/api/skills/popular":yl,"/api/skills/publisher":bl,"/api/skills/detail":xl,"/api/skills/preview":Sl,"/api/skills/discover":Cl,"/api/skills/resolve-ref":wl,"/api/skill/import":Vs,"/api/skills/import-bulk":Hs,"/api/skill/edit-external":vs,"/api/skill/duplicate":bs,"/api/skill/move-scope":ys,"/api/skill-upload":ec,"/api/skill/install":tc,"/api/skill/uninstall":nc,"/api/skill/restore":ic,"/api/skill/reimport":ac,"/api/skill/revert":oc,"/api/skill/track-in-git":is,"/api/skill-targets":rc,"/api/search":fc,"/api/semantic-status":Hc,"/api/lint/config":Jc,"/api/lint/markdownlint-config":Yc,"/api/lint/frontmatter-schema":Xc,"/api/lint/frontmatter-schemas":Zc,"/api/lint":$c,"/api/lint/audit":il,"/api/lint/fix":ol,"/api/audit":al,"/api/create-page":ri,"/api/create-folder":ai,"/api/duplicate-path":oi,"/api/rename-path":li,"/api/delete-path":ui,"/api/trash/cleanup":di,"/api/upload":fi,"/api/agent-write":rr,"/api/agent-write-md":ir,"/api/agent-write-batch":ar,"/api/frontmatter-patch":sr,"/api/agent-patch":gr,"/api/agent-undo":_r,"/api/agent-activity":vr,"/api/agent-burst-diff":xr,"/api/save-version":jr,"/api/history":Mr,"/api/rollback":Pr,"/api/__embed-detect":Wr,"/api/server-info":Lr,"/api/acp/catalog":zr,"/api/share/construct-url":vc,"/api/share/target-status":bc,"/api/git/branch-info":yc,"/api/git/checkout":xc,"/api/share/publish/owners":Cc,"/api/share/publish/name-check":Tc,"/api/share/publish":Ec,"/api/principal":Ur,"/api/rescue":ni,"/api/workspace":Gr,"/api/sync/status":Aa,"/api/sync/trigger":ja,"/api/sync/conflicts":Ma,"/api/sync/conflict-content":Pa,"/api/sync/resolve-conflict":Na,"/api/local-op/clone":Ci,"/api/local-op/ok-init":ki,"/api/local-op/auth/login":$i,"/api/local-op/auth/status":pa,"/api/local-op/auth/pat":ha,"/api/local-op/auth/gh-login":ia,"/api/local-op/auth/cancel":sa,"/api/local-op/auth/repos":_a,"/api/local-op/auth/signout":Sa,"/api/local-op/auth/set-identity":Da,"/api/local-op/embeddings/set-key":Lc,"/api/local-op/embeddings/clear-key":Rc,"/api/local-op/embeddings/test":Vc,"/api/installed-agents":Ga,"/api/spawn-cursor":_c,"/api/handoff":gc,"/api/install-skill":Ba,"/api/skill/install-state":pc,"/api/seed/plan":Fa,"/api/seed/apply":Ia,"/api/seed/install-pack-skill":La,"/api/seed/packs":za,"/api/client-logs":Dc};T&&(Tl[`/api/test-reset`]=wr,Tl[`/api/test-flush-git`]=Sr,Tl[`/api/test-rescan-backlinks`]=Er,Tl[`/api/test-rescan-files`]=Dr);let El=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/generated-index/settings./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/saved-theme./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/skill/track-in-git./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),Dl=[`/api/local-op/`],Ol=BB({log:X,policy:n,ephemeral:Pe,table:{resolve(e){let t=Tl[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await Nr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>El.has(e)||Dl.some(t=>e.startsWith(t))}}),kl=pW({hocuspocus:s,derivedDocumentIndex:k,getFileIndex:m,isSafeDocName:LZ,readPageTitleForDocName:ht,readPageTitleForLinkedDocName:gt,readFrontmatterMetadataForLinkedDocName:Ct,collectAdmittedDocNames:qt,resolveAlias:Tt,respondToDerivedIndexQueryFailure:en}),Al=[kl,vW({hocuspocus:s,agentPresenceBroadcaster:ae,isAllowedWorkspaceHostHeader:a,log:X}),Be],jl=Al.flatMap(e=>[...e.paths]);BU(jl,Tl);let Ml=Al.map(e=>BB({log:X,policy:n,ephemeral:Pe,table:e.table})),Nl={paths:jl,dispatch:async(e,t)=>{for(let n of Ml)if(await n(e,t))return!0;return!1}},Pl=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]);for(let e of Pl)if(Tl[e]===void 0&&kl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await Ol(e,t)},nativeApi:Nl,localApi:gW({resolve:e=>{if(!Pl.has(e))return;let t=Tl[e];return t===void 0?kl.table.resolve(e)?.dispatch:t}})}}function zZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=Tu(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!AB(f,o)){K(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!MB(e.headers.host,o)){K(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:TB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=ZY(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=De.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function BZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function gve(e){let t;try{t=qu(e.contentDir,{withFileTypes:!0})}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Wx(n.name,w)&&e.basenameIndex.add(n.name)}async function VZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await ud(i,{withFileTypes:!0})}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=I(i,o.name),s=UM(L(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await cd(a)}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await dd(a)}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!WM(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await fd(i)}catch(t){let n=BZ(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()&&Wx(a,ue)&&!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()&&Wx(a,ue)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const HZ=M({principalId:u().optional(),tabSessionId:u().optional(),expectedServerInstanceId:u().optional(),expectedBranch:u().optional(),expectedDocLineageEpoch:u().optional(),clientProtocolVersion:i().optional(),clientRuntimeVersion:u().optional(),clientKind:u().optional()}).loose(),UZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function WZ(e){return UZ.includes(e)}function GZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function _ve(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!WZ(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 KZ=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=GZ(e,this.payload)}};function qZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=HZ.safeParse(t);return n.success?n.data:void 0}var JZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const YZ=P(`conflict-storage`);var XZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=I(Bk(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!B(this.storePath)){this.conflicts=[];return}try{let e=V(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){YZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){YZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=F(this.storePath);B(e)||Hu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return ed(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return YZ.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-DQRBUWfE.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=R(this.projectDir),r=R(t,e);if(!WM(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);gL(r,t),$s(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`]),YZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Jb(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){YZ.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}),YZ.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=R(this.projectDir),a=R(i,e.file);if(!WM(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(gL(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-DQRBUWfE.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);gL(a,i),$s(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);$s(a,n,`utf-8`);break;case`delete`:B(a)&&zs(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function vve(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 yve(e,t){let n=Bk(e);try{Hu(n,{recursive:!0}),ed(I(n,to),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=lc(e);Hu(F(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`};ed(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const ZZ=new Map;let QZ=!1;function bve(e,t){try{let n=vve(e,t);for(let e of ZZ.keys())yve(e,n)}catch{}}function xve(e){ZZ.set(e,(ZZ.get(e)??0)+1),QZ||(QZ=!0,process.on(`uncaughtExceptionMonitor`,bve));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=ZZ.get(e)??0;n<=1?ZZ.delete(e):ZZ.set(e,n-1)}}}function $Z(e){let t=e.scheduler??Wi,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 eQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tQ(e){if(!B(e))return{};let t;try{t=(0,ck.parse)(V(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!eQ(t))return{};let n=t.telemetry;if(!eQ(n))return{};let r=n.localSink;return eQ(r)?r:{}}function nQ(e){return typeof e==`boolean`?e:void 0}function Sve(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function rQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function iQ(e){if(eQ(e))return Sve(e.maxBytes)}function Cve(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=tQ(Us(`project`,e.projectDir)),n=tQ(Us(`project-local`,e.projectDir));if((nQ(n.enabled)??nQ(t.enabled)??!0)===!1)return null;let r=iQ(n.spans)??iQ(t.spans)??52428800,i=iQ(n.logs)??iQ(t.logs)??26214400,a=rQ(n.attributeDenylist)??rQ(t.attributeDenylist)??_e;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 wve;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(wve||={});const oQ=aQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),sQ=e=>{switch(typeof e){case`undefined`:return oQ.undefined;case`string`:return oQ.string;case`number`:return Number.isNaN(e)?oQ.nan:oQ.number;case`boolean`:return oQ.boolean;case`function`:return oQ.function;case`bigint`:return oQ.bigint;case`symbol`:return oQ.symbol;case`object`:return Array.isArray(e)?oQ.array:e===null?oQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?oQ.promise:typeof Map<`u`&&e instanceof Map?oQ.map:typeof Set<`u`&&e instanceof Set?oQ.set:typeof Date<`u`&&e instanceof Date?oQ.date:oQ.object;default:return oQ.unknown}},Z=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 cQ=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()}};cQ.create=e=>new cQ(e);const lQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===oQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,aQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${aQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${aQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${aQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:aQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,aQ.assertNever(e)}return{message:n}};let Tve=lQ;function uQ(){return Tve}const dQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function fQ(e,t){let n=uQ(),r=dQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===lQ?void 0:lQ].filter(e=>!!e)});e.common.issues.push(r)}var pQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return mQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return mQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const mQ=Object.freeze({status:`aborted`}),hQ=e=>({status:`dirty`,value:e}),gQ=e=>({status:`valid`,value:e}),_Q=e=>e.status===`aborted`,vQ=e=>e.status===`dirty`,yQ=e=>e.status===`valid`,bQ=e=>typeof Promise<`u`&&e instanceof Promise;var xQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(xQ||={});var SQ=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const CQ=(e,t)=>{if(yQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new cQ(e.common.issues);return this._error=t,this._error}}};function wQ(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var TQ=class{get description(){return this._def.description}_getType(e){return sQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:sQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new pQ,ctx:{common:e.parent.common,data:e.data,parsedType:sQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(bQ(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sQ(e)};return CQ(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>yQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sQ(e)},r=this._parse({data:e,path:n.path,parent:n});return CQ(n,await(bQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new r$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return i$.create(this,this._def)}nullable(){return a$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return VQ.create(this)}promise(){return n$.create(this,this._def)}or(e){return WQ.create([this,e],this._def)}and(e){return qQ.create(this,e,this._def)}transform(e){return new r$({...wQ(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new o$({...wQ(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new l$({typeName:Q.ZodBranded,type:this,...wQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new s$({...wQ(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return u$.create(this,e)}readonly(){return d$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Eve=/^c[^\s-]{8,}$/i,Dve=/^[0-9a-z]+$/,Ove=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kve=/^[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,Ave=/^[a-z0-9_-]{21}$/i,jve=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mve=/^[-+]?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)?)??$/,Nve=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let EQ;const Pve=/^(?:(?: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])$/,Fve=/^(?:(?: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])$/,Ive=/^(([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]))$/,Lve=/^(([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])$/,Rve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zve=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,DQ=`((\\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])))`,Bve=RegExp(`^${DQ}$`);function OQ(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 Vve(e){return RegExp(`^${OQ(e)}$`)}function Hve(e){let t=`${DQ}T${OQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Uve(e,t){return!!((t===`v4`||!t)&&Pve.test(e)||(t===`v6`||!t)&&Ive.test(e))}function Wve(e,t){if(!jve.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 Gve(e,t){return!!((t===`v4`||!t)&&Fve.test(e)||(t===`v6`||!t)&&Lve.test(e))}var kQ=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==oQ.string){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.string,received:t.parsedType}),mQ}let t=new pQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Nve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)EQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),EQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)kve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ave.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Eve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Dve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Ove.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),fQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Hve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Bve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Vve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Mve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Uve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Wve(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Gve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Rve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?zve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64url`,code:Z.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:Z.invalid_string,...xQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...xQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...xQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...xQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...xQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...xQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...xQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...xQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...xQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...xQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...xQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...xQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...xQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...xQ.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...xQ.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...xQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...xQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...xQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...xQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...xQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...xQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...xQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...xQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...xQ.errToObj(t)})}nonempty(e){return this.min(1,xQ.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};kQ.create=e=>new kQ({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...wQ(e)});function Kve(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 AQ=class e extends TQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==oQ.number){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.number,received:t.parsedType}),mQ}let t,n=new pQ;for(let r of this._def.checks)r.kind===`int`?aQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Kve(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:xQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:xQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:xQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:xQ.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&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)}};AQ.create=e=>new AQ({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...wQ(e)});var jQ=class e extends TQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==oQ.bigint)return this._getInvalidInput(e);let t,n=new pQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.bigint,received:t.parsedType}),mQ}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};jQ.create=e=>new jQ({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...wQ(e)});var MQ=class extends TQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==oQ.boolean){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.boolean,received:t.parsedType}),mQ}return gQ(e.data)}};MQ.create=e=>new MQ({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...wQ(e)});var NQ=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==oQ.date){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.date,received:t.parsedType}),mQ}if(Number.isNaN(e.data.getTime()))return fQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),mQ;let t=new pQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):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:xQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:xQ.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};NQ.create=e=>new NQ({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...wQ(e)});var PQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.symbol){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.symbol,received:t.parsedType}),mQ}return gQ(e.data)}};PQ.create=e=>new PQ({typeName:Q.ZodSymbol,...wQ(e)});var FQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.undefined,received:t.parsedType}),mQ}return gQ(e.data)}};FQ.create=e=>new FQ({typeName:Q.ZodUndefined,...wQ(e)});var IQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.null){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.null,received:t.parsedType}),mQ}return gQ(e.data)}};IQ.create=e=>new IQ({typeName:Q.ZodNull,...wQ(e)});var LQ=class extends TQ{constructor(){super(...arguments),this._any=!0}_parse(e){return gQ(e.data)}};LQ.create=e=>new LQ({typeName:Q.ZodAny,...wQ(e)});var RQ=class extends TQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gQ(e.data)}};RQ.create=e=>new RQ({typeName:Q.ZodUnknown,...wQ(e)});var zQ=class extends TQ{_parse(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.never,received:t.parsedType}),mQ}};zQ.create=e=>new zQ({typeName:Q.ZodNever,...wQ(e)});var BQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.void,received:t.parsedType}),mQ}return gQ(e.data)}};BQ.create=e=>new BQ({typeName:Q.ZodVoid,...wQ(e)});var VQ=class e extends TQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==oQ.array)return fQ(t,{code:Z.invalid_type,expected:oQ.array,received:t.parsedType}),mQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(fQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(fQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(fQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new SQ(t,e,t.path,n)))).then(e=>pQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new SQ(t,e,t.path,n)));return pQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:xQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:xQ.toString(n)}})}nonempty(e){return this.min(1,e)}};VQ.create=(e,t)=>new VQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...wQ(t)});function HQ(e){if(e instanceof UQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=i$.create(HQ(r))}return new UQ({...e._def,shape:()=>t})}else if(e instanceof VQ)return new VQ({...e._def,type:HQ(e.element)});else if(e instanceof i$)return i$.create(HQ(e.unwrap()));else if(e instanceof a$)return a$.create(HQ(e.unwrap()));else if(e instanceof JQ)return JQ.create(e.items.map(e=>HQ(e)));else return e}var UQ=class e extends TQ{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=aQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==oQ.object){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.object,received:t.parsedType}),mQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof zQ&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new SQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof zQ){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(fQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new SQ(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>pQ.mergeObjectSync(t,e)):pQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return xQ.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:xQ.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of 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 HQ(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 i$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return $Q(aQ.objectKeys(this.shape))}};UQ.create=(e,t)=>new UQ({shape:()=>e,unknownKeys:`strip`,catchall:zQ.create(),typeName:Q.ZodObject,...wQ(t)}),UQ.strictCreate=(e,t)=>new UQ({shape:()=>e,unknownKeys:`strict`,catchall:zQ.create(),typeName:Q.ZodObject,...wQ(t)}),UQ.lazycreate=(e,t)=>new UQ({shape:e,unknownKeys:`strip`,catchall:zQ.create(),typeName:Q.ZodObject,...wQ(t)});var WQ=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new cQ(e.ctx.common.issues));return fQ(t,{code:Z.invalid_union,unionErrors:n}),mQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new cQ(e));return fQ(t,{code:Z.invalid_union,unionErrors:i}),mQ}}get options(){return this._def.options}};WQ.create=(e,t)=>new WQ({options:e,typeName:Q.ZodUnion,...wQ(t)});const GQ=e=>e instanceof ZQ?GQ(e.schema):e instanceof r$?GQ(e.innerType()):e instanceof QQ?[e.value]:e instanceof e$?e.options:e instanceof t$?aQ.objectValues(e.enum):e instanceof o$?GQ(e._def.innerType):e instanceof FQ?[void 0]:e instanceof IQ?[null]:e instanceof i$?[void 0,...GQ(e.unwrap())]:e instanceof a$?[null,...GQ(e.unwrap())]:e instanceof l$||e instanceof d$?GQ(e.unwrap()):e instanceof s$?GQ(e._def.innerType):[];var qve=class e extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==oQ.object)return fQ(t,{code:Z.invalid_type,expected:oQ.object,received:t.parsedType}),mQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(fQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),mQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=GQ(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...wQ(r)})}};function KQ(e,t){let n=sQ(e),r=sQ(t);if(e===t)return{valid:!0,data:e};if(n===oQ.object&&r===oQ.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=KQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===oQ.array&&r===oQ.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=KQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===oQ.date&&r===oQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var qQ=class extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(_Q(e)||_Q(r))return mQ;let i=KQ(e.value,r.value);return i.valid?((vQ(e)||vQ(r))&&t.dirty(),{status:t.value,value:i.data}):(fQ(n,{code:Z.invalid_intersection_types}),mQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};qQ.create=(e,t,n)=>new qQ({left:e,right:t,typeName:Q.ZodIntersection,...wQ(n)});var JQ=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.array)return fQ(n,{code:Z.invalid_type,expected:oQ.array,received:n.parsedType}),mQ;if(n.data.length<this._def.items.length)return fQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),mQ;!this._def.rest&&n.data.length>this._def.items.length&&(fQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new SQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>pQ.mergeArray(t,e)):pQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};JQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new JQ({items:e,typeName:Q.ZodTuple,rest:null,...wQ(t)})};var Jve=class e extends TQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.object)return fQ(n,{code:Z.invalid_type,expected:oQ.object,received:n.parsedType}),mQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new SQ(n,e,n.path,e)),value:a._parse(new SQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?pQ.mergeObjectAsync(t,r):pQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof TQ?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...wQ(r)}):new e({keyType:kQ.create(),valueType:t,typeName:Q.ZodRecord,...wQ(n)})}},YQ=class extends TQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.map)return fQ(n,{code:Z.invalid_type,expected:oQ.map,received:n.parsedType}),mQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new SQ(n,e,n.path,[a,`key`])),value:i._parse(new SQ(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return mQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return mQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};YQ.create=(e,t,n)=>new YQ({valueType:t,keyType:e,typeName:Q.ZodMap,...wQ(n)});var XQ=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.set)return fQ(n,{code:Z.invalid_type,expected:oQ.set,received:n.parsedType}),mQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(fQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(fQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return mQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new SQ(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:xQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};XQ.create=(e,t)=>new XQ({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...wQ(t)});var Yve=class e extends TQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==oQ.function)return fQ(t,{code:Z.invalid_type,expected:oQ.function,received:t.parsedType}),mQ;function n(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),lQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),lQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof n$){let e=this;return gQ(async function(...t){let o=new cQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return gQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new cQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new cQ([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:JQ.create(t).rest(RQ.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||JQ.create([]).rest(RQ.create()),returns:n||RQ.create(),typeName:Q.ZodFunction,...wQ(r)})}},ZQ=class extends TQ{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZQ.create=(e,t)=>new ZQ({getter:e,typeName:Q.ZodLazy,...wQ(t)});var QQ=class extends TQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return fQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),mQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};QQ.create=(e,t)=>new QQ({value:e,typeName:Q.ZodLiteral,...wQ(t)});function $Q(e,t){return new e$({values:e,typeName:Q.ZodEnum,...wQ(t)})}var e$=class e extends TQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{expected:aQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),mQ}return gQ(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};e$.create=$Q;var t$=class extends TQ{_parse(e){let t=aQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==oQ.string&&n.parsedType!==oQ.number){let e=aQ.objectValues(t);return fQ(n,{expected:aQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(aQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=aQ.objectValues(t);return fQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),mQ}return gQ(e.data)}get enum(){return this._def.values}};t$.create=(e,t)=>new t$({values:e,typeName:Q.ZodNativeEnum,...wQ(t)});var n$=class extends TQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==oQ.promise&&t.common.async===!1?(fQ(t,{code:Z.invalid_type,expected:oQ.promise,received:t.parsedType}),mQ):gQ((t.parsedType===oQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};n$.create=(e,t)=>new n$({type:e,typeName:Q.ZodPromise,...wQ(t)});var r$=class extends TQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{fQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return mQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(r.value):r});{if(t.value===`aborted`)return mQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?mQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?mQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yQ(e))return mQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>yQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):mQ);aQ.assertNever(r)}};r$.create=(e,t,n)=>new r$({schema:e,typeName:Q.ZodEffects,effect:t,...wQ(n)}),r$.createWithPreprocess=(e,t,n)=>new r$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...wQ(n)});var i$=class extends TQ{_parse(e){return this._getType(e)===oQ.undefined?gQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};i$.create=(e,t)=>new i$({innerType:e,typeName:Q.ZodOptional,...wQ(t)});var a$=class extends TQ{_parse(e){return this._getType(e)===oQ.null?gQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};a$.create=(e,t)=>new a$({innerType:e,typeName:Q.ZodNullable,...wQ(t)});var o$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===oQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};o$.create=(e,t)=>new o$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...wQ(t)});var s$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return bQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new cQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new cQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};s$.create=(e,t)=>new s$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...wQ(t)});var c$=class extends TQ{_parse(e){if(this._getType(e)!==oQ.nan){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.nan,received:t.parsedType}),mQ}return{status:`valid`,value:e.data}}};c$.create=e=>new c$({typeName:Q.ZodNaN,...wQ(e)});var l$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},u$=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?mQ:e.status===`dirty`?(t.dirty(),hQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?mQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},d$=class extends TQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(yQ(e)&&(e.value=Object.freeze(e.value)),e);return bQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};d$.create=(e,t)=>new d$({innerType:e,typeName:Q.ZodReadonly,...wQ(t)}),UQ.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),kQ.create,AQ.create,c$.create,jQ.create,MQ.create,NQ.create,PQ.create,FQ.create,IQ.create,LQ.create,RQ.create,zQ.create,BQ.create,VQ.create;const Xve=UQ.create;UQ.strictCreate,WQ.create,qve.create,qQ.create,JQ.create,Jve.create,YQ.create,XQ.create,Yve.create,ZQ.create,QQ.create,e$.create,t$.create,n$.create,r$.create,i$.create,a$.create,r$.createWithPreprocess,u$.create;const Zve=fe(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);d.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>h(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>m(e,t,n),e.parseAsync=async(t,n)=>Te(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>oe(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)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Qve=fe(`ZodMiniObject`,(e,t)=>{ie.init(e,t),Zve.init(e,t),T(e,`shape`,()=>t.shape)});function f$(e,t){return new Qve({type:`object`,shape:e??{},...r(t)})}function p$(e){return!!e._zod}function m$(e){let t=Object.values(e);if(t.length===0)return f$({});let n=t.every(p$),r=t.every(e=>!p$(e));if(n)return f$(e);if(r)return Xve(e);throw Error(`Mixed Zod versions detected in object shape.`)}function h$(e,t){return p$(e)?m(e,t):e.safeParse(t)}async function g$(e,t){return p$(e)?await oe(e,t):await e.safeParseAsync(t)}function _$(e){if(!e)return;let t;if(t=p$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function v$(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 m$(e)}}if(p$(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 y$(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 $ve(e){return e.description}function eye(e){if(p$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function b$(e){if(p$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const x$=`2025-11-25`,S$=[x$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],C$=`io.modelcontextprotocol/related-task`,w$=s(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),T$=p([u(),i().int()]),E$=u();ve({ttl:i().optional(),pollInterval:i().optional()});const tye=M({ttl:i().optional()}),nye=M({taskId:u()}),D$=ve({progressToken:T$.optional(),[C$]:nye.optional()}),O$=M({_meta:D$.optional()}),k$=O$.extend({task:tye.optional()}),rye=e=>k$.safeParse(e).success,A$=M({method:u(),params:O$.loose().optional()}),j$=M({_meta:D$.optional()}),M$=M({method:u(),params:j$.loose().optional()}),N$=ve({_meta:D$.optional()}),P$=p([u(),i().int()]),F$=M({jsonrpc:x(`2.0`),id:P$,...A$.shape}).strict(),I$=e=>F$.safeParse(e).success,L$=M({jsonrpc:x(`2.0`),...M$.shape}).strict(),iye=e=>L$.safeParse(e).success,R$=M({jsonrpc:x(`2.0`),id:P$,result:N$}).strict(),z$=e=>R$.safeParse(e).success;var B$;(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`})(B$||={});const V$=M({jsonrpc:x(`2.0`),id:P$.optional(),error:M({code:i().int(),message:u(),data:_().optional()})}).strict(),H$=e=>V$.safeParse(e).success,U$=p([F$,L$,R$,V$]);p([R$,V$]);const W$=N$.strict(),aye=j$.extend({requestId:P$.optional(),reason:u().optional()}),G$=M$.extend({method:x(`notifications/cancelled`),params:aye}),K$=M({icons:N(M({src:u(),mimeType:u().optional(),sizes:N(u()).optional(),theme:Me([`light`,`dark`]).optional()})).optional()}),q$=M({name:u(),title:u().optional()}),J$=q$.extend({...q$.shape,...K$.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),oye=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,c(M({form:c(M({applyDefaults:D().optional()}),C(u(),_())).optional(),url:w$.optional()}),C(u(),_()).optional())),sye=ve({list:w$.optional(),cancel:w$.optional(),requests:ve({sampling:ve({createMessage:w$.optional()}).optional(),elicitation:ve({create:w$.optional()}).optional()}).optional()}),cye=ve({list:w$.optional(),cancel:w$.optional(),requests:ve({tools:ve({call:w$.optional()}).optional()}).optional()}),lye=M({experimental:C(u(),w$).optional(),sampling:M({context:w$.optional(),tools:w$.optional()}).optional(),elicitation:oye.optional(),roots:M({listChanged:D().optional()}).optional(),tasks:sye.optional(),extensions:C(u(),w$).optional()}),uye=O$.extend({protocolVersion:u(),capabilities:lye,clientInfo:J$}),Y$=A$.extend({method:x(`initialize`),params:uye}),X$=e=>Y$.safeParse(e).success,dye=M({experimental:C(u(),w$).optional(),logging:w$.optional(),completions:w$.optional(),prompts:M({listChanged:D().optional()}).optional(),resources:M({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:M({listChanged:D().optional()}).optional(),tasks:cye.optional(),extensions:C(u(),w$).optional()}),fye=N$.extend({protocolVersion:u(),capabilities:dye,serverInfo:J$,instructions:u().optional()}),Z$=M$.extend({method:x(`notifications/initialized`),params:j$.optional()}),pye=e=>Z$.safeParse(e).success,Q$=A$.extend({method:x(`ping`),params:O$.optional()}),mye=M({progress:i(),total:v(i()),message:v(u())}),hye=M({...j$.shape,...mye.shape,progressToken:T$}),$$=M$.extend({method:x(`notifications/progress`),params:hye}),gye=O$.extend({cursor:E$.optional()}),e1=A$.extend({params:gye.optional()}),t1=N$.extend({nextCursor:E$.optional()}),_ye=Me([`working`,`input_required`,`completed`,`failed`,`cancelled`]),n1=M({taskId:u(),status:_ye,ttl:p([i(),Ie()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:v(i()),statusMessage:v(u())}),r1=N$.extend({task:n1}),vye=j$.merge(n1),i1=M$.extend({method:x(`notifications/tasks/status`),params:vye}),a1=A$.extend({method:x(`tasks/get`),params:O$.extend({taskId:u()})}),o1=N$.merge(n1),s1=A$.extend({method:x(`tasks/result`),params:O$.extend({taskId:u()})});N$.loose();const c1=e1.extend({method:x(`tasks/list`)}),l1=t1.extend({tasks:N(n1)}),u1=A$.extend({method:x(`tasks/cancel`),params:O$.extend({taskId:u()})}),yye=N$.merge(n1),d1=M({uri:u(),mimeType:v(u()),_meta:C(u(),_()).optional()}),f1=d1.extend({text:u()}),p1=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),m1=d1.extend({blob:p1}),h1=Me([`user`,`assistant`]),g1=M({audience:N(h1).optional(),priority:i().min(0).max(1).optional(),lastModified:a({offset:!0}).optional()}),_1=M({...q$.shape,...K$.shape,uri:u(),description:v(u()),mimeType:v(u()),size:v(i()),annotations:g1.optional(),_meta:v(ve({}))}),bye=M({...q$.shape,...K$.shape,uriTemplate:u(),description:v(u()),mimeType:v(u()),annotations:g1.optional(),_meta:v(ve({}))}),v1=e1.extend({method:x(`resources/list`)}),xye=t1.extend({resources:N(_1)}),y1=e1.extend({method:x(`resources/templates/list`)}),Sye=t1.extend({resourceTemplates:N(bye)}),b1=O$.extend({uri:u()}),Cye=b1,x1=A$.extend({method:x(`resources/read`),params:Cye}),wye=N$.extend({contents:N(p([f1,m1]))}),Tye=M$.extend({method:x(`notifications/resources/list_changed`),params:j$.optional()}),Eye=b1,Dye=A$.extend({method:x(`resources/subscribe`),params:Eye}),Oye=b1,kye=A$.extend({method:x(`resources/unsubscribe`),params:Oye}),Aye=j$.extend({uri:u()}),jye=M$.extend({method:x(`notifications/resources/updated`),params:Aye}),Mye=M({name:u(),description:v(u()),required:v(D())}),Nye=M({...q$.shape,...K$.shape,description:v(u()),arguments:v(N(Mye)),_meta:v(ve({}))}),S1=e1.extend({method:x(`prompts/list`)}),Pye=t1.extend({prompts:N(Nye)}),Fye=O$.extend({name:u(),arguments:C(u(),u()).optional()}),C1=A$.extend({method:x(`prompts/get`),params:Fye}),w1=M({type:x(`text`),text:u(),annotations:g1.optional(),_meta:C(u(),_()).optional()}),T1=M({type:x(`image`),data:p1,mimeType:u(),annotations:g1.optional(),_meta:C(u(),_()).optional()}),E1=M({type:x(`audio`),data:p1,mimeType:u(),annotations:g1.optional(),_meta:C(u(),_()).optional()}),Iye=M({type:x(`tool_use`),name:u(),id:u(),input:C(u(),_()),_meta:C(u(),_()).optional()}),Lye=M({type:x(`resource`),resource:p([f1,m1]),annotations:g1.optional(),_meta:C(u(),_()).optional()}),D1=p([w1,T1,E1,_1.extend({type:x(`resource_link`)}),Lye]),Rye=M({role:h1,content:D1}),zye=N$.extend({description:u().optional(),messages:N(Rye)}),Bye=M$.extend({method:x(`notifications/prompts/list_changed`),params:j$.optional()}),Vye=M({title:u().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Hye=M({taskSupport:Me([`required`,`optional`,`forbidden`]).optional()}),O1=M({...q$.shape,...K$.shape,description:u().optional(),inputSchema:M({type:x(`object`),properties:C(u(),w$).optional(),required:N(u()).optional()}).catchall(_()),outputSchema:M({type:x(`object`),properties:C(u(),w$).optional(),required:N(u()).optional()}).catchall(_()).optional(),annotations:Vye.optional(),execution:Hye.optional(),_meta:C(u(),_()).optional()}),k1=e1.extend({method:x(`tools/list`)}),Uye=t1.extend({tools:N(O1)}),A1=N$.extend({content:N(D1).default([]),structuredContent:C(u(),_()).optional(),isError:D().optional()});A1.or(N$.extend({toolResult:_()}));const Wye=k$.extend({name:u(),arguments:C(u(),_()).optional()}),j1=A$.extend({method:x(`tools/call`),params:Wye}),Gye=M$.extend({method:x(`notifications/tools/list_changed`),params:j$.optional()});M({autoRefresh:D().default(!0),debounceMs:i().int().nonnegative().default(300)});const M1=Me([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Kye=O$.extend({level:M1}),N1=A$.extend({method:x(`logging/setLevel`),params:Kye}),qye=j$.extend({level:M1,logger:u().optional(),data:_()}),Jye=M$.extend({method:x(`notifications/message`),params:qye}),Yye=M({hints:N(M({name:u().optional()})).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),Xye=M({mode:Me([`auto`,`required`,`none`]).optional()}),Zye=M({type:x(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:N(D1).default([]),structuredContent:M({}).loose().optional(),isError:D().optional(),_meta:C(u(),_()).optional()}),Qye=Pe(`type`,[w1,T1,E1]),P1=Pe(`type`,[w1,T1,E1,Iye,Zye]),$ye=M({role:h1,content:p([P1,N(P1)]),_meta:C(u(),_()).optional()}),ebe=k$.extend({messages:N($ye),modelPreferences:Yye.optional(),systemPrompt:u().optional(),includeContext:Me([`none`,`thisServer`,`allServers`]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:N(u()).optional(),metadata:w$.optional(),tools:N(O1).optional(),toolChoice:Xye.optional()}),tbe=A$.extend({method:x(`sampling/createMessage`),params:ebe}),F1=N$.extend({model:u(),stopReason:v(Me([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:h1,content:Qye}),I1=N$.extend({model:u(),stopReason:v(Me([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:h1,content:p([P1,N(P1)])}),nbe=M({type:x(`boolean`),title:u().optional(),description:u().optional(),default:D().optional()}),rbe=M({type:x(`string`),title:u().optional(),description:u().optional(),minLength:i().optional(),maxLength:i().optional(),format:Me([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),ibe=M({type:Me([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),abe=M({type:x(`string`),title:u().optional(),description:u().optional(),enum:N(u()),default:u().optional()}),obe=M({type:x(`string`),title:u().optional(),description:u().optional(),oneOf:N(M({const:u(),title:u()})),default:u().optional()}),sbe=p([p([M({type:x(`string`),title:u().optional(),description:u().optional(),enum:N(u()),enumNames:N(u()).optional(),default:u().optional()}),p([abe,obe]),p([M({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:M({type:x(`string`),enum:N(u())}),default:N(u()).optional()}),M({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:M({anyOf:N(M({const:u(),title:u()}))}),default:N(u()).optional()})])]),nbe,rbe,ibe]),cbe=p([k$.extend({mode:x(`form`).optional(),message:u(),requestedSchema:M({type:x(`object`),properties:C(u(),sbe),required:N(u()).optional()})}),k$.extend({mode:x(`url`),message:u(),elicitationId:u(),url:u().url()})]),lbe=A$.extend({method:x(`elicitation/create`),params:cbe}),ube=j$.extend({elicitationId:u()}),dbe=M$.extend({method:x(`notifications/elicitation/complete`),params:ube}),L1=N$.extend({action:Me([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,C(u(),p([u(),i(),D(),N(u())])).optional())}),fbe=M({type:x(`ref/resource`),uri:u()}),pbe=M({type:x(`ref/prompt`),name:u()}),mbe=O$.extend({ref:p([pbe,fbe]),argument:M({name:u(),value:u()}),context:M({arguments:C(u(),u()).optional()}).optional()}),R1=A$.extend({method:x(`completion/complete`),params:mbe});function hbe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function gbe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const _be=N$.extend({completion:ve({values:N(u()).max(100),total:v(i().int()),hasMore:v(D())})}),vbe=M({uri:u().startsWith(`file://`),name:u().optional(),_meta:C(u(),_()).optional()}),ybe=A$.extend({method:x(`roots/list`),params:O$.optional()}),z1=N$.extend({roots:N(vbe)}),bbe=M$.extend({method:x(`notifications/roots/list_changed`),params:j$.optional()});p([Q$,Y$,R1,N1,C1,S1,v1,y1,x1,Dye,kye,j1,k1,a1,s1,c1,u1]),p([G$,$$,Z$,bbe,i1]),p([W$,F1,I1,L1,z1,o1,l1,r1]),p([Q$,tbe,lbe,ybe,a1,s1,c1,u1]),p([G$,$$,Jye,jye,Tye,Gye,Bye,i1,dbe]),p([W$,fye,_be,zye,Pye,xye,Sye,wye,A1,Uye,o1,l1,r1]);var B1=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===B$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new xbe(e.elicitations,n)}return new e(t,n,r)}},xbe=class extends B1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(B$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function V1(e){return e===`completed`||e===`failed`||e===`cancelled`}const Sbe=Symbol(`Let zodToJsonSchema decide on which parser to use`),H1={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`},Cbe=e=>typeof e==`string`?{...H1,name:e}:{...H1,...e},wbe=e=>{let t=Cbe(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 U1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function W1(e,t,n,r,i){e[t]=n,U1(e,t,r,i)}const G1=(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 K1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?G1(t,e.currentPath):t.join(`/`)}}function Tbe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=a0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&W1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&W1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(W1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),W1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Ebe(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?W1(n,`minimum`,r.value,r.message,t):W1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),W1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?W1(n,`maximum`,r.value,r.message,t):W1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),W1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:W1(n,`multipleOf`,r.value,r.message,t);break}return n}function Dbe(){return{type:`boolean`}}function q1(e,t){return a0(e.type._def,t)}const Obe=(e,t)=>a0(e.innerType._def,t);function J1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>J1(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 kbe(e,t)}}const kbe=(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`:W1(n,`minimum`,r.value,r.message,t);break;case`max`:W1(n,`maximum`,r.value,r.message,t);break}return n};function Abe(e,t){return{...a0(e.innerType._def,t),default:e.defaultValue()}}function jbe(e,t){return t.effectStrategy===`input`?a0(e.schema._def,t):K1(t)}function Mbe(e){return{type:`string`,enum:Array.from(e.values)}}const Nbe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Pbe(e,t){let n=[a0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),a0(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(Nbe(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 Fbe(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 Y1;const X1={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:()=>(Y1===void 0&&(Y1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Y1),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 Z1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:W1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:W1(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`:$1(n,`email`,r.message,t);break;case`format:idn-email`:$1(n,`idn-email`,r.message,t);break;case`pattern:zod`:e0(n,X1.email,r.message,t);break}break;case`url`:$1(n,`uri`,r.message,t);break;case`uuid`:$1(n,`uuid`,r.message,t);break;case`regex`:e0(n,r.regex,r.message,t);break;case`cuid`:e0(n,X1.cuid,r.message,t);break;case`cuid2`:e0(n,X1.cuid2,r.message,t);break;case`startsWith`:e0(n,RegExp(`^${Q1(r.value,t)}`),r.message,t);break;case`endsWith`:e0(n,RegExp(`${Q1(r.value,t)}$`),r.message,t);break;case`datetime`:$1(n,`date-time`,r.message,t);break;case`date`:$1(n,`date`,r.message,t);break;case`time`:$1(n,`time`,r.message,t);break;case`duration`:$1(n,`duration`,r.message,t);break;case`length`:W1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),W1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:e0(n,RegExp(Q1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&$1(n,`ipv4`,r.message,t),r.version!==`v4`&&$1(n,`ipv6`,r.message,t);break;case`base64url`:e0(n,X1.base64url,r.message,t);break;case`jwt`:e0(n,X1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&e0(n,X1.ipv4Cidr,r.message,t),r.version!==`v4`&&e0(n,X1.ipv6Cidr,r.message,t);break;case`emoji`:e0(n,X1.emoji(),r.message,t);break;case`ulid`:e0(n,X1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:$1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:W1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:e0(n,X1.base64,r.message,t);break}break;case`nanoid`:e0(n,X1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Q1(e,t){return t.patternStrategy===`escape`?Lbe(e):e}const Ibe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Lbe(e){let t=``;for(let n=0;n<e.length;n++)Ibe.has(e[n])||(t+=`\\`),t+=e[n];return t}function $1(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}}})):W1(e,`format`,t,n,r)}function e0(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:t0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):W1(e,`pattern`,t0(t,r),n,r)}function t0(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
|
|
1173
|
+
`).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 nr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Is=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ls(e){try{let t=Qo(e.scope);if(!t)return;let n=PI(t);if(n.length===0)return;let r=BI(R(e.skillsRoot,e.name),e.name,t,n,`copy`,FI(e.scope));if(r.length===0)return;await CN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Rs(e,t){if(t.ok){J(e,200,Xee,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let Bs=g_e({contentDir:l,skillsHome:To,...j===void 0?{}:{projectDir:j},resolveSkillDirForRead:Oo,parseFrontmatterDoc:po,attributeOkArtifactWrite:tr,commitOkArtifactWrite:nr,shadowHeadSha:Fs,artifactWriterId:Is,effectiveInstallMode:Ro,signalFiles:()=>A?.(`files`)}),Vs=q(_ee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await aO(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??AD(d);if(!p){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(xX(t,p,`skill-import`))return;let m=await MD(p);r=m.cleanup,s=m.ref;let h=XD(m.dir);if(h.length===0){K(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=>qD(e.dir)?.name===f)??h.find(e=>e.name===eo[f]);if(!e){K(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){K(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??js(d)}catch(e){if(e instanceof hD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Bs.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||Ca(u))&&TI({source:u,skills:[d.body.name]},uI()),await be?.rebuildIgnorePatterns(),Rs(t,d)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Hs=q(pee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await aO(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??AD(d);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(xX(t,f,`skills-import-bulk`))return;if(l=e?.publisher??js(d),f.kind===`well-known`)a=f,o=await TD(f.origin);else{let e=await MD(f);r=e.cleanup,c=e.ref,s=XD(e.dir)}}catch(e){if(e instanceof hD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await MD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof hD?`not-found`:`failed`,warnings:[],...e instanceof hD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>YD(e.dir)?.name===t)??s.find(e=>e.name===eo[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Bs.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){P(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.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){P(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||Ca(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&TI({source:u,skills:e},uI())}await be?.rebuildIgnorePatterns(),J(t,200,Br,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),Us=8*1024*1024,Gs=32*1024*1024;function Ys(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=R(e,n);return r!==e&&!r.startsWith(e+z)?null:r}function Xs(e){return new Promise((t,n)=>{let r;try{r=Oq(e,{files:200,fields:10,fieldSize:2*1024,fileSize:Us})}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>Gs){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 Qs(e,t){return new Promise((n,r)=>{(0,$ce.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=Ys(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){Ws(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>Us){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>Gs){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{Ws(F(n),{recursive:!0}),$s(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 ec(e,t){let n=Uu(I(ad(),`ok-skill-upload-`)),r=()=>{try{Js(n,{recursive:!0,force:!0})}catch{}};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=wo(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=fk({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},pe);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Xs(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Qs(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Ys(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}Ws(F(r),{recursive:!0}),$s(r,e.data)}let u=XD(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];Rs(t,await Bs.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let tc=q(ote,async(e,t,n)=>{try{let e=Do(n.scope);if(!Co(n.name,t,`skill-install`))return;if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Qo(n.scope),i=R(e,n.name),a=n.scope===`project`?l:To,o=(n.scope===`project`?fL(l):pL(To)).find(e=>e.name===n.name),s=o?R(a,o.dir):i;if(!B(s)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await Lt(n.scope===`project`?`${L(a,s).split(z).join(`/`)}/SKILL`:or(n.scope,n.name));let c=NI(s,n.name);if(!c.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=Eo.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:o.hosts.filter(Si),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.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){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await Eo.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?K(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" 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`}):K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(Si),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await Eo.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?j:To;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Ar.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?j:To;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Ar.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,rs,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?j:To,l=await Ar.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!l.ok)switch(l.kind){case`invalid-location`:K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(l.kind)}`)}A?.(`files`),J(t,200,rs,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f===void 0?OI(To).map(e=>e.editorId).filter(e=>Tr.includes(e)):Tr.filter(e=>f?.some(t=>t===e)):f===void 0?PI(r):Tr.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===void 0?n.scope===`global`&&B(I(To,`.agents`)):f.includes(`agents`))?[...h,`agents`]:[...h],a=n.scope===`project`?j:To,l=d===void 0?Ro(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await Eo.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}A?.(`files`),J(t,200,rs,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await Eo.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:l,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),A?.(`files`),J(t,200,rs,{name:n.name,hosts:v.hosts,scripts:c.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=jI(xN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&qI(n.name,r,v,FI(n.scope));let y=I(r,...ND),b=B(y)?V(y,`utf-8`):null,x=b===null?null:LD(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=BI(s,n.name,r,h,C,FI(n.scope));w.length===0?await wN(r,n.name):await CN(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),A?.(`files`),J(t,200,rs,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),nc=q(Fr,async(e,t,n)=>{try{if(!Co(n.name,t,`skill-uninstall`))return;let e=Qo(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await $o(e,n.name,n.scope);A?.(`files`),J(t,200,Zt,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),rc=_W({GET:q(Rt,async(e,t)=>{try{let e=PI(j??``),n=(e,t)=>{let n=b_e(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,on,{targets:e,configured:!1,folders:[...j?cX(l,oL(l,`project`)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...cX(To,oL(To,`global`)).map(e=>({...e,scope:`global`,...n(To,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(An,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:To;if(e.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await x_e(r,i.join(`/`)),A?.(`files`),J(t,200,ur,{targets:PI(j??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(oL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?y_e({base:r,folderRel:e.root,targetRootRel:a}):uX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await pX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),A?.(`files`),J(t,200,ur,{targets:PI(j??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),ic=q(jee,async(e,t,n)=>{try{let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Co(n.name,t,`skill-restore`)||Ko(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=E?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await CX({shadow:r,contentDir:l,contentRoot:re??`.`,name:n.name,version:n.version,skillDirRel:zo(n.name)});if(!i.ok){Lo(t,i,`skill-restore`);return}let a=[],o=NI(R(l,zo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),tr(e,Xn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await nr(`skill-restore`),A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,tee,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),ac=q(Fee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Co(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?To:l,{root:a,dirRel:o,realDir:s}=ds(n.scope,n.name),c=!o.startsWith(`${hs}/`);if(s===null||!B(R(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=I(n.scope===`global`?To:j,...ND),d=Ns(u).skills[n.name];if(!d){let e=BD(n.name,YD(R(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:K_e(R(a,n.name))})??Wo(i,n.name);e&&(d=e)}if(!d){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await wJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=eo[e],a=await aO(d.source,e).catch(async e=>{if(i===void 0)throw e;return aO(d.source,i)}),o=a?.source??WO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??AD(o);if(!c){K(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(xX(t,c,`skill-reimport`))return;let l=await MD(c);r=l.cleanup,f=l.ref;let u=XD(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>YD(e.dir)?.name===n.name)??u.find(e=>e.name===eo[s??n.name])??(u.length===1?u[0]:void 0);if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=JD(m.dir);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=YD(m.dir)}catch(e){if(e instanceof hD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=sX(p);if(h){K(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=YD(R(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){await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=po(p.skillMd).body;if(n.dryRun){let e=YD(R(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&j)try{let e=mc({baseDir:j,timeout:{block:15e3}}),t=L(j,R(a,n.name)).split(z).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!0,source:d.source,localBody:po(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 fn(e,`deleted-upstream`)}let x=ij({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=sj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:oX});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=cj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(tr(e,Xn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await nr(`skill-reimport`));let C=Ps(a,n.name),w=n.scope===`project`?await Fs(Is(e),o):void 0;await wJ(u,e=>RD(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 Ls({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),A?.(`files`),await be?.rebuildIgnorePatterns(),J(t,200,Xe,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),oc=q(ree,async(e,t,n)=>{try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=fk(n,pe);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Co(n.name,t,`skill-revert`)||Ko(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=I(j,...ND),i=Ns(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=E?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await CX({shadow:a,contentDir:l,contentRoot:re??`.`,name:n.name,version:i.baselineRef,skillDirRel:zo(n.name)});if(!o.ok){Lo(t,o,`skill-revert`);return}tr(e,Xn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await nr(`skill-revert`);let s=R(l,zo(n.name),`..`),c=Ps(s,n.name);await wJ(r,e=>RD(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Do(`project`)&&await Ls({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),A?.(`files`),J(t,200,$n,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function sc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function cc(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 lc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function uc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let dc=m_e({contentDir:l,projectDir:j,getAllFilesIndex:g,getFileIndexGeneration:v,getSearchMaxEntries:eve,semanticSearch:De,getSemanticSimilarityFloor:Oe,ready:Ce,getProjectSkillsRoot:()=>Do(`project`),parseFrontmatterDoc:po});dc.prewarm();let fc=_W({GET:q(Rt,VB(async(e,t)=>{let n=Fc(e),r=n.get(`limit`),i=n.get(`query`)??``,a=sc(n.get(`intent`)),o=Xo(n.get(`ranking`)),s=cc(n.get(`scope`)??n.get(`scopes`)),c=lc(n.get(`semantic`)),l=uc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,Za,await dc.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Uee,VB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=sc(n.intent),a=Xo(n.ranking),o=cc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=lc(n.semantic),l=uc(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,Za,await dc.buildSearchResponse({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`}),pc=q(Rt,VB(async(e,t)=>{J(t,200,See,{...await SI(nd())},{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 gc(e,t){if(r(e,t,{handler:`handoff`}))try{await ofe(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:at.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:fS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function _c(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await rN(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:fS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let vc=q(kt,async(e,t,n)=>{try{if(!j){NF(`no-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`no-remote`},{handler:MF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!$pe(e,n.kind)){NF(`invalid-path`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`invalid-path`},{handler:MF});return}let r=ime(j);if(r===null){if(LF(j).kind===`no-remote`){NF(`no-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`no-remote`},{handler:MF});return}NF(`detached-head`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`detached-head`},{handler:MF});return}let i=LF(j);if(i.kind===`no-remote`){NF(`no-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`no-remote`},{handler:MF});return}if(i.kind===`non-github`){NF(`non-github-remote`,{kind:n.kind}),J(t,200,xt,{ok:!1,error:`non-github-remote`},{handler:MF});return}if(!lme(j,r)){NF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,xt,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:MF});return}let a=OZ(j,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&&P(`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=eme(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=tme(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Fte(s)}`,u=await nme(j,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);NF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,xt,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:MF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:MF,cause:e})}},{handler:MF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:MF})}),yc=q(Rt,async(e,t)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:iB});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(!dr(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:iB});return}if(!nB(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:iB});return}J(t,200,pt,await rB(j,r,i,a),{handler:iB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:iB,cause:e})}},{handler:iB,method:`GET`,skipBodyParse:!0}),bc=q(iee,async(e,t,n)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:YF});return}if(!nB(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:YF});return}let e=OZ(j,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}`;J(t,200,er,await _me(j,n.branch,r,n.kind),{handler:YF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:YF,cause:e})}},{handler:YF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:YF})}),xc=q(ete,async(e,t,n)=>{if(fk(n,pe).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:lB});return}if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lB});return}try{J(t,200,dee,await hc(()=>dB(j,n.branch,{fastForward:n.fastForward===!0})),{handler:lB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lB,cause:e})}},{handler:lB,method:`POST`});async function Sc(e){let[t,...n]=ce,r=[...n,...e];return await new Promise((e,n)=>{let i=bu(t,r,YM({...vi,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},HF),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 ${HF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=JF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Cc=q(Rt,async(e,t)=>{if(!Re.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:zF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Sc([`share`,`owners`,`--json`]),n=ume(GF(e));qF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,Ze,n,{handler:zF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zF,cause:e})}finally{Re.release(`/api/share/publish/owners`)}},{handler:zF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:zF})}),Tc=q(Rt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!WF(r)||!UF(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:BF});return}if(!Re.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:BF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Sc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=dme(GF(e));qF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Iee,n,{handler:BF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:BF,cause:e})}finally{Re.release(`/api/share/publish/name-check`)}},{handler:BF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:BF})}),Ec=q(Mee,async(e,t,n)=>{if(!j){qF(`publish-create`,`no-project`),J(t,200,Fn,{ok:!1,error:`no-project`},{handler:VF});return}if(!WF(n.owner)||!UF(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:VF});return}if(!Re.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:VF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,j,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Sc(e),i=mme(GF(r));qF(`publish-create`,i.ok?`ok`:i.error),i.ok&&se?.()?.refreshRemote().catch(()=>{}),J(t,200,Fn,i,{handler:VF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:VF,cause:e})}finally{Re.release(`/api/share/publish`)}},{handler:VF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:VF})}),Dc=q(Kr,async(e,t,n)=>{try{let e=P(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,si,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Oc=j?Bk(j):null;async function Ac(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:ole(e.headers),previewUrl:null,port:Oc?kc(Oc)?.port??0:0,singleFile:Pe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,Ua,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function jc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Le?.()??{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}J(t,200,de,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Mc=`local-op-embeddings-set-key`,Nc=`local-op-embeddings-clear-key`,Pc=`/api/local-op/embeddings`;function Ic(){let e=Ae?.();return{projectDir:j??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Lc=q(Yee,async(e,t,n)=>{if(!Re.tryAcquire(Pc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Mc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Ic();await new $j(ke).setForProject(e,r,n.key),De?.reloadCredential(),J(t,200,mi,{keyPresent:!0},{handler:Mc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Mc,cause:e})}finally{Re.release(Pc)}},{handler:Mc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Mc})}),Rc=q(Rt,async(e,t)=>{if(!Re.tryAcquire(Pc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Nc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Ic();await new $j(ke).clearForProject(e,n),De?.reloadCredential(),J(t,200,mi,{keyPresent:!1},{handler:Nc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Nc,cause:e})}finally{Re.release(Pc)}},{handler:Nc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Nc})}),zc=`local-op-embeddings-test`,Bc=`/api/local-op/embeddings/test`,Vc=q(Rt,async(e,t)=>{if(!Re.tryAcquire(Bc)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:zc,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 Kj(new $j(ke),j??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await nde({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,ate,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:zc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:zc,cause:e})}finally{Re.release(Bc)}},{handler:zc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:zc})}),Hc=q(Rt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(De){let t=De.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Ae?.()?.baseUrl??`https://api.openai.com/v1`,o=await Kj(new $j(ke),j??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of m())!tS(e)&&!nS(e)&&!ps(e)&&(f+=1);J(t,200,Ao,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Uc=0;function Wc(){Uc+=1,A?.(`lint-config`)}let Gc=()=>`${Uc} ${t.getActiveBranch()} ${k?.readLocalTargetGeneration?.()??0}`;async function Kc(e,t){let n=je?.()??Or;try{let r=await ya(e,zP(l,n,{docName:t,projectDir:j??l,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ne?.()??`warning`;if(k&&a!==`off`&&!sS(t)){await Xt(t,e,`lint-validation`);let r=mF({projectDir:j??l,contentDir:l,baseConfig:n,derivedDocumentIndex:k,linksValidation:a,admittedDocNames:qt,docFilePathFor:e=>TZ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:TZ(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}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function qc(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=HP({projectDir:j??l,contentDir:l});return dP(t.schemas,n)}let Jc=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!LZ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=je?.()??Or,i=[],a=IP(l,n??void 0,e=>i.push(e)),o=RP(j??l,LP(r,a),e=>i.push(e));n===null&&i.push(...qc(o)),J(t,200,ss,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Yc=q(ut,async(e,t,n)=>{let r;try{r=QP(R(l),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Wc();try{let e=je?.()??Or,n=[],r=IP(l,void 0,e=>n.push(e)),i=RP(j??l,LP(e,r),e=>n.push(e));n.push(...qc(i)),J(t,200,ss,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Xc=q(la,async(e,t,n)=>{let r;try{let e=R(j??l),t=n.parentPath??[];r=n.delete?ope(e,n.file):n.field!==void 0&&n.removeField?ipe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?ape(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?npe(e,n.file,n.field,n.constraint,t):rpe(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&A?.(`files`),Wc();try{let e=je?.()??Or,n=[],r=IP(l,void 0,e=>n.push(e)),i=RP(j??l,LP(e,r),e=>n.push(e));n.push(...qc(i)),J(t,200,ss,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),Zc=q(Rt,async(e,t)=>{try{let e=R(j??l),{schemas:n,truncated:r}=Mfe(e),i=new Set(n),a=!1;if(be!==void 0){let t=hZ({contentDir:l,contentFilter:be,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&&fo(a)){let t=L(e,R(l,a));!t.startsWith(`..`)&&!Eu(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,gee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Qc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=s.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},$c=q(Rt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!LZ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=TZ(l,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=je?.()??Or,a=[],o=await VP({projectDir:j??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Qc});J(t,200,bee,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof RM){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),el=new sP,tl=bX();function nl(e,t,n){let r=`${n} ${Gc()} ${t??``}`;return tl.run(r,()=>Tpe(e,{targetPath:t})).promise}function rl(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let il=q(Rt,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&&!gZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=je?.()??Or;J(t,200,Jee,await UP({projectDir:j??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:Qc,cache:el,auditGeneration:Gc}),{handler:`lint-audit`})}catch(e){if(e instanceof BP){rl(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),al=q(Rt,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&&!gZ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!gZ(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=TZ(l,o)??`${o}.md`}let s=je?.()??Or,c=await nl(mF({projectDir:j??l,contentDir:l,baseConfig:s,liveSourceFor:Qc,derivedDocumentIndex:k??null,linksValidation:Ne?.(),admittedDocNames:qt,docFilePathFor:e=>TZ(l,e),cache:el,auditGeneration:Gc}),i,sP.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){J(t,200,Qee,wpe(c),{handler:`audit`});return}J(t,200,Cr,c,{handler:`audit`})}catch(e){if(e instanceof BP){rl(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),ol=q(nte,async(t,n,r)=>{try{let t=vZ(r.docName,n,`lint-fix`);if(t===null)return;let i=Tt(t),a=fk(r,pe);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(tS(i)||nS(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=TZ(l,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}qM(R(l,f),l);let p=je?.()??Or,{stored:m}=Hn(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await $fe({projectDir:j??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Jo(d),n=Ra[t]??ca(u??o);ae?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{xw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,yw(h))},h.origin),a.kind!==`anonymous`&&Dj(i,o,s,u,void 0,a.kind===`agent`?Vn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{ae?.touchMode(o,`idle`)}let t=await Lt(i);if(t?.kind===`failure`){Bt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Vt(n,`lint-fix`);return}Mt(i,`lint-fix`);try{b=await ya(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,hr,{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 RM){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof bS){xS(n,e,`lint-fix`);return}if(e instanceof TS){OS(n,e,`lint-fix`);return}if(e instanceof jw){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),sl=`link-preview`,cl=new TG({cacheDir:Pe?null:R(j??l,`.ok`,`local`,`link-previews`)}),ll=null,ul=()=>(ll??=cl.init(),ll),dl=Fe??gG;async function fl(e){let t=await dl(e);return t.ok?{ok:!0,metadata:await xG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:dl})}:{ok:!1,reason:t.reason}}let pl=()=>{try{return Ie?.()===!0}catch{return!1}},ml=q(yt,async(e,t,n)=>{try{if(!pl()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,Wn,{ok:!1,reason:`disabled`},{handler:sl});return}await ul();let e=!1,r=await cl.load(n.url,()=>(e=!0,fl(n.url)));cl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,Wn,i,{handler:sl})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:sl,cause:e})}},{handler:sl,method:`POST`,preBodyGate:(e,t)=>{let n=OG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:sl}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:sl}),!1)}}),hl=gle({service:dt,getPrincipal:pe,onChanged:()=>A?.(`comments`)}),gl=_W({GET:hl.list,POST:hl.create},{handler:`comments`}),_l=_W({GET:hl.read,POST:hl.mutate,DELETE:hl.remove},{handler:`comment`}),{handleSkillsSearch:vl,handleSkillsPopular:yl,handleSkillsPublisher:bl,handleSkillsDetail:xl,handleSkillsPreview:Sl,handleSkillsDiscover:Cl,handleSkillsResolveRef:wl}=A_e({log:X,skillsHome:To,projectDir:j,contentDir:l,resolveSkillDirForRead:Oo}),Tl={"/api/config":Ac,"/api/config/diagnostics":jc,"/api/generated-index/settings":_W({GET:q(Rt,async(e,t)=>{if(!d){K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}J(t,200,FZ,d(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:q(mve,async(e,t,n)=>{if(!f){K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}J(t,200,FZ,await f(n.enabled),{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`}),"/api/comments":gl,"/api/comment":_l,"/api/asset":Qr,"/api/asset-text":ei,"/api/comment-counts":pr,"/api/link-preview":ml,"/api/folder-config":Qa,"/api/saved-themes":to,"/api/saved-theme":oo,"/api/template":bo,"/api/template/import":xo,"/api/templates":uo,"/api/skill":xs,"/api/skill-file":ks,"/api/skill-file/rename":As,"/api/skills":os,"/api/skills/installed":cr,"/api/skills/search":vl,"/api/skills/popular":yl,"/api/skills/publisher":bl,"/api/skills/detail":xl,"/api/skills/preview":Sl,"/api/skills/discover":Cl,"/api/skills/resolve-ref":wl,"/api/skill/import":Vs,"/api/skills/import-bulk":Hs,"/api/skill/edit-external":vs,"/api/skill/duplicate":bs,"/api/skill/move-scope":ys,"/api/skill-upload":ec,"/api/skill/install":tc,"/api/skill/uninstall":nc,"/api/skill/restore":ic,"/api/skill/reimport":ac,"/api/skill/revert":oc,"/api/skill/track-in-git":is,"/api/skill-targets":rc,"/api/search":fc,"/api/semantic-status":Hc,"/api/lint/config":Jc,"/api/lint/markdownlint-config":Yc,"/api/lint/frontmatter-schema":Xc,"/api/lint/frontmatter-schemas":Zc,"/api/lint":$c,"/api/lint/audit":il,"/api/lint/fix":ol,"/api/audit":al,"/api/create-page":ri,"/api/create-folder":ai,"/api/duplicate-path":oi,"/api/rename-path":li,"/api/delete-path":ui,"/api/trash/cleanup":di,"/api/upload":fi,"/api/agent-write":rr,"/api/agent-write-md":ir,"/api/agent-write-batch":ar,"/api/frontmatter-patch":sr,"/api/agent-patch":gr,"/api/agent-undo":_r,"/api/agent-activity":vr,"/api/agent-burst-diff":xr,"/api/save-version":jr,"/api/history":Mr,"/api/rollback":Pr,"/api/__embed-detect":Wr,"/api/server-info":Lr,"/api/acp/catalog":zr,"/api/share/construct-url":vc,"/api/share/target-status":bc,"/api/git/branch-info":yc,"/api/git/checkout":xc,"/api/share/publish/owners":Cc,"/api/share/publish/name-check":Tc,"/api/share/publish":Ec,"/api/principal":Ur,"/api/rescue":ni,"/api/workspace":Gr,"/api/sync/status":Aa,"/api/sync/trigger":ja,"/api/sync/conflicts":Ma,"/api/sync/conflict-content":Pa,"/api/sync/resolve-conflict":Na,"/api/local-op/clone":Ci,"/api/local-op/ok-init":ki,"/api/local-op/auth/login":$i,"/api/local-op/auth/status":pa,"/api/local-op/auth/pat":ha,"/api/local-op/auth/gh-login":ia,"/api/local-op/auth/cancel":sa,"/api/local-op/auth/repos":_a,"/api/local-op/auth/signout":Sa,"/api/local-op/auth/set-identity":Da,"/api/local-op/embeddings/set-key":Lc,"/api/local-op/embeddings/clear-key":Rc,"/api/local-op/embeddings/test":Vc,"/api/installed-agents":Ga,"/api/spawn-cursor":_c,"/api/handoff":gc,"/api/install-skill":Ba,"/api/skill/install-state":pc,"/api/seed/plan":Fa,"/api/seed/apply":Ia,"/api/seed/install-pack-skill":La,"/api/seed/packs":za,"/api/client-logs":Dc};T&&(Tl[`/api/test-reset`]=wr,Tl[`/api/test-flush-git`]=Sr,Tl[`/api/test-rescan-backlinks`]=Er,Tl[`/api/test-rescan-files`]=Dr);let El=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/generated-index/settings./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/saved-theme./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/skill/track-in-git./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),Dl=[`/api/local-op/`],Ol=BB({log:X,policy:n,ephemeral:Pe,table:{resolve(e){let t=Tl[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await Nr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>El.has(e)||Dl.some(t=>e.startsWith(t))}}),kl=pW({hocuspocus:s,derivedDocumentIndex:k,getFileIndex:m,isSafeDocName:LZ,readPageTitleForDocName:ht,readPageTitleForLinkedDocName:gt,readFrontmatterMetadataForLinkedDocName:Ct,collectAdmittedDocNames:qt,resolveAlias:Tt,respondToDerivedIndexQueryFailure:en}),Al=[kl,vW({hocuspocus:s,agentPresenceBroadcaster:ae,isAllowedWorkspaceHostHeader:a,log:X}),Be],jl=Al.flatMap(e=>[...e.paths]);BU(jl,Tl);let Ml=Al.map(e=>BB({log:X,policy:n,ephemeral:Pe,table:e.table})),Nl={paths:jl,dispatch:async(e,t)=>{for(let n of Ml)if(await n(e,t))return!0;return!1}},Pl=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]);for(let e of Pl)if(Tl[e]===void 0&&kl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await Ol(e,t)},nativeApi:Nl,localApi:gW({resolve:e=>{if(!Pl.has(e))return;let t=Tl[e];return t===void 0?kl.table.resolve(e)?.dispatch:t}})}}function zZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=Tu(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!AB(f,o)){K(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!MB(e.headers.host,o)){K(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:TB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=ZY(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=De.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function BZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function gve(e){let t;try{t=qu(e.contentDir,{withFileTypes:!0})}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Wx(n.name,w)&&e.basenameIndex.add(n.name)}async function VZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await ud(i,{withFileTypes:!0})}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=I(i,o.name),s=UM(L(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await cd(a)}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await dd(a)}catch(t){let n=BZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!WM(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await fd(i)}catch(t){let n=BZ(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()&&Wx(a,ue)&&!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()&&Wx(a,ue)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const HZ=M({principalId:u().optional(),tabSessionId:u().optional(),expectedServerInstanceId:u().optional(),expectedBranch:u().optional(),expectedDocLineageEpoch:u().optional(),clientProtocolVersion:i().optional(),clientRuntimeVersion:u().optional(),clientKind:u().optional()}).loose(),UZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function WZ(e){return UZ.includes(e)}function GZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function _ve(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!WZ(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 KZ=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=GZ(e,this.payload)}};function qZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=HZ.safeParse(t);return n.success?n.data:void 0}var JZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const YZ=P(`conflict-storage`);var XZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=I(Bk(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!B(this.storePath)){this.conflicts=[];return}try{let e=V(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){YZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){YZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=F(this.storePath);B(e)||Hu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return ed(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return YZ.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-Bo4ytezq.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=R(this.projectDir),r=R(t,e);if(!WM(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);gL(r,t),$s(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`]),YZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Jb(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){YZ.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}),YZ.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=R(this.projectDir),a=R(i,e.file);if(!WM(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(gL(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-Bo4ytezq.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);gL(a,i),$s(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);$s(a,n,`utf-8`);break;case`delete`:B(a)&&zs(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function vve(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 yve(e,t){let n=Bk(e);try{Hu(n,{recursive:!0}),ed(I(n,to),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=lc(e);Hu(F(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`};ed(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const ZZ=new Map;let QZ=!1;function bve(e,t){try{let n=vve(e,t);for(let e of ZZ.keys())yve(e,n)}catch{}}function xve(e){ZZ.set(e,(ZZ.get(e)??0)+1),QZ||(QZ=!0,process.on(`uncaughtExceptionMonitor`,bve));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=ZZ.get(e)??0;n<=1?ZZ.delete(e):ZZ.set(e,n-1)}}}function $Z(e){let t=e.scheduler??Wi,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 eQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function tQ(e){if(!B(e))return{};let t;try{t=(0,ck.parse)(V(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!eQ(t))return{};let n=t.telemetry;if(!eQ(n))return{};let r=n.localSink;return eQ(r)?r:{}}function nQ(e){return typeof e==`boolean`?e:void 0}function Sve(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function rQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function iQ(e){if(eQ(e))return Sve(e.maxBytes)}function Cve(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=tQ(Us(`project`,e.projectDir)),n=tQ(Us(`project-local`,e.projectDir));if((nQ(n.enabled)??nQ(t.enabled)??!0)===!1)return null;let r=iQ(n.spans)??iQ(t.spans)??52428800,i=iQ(n.logs)??iQ(t.logs)??26214400,a=rQ(n.attributeDenylist)??rQ(t.attributeDenylist)??_e;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 wve;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(wve||={});const oQ=aQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),sQ=e=>{switch(typeof e){case`undefined`:return oQ.undefined;case`string`:return oQ.string;case`number`:return Number.isNaN(e)?oQ.nan:oQ.number;case`boolean`:return oQ.boolean;case`function`:return oQ.function;case`bigint`:return oQ.bigint;case`symbol`:return oQ.symbol;case`object`:return Array.isArray(e)?oQ.array:e===null?oQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?oQ.promise:typeof Map<`u`&&e instanceof Map?oQ.map:typeof Set<`u`&&e instanceof Set?oQ.set:typeof Date<`u`&&e instanceof Date?oQ.date:oQ.object;default:return oQ.unknown}},Z=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 cQ=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()}};cQ.create=e=>new cQ(e);const lQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===oQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,aQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${aQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${aQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${aQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:aQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,aQ.assertNever(e)}return{message:n}};let Tve=lQ;function uQ(){return Tve}const dQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function fQ(e,t){let n=uQ(),r=dQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===lQ?void 0:lQ].filter(e=>!!e)});e.common.issues.push(r)}var pQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return mQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return mQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const mQ=Object.freeze({status:`aborted`}),hQ=e=>({status:`dirty`,value:e}),gQ=e=>({status:`valid`,value:e}),_Q=e=>e.status===`aborted`,vQ=e=>e.status===`dirty`,yQ=e=>e.status===`valid`,bQ=e=>typeof Promise<`u`&&e instanceof Promise;var xQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(xQ||={});var SQ=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const CQ=(e,t)=>{if(yQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new cQ(e.common.issues);return this._error=t,this._error}}};function wQ(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var TQ=class{get description(){return this._def.description}_getType(e){return sQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:sQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new pQ,ctx:{common:e.parent.common,data:e.data,parsedType:sQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(bQ(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sQ(e)};return CQ(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return yQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>yQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:sQ(e)},r=this._parse({data:e,path:n.path,parent:n});return CQ(n,await(bQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new r$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return i$.create(this,this._def)}nullable(){return a$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return VQ.create(this)}promise(){return n$.create(this,this._def)}or(e){return WQ.create([this,e],this._def)}and(e){return qQ.create(this,e,this._def)}transform(e){return new r$({...wQ(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new o$({...wQ(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new l$({typeName:Q.ZodBranded,type:this,...wQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new s$({...wQ(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return u$.create(this,e)}readonly(){return d$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Eve=/^c[^\s-]{8,}$/i,Dve=/^[0-9a-z]+$/,Ove=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kve=/^[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,Ave=/^[a-z0-9_-]{21}$/i,jve=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mve=/^[-+]?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)?)??$/,Nve=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let EQ;const Pve=/^(?:(?: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])$/,Fve=/^(?:(?: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])$/,Ive=/^(([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]))$/,Lve=/^(([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])$/,Rve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zve=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,DQ=`((\\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])))`,Bve=RegExp(`^${DQ}$`);function OQ(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 Vve(e){return RegExp(`^${OQ(e)}$`)}function Hve(e){let t=`${DQ}T${OQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Uve(e,t){return!!((t===`v4`||!t)&&Pve.test(e)||(t===`v6`||!t)&&Ive.test(e))}function Wve(e,t){if(!jve.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 Gve(e,t){return!!((t===`v4`||!t)&&Fve.test(e)||(t===`v6`||!t)&&Lve.test(e))}var kQ=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==oQ.string){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.string,received:t.parsedType}),mQ}let t=new pQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?fQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&fQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Nve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)EQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),EQ.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)kve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ave.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Eve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Dve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Ove.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),fQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Hve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Bve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Vve(r).test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Mve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Uve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Wve(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Gve(e.data,r.version)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Rve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?zve.test(e.data)||(n=this._getOrReturnCtx(e,n),fQ(n,{validation:`base64url`,code:Z.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:Z.invalid_string,...xQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...xQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...xQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...xQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...xQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...xQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...xQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...xQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...xQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...xQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...xQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...xQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...xQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...xQ.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...xQ.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...xQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...xQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...xQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...xQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...xQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...xQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...xQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...xQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...xQ.errToObj(t)})}nonempty(e){return this.min(1,xQ.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};kQ.create=e=>new kQ({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...wQ(e)});function Kve(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 AQ=class e extends TQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==oQ.number){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.number,received:t.parsedType}),mQ}let t,n=new pQ;for(let r of this._def.checks)r.kind===`int`?aQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Kve(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:xQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:xQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:xQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:xQ.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&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)}};AQ.create=e=>new AQ({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...wQ(e)});var jQ=class e extends TQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==oQ.bigint)return this._getInvalidInput(e);let t,n=new pQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),fQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):aQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.bigint,received:t.parsedType}),mQ}gte(e,t){return this.setLimit(`min`,e,!0,xQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,xQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,xQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,xQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:xQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:xQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:xQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:xQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:xQ.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};jQ.create=e=>new jQ({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...wQ(e)});var MQ=class extends TQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==oQ.boolean){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.boolean,received:t.parsedType}),mQ}return gQ(e.data)}};MQ.create=e=>new MQ({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...wQ(e)});var NQ=class e extends TQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==oQ.date){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.date,received:t.parsedType}),mQ}if(Number.isNaN(e.data.getTime()))return fQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),mQ;let t=new pQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),fQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):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:xQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:xQ.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};NQ.create=e=>new NQ({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...wQ(e)});var PQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.symbol){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.symbol,received:t.parsedType}),mQ}return gQ(e.data)}};PQ.create=e=>new PQ({typeName:Q.ZodSymbol,...wQ(e)});var FQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.undefined,received:t.parsedType}),mQ}return gQ(e.data)}};FQ.create=e=>new FQ({typeName:Q.ZodUndefined,...wQ(e)});var IQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.null){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.null,received:t.parsedType}),mQ}return gQ(e.data)}};IQ.create=e=>new IQ({typeName:Q.ZodNull,...wQ(e)});var LQ=class extends TQ{constructor(){super(...arguments),this._any=!0}_parse(e){return gQ(e.data)}};LQ.create=e=>new LQ({typeName:Q.ZodAny,...wQ(e)});var RQ=class extends TQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return gQ(e.data)}};RQ.create=e=>new RQ({typeName:Q.ZodUnknown,...wQ(e)});var zQ=class extends TQ{_parse(e){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.never,received:t.parsedType}),mQ}};zQ.create=e=>new zQ({typeName:Q.ZodNever,...wQ(e)});var BQ=class extends TQ{_parse(e){if(this._getType(e)!==oQ.undefined){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.void,received:t.parsedType}),mQ}return gQ(e.data)}};BQ.create=e=>new BQ({typeName:Q.ZodVoid,...wQ(e)});var VQ=class e extends TQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==oQ.array)return fQ(t,{code:Z.invalid_type,expected:oQ.array,received:t.parsedType}),mQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(fQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(fQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(fQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new SQ(t,e,t.path,n)))).then(e=>pQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new SQ(t,e,t.path,n)));return pQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:xQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:xQ.toString(n)}})}nonempty(e){return this.min(1,e)}};VQ.create=(e,t)=>new VQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...wQ(t)});function HQ(e){if(e instanceof UQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=i$.create(HQ(r))}return new UQ({...e._def,shape:()=>t})}else if(e instanceof VQ)return new VQ({...e._def,type:HQ(e.element)});else if(e instanceof i$)return i$.create(HQ(e.unwrap()));else if(e instanceof a$)return a$.create(HQ(e.unwrap()));else if(e instanceof JQ)return JQ.create(e.items.map(e=>HQ(e)));else return e}var UQ=class e extends TQ{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=aQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==oQ.object){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.object,received:t.parsedType}),mQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof zQ&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new SQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof zQ){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(fQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new SQ(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>pQ.mergeObjectSync(t,e)):pQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return xQ.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:xQ.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of 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 HQ(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 i$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return $Q(aQ.objectKeys(this.shape))}};UQ.create=(e,t)=>new UQ({shape:()=>e,unknownKeys:`strip`,catchall:zQ.create(),typeName:Q.ZodObject,...wQ(t)}),UQ.strictCreate=(e,t)=>new UQ({shape:()=>e,unknownKeys:`strict`,catchall:zQ.create(),typeName:Q.ZodObject,...wQ(t)}),UQ.lazycreate=(e,t)=>new UQ({shape:e,unknownKeys:`strip`,catchall:zQ.create(),typeName:Q.ZodObject,...wQ(t)});var WQ=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new cQ(e.ctx.common.issues));return fQ(t,{code:Z.invalid_union,unionErrors:n}),mQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new cQ(e));return fQ(t,{code:Z.invalid_union,unionErrors:i}),mQ}}get options(){return this._def.options}};WQ.create=(e,t)=>new WQ({options:e,typeName:Q.ZodUnion,...wQ(t)});const GQ=e=>e instanceof ZQ?GQ(e.schema):e instanceof r$?GQ(e.innerType()):e instanceof QQ?[e.value]:e instanceof e$?e.options:e instanceof t$?aQ.objectValues(e.enum):e instanceof o$?GQ(e._def.innerType):e instanceof FQ?[void 0]:e instanceof IQ?[null]:e instanceof i$?[void 0,...GQ(e.unwrap())]:e instanceof a$?[null,...GQ(e.unwrap())]:e instanceof l$||e instanceof d$?GQ(e.unwrap()):e instanceof s$?GQ(e._def.innerType):[];var qve=class e extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==oQ.object)return fQ(t,{code:Z.invalid_type,expected:oQ.object,received:t.parsedType}),mQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(fQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),mQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=GQ(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...wQ(r)})}};function KQ(e,t){let n=sQ(e),r=sQ(t);if(e===t)return{valid:!0,data:e};if(n===oQ.object&&r===oQ.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=KQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===oQ.array&&r===oQ.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=KQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===oQ.date&&r===oQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var qQ=class extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(_Q(e)||_Q(r))return mQ;let i=KQ(e.value,r.value);return i.valid?((vQ(e)||vQ(r))&&t.dirty(),{status:t.value,value:i.data}):(fQ(n,{code:Z.invalid_intersection_types}),mQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};qQ.create=(e,t,n)=>new qQ({left:e,right:t,typeName:Q.ZodIntersection,...wQ(n)});var JQ=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.array)return fQ(n,{code:Z.invalid_type,expected:oQ.array,received:n.parsedType}),mQ;if(n.data.length<this._def.items.length)return fQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),mQ;!this._def.rest&&n.data.length>this._def.items.length&&(fQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new SQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>pQ.mergeArray(t,e)):pQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};JQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new JQ({items:e,typeName:Q.ZodTuple,rest:null,...wQ(t)})};var Jve=class e extends TQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.object)return fQ(n,{code:Z.invalid_type,expected:oQ.object,received:n.parsedType}),mQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new SQ(n,e,n.path,e)),value:a._parse(new SQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?pQ.mergeObjectAsync(t,r):pQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof TQ?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...wQ(r)}):new e({keyType:kQ.create(),valueType:t,typeName:Q.ZodRecord,...wQ(n)})}},YQ=class extends TQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.map)return fQ(n,{code:Z.invalid_type,expected:oQ.map,received:n.parsedType}),mQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new SQ(n,e,n.path,[a,`key`])),value:i._parse(new SQ(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return mQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return mQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};YQ.create=(e,t,n)=>new YQ({valueType:t,keyType:e,typeName:Q.ZodMap,...wQ(n)});var XQ=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==oQ.set)return fQ(n,{code:Z.invalid_type,expected:oQ.set,received:n.parsedType}),mQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(fQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(fQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return mQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new SQ(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:xQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:xQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};XQ.create=(e,t)=>new XQ({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...wQ(t)});var Yve=class e extends TQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==oQ.function)return fQ(t,{code:Z.invalid_type,expected:oQ.function,received:t.parsedType}),mQ;function n(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),lQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return dQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,uQ(),lQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof n$){let e=this;return gQ(async function(...t){let o=new cQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return gQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new cQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new cQ([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:JQ.create(t).rest(RQ.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||JQ.create([]).rest(RQ.create()),returns:n||RQ.create(),typeName:Q.ZodFunction,...wQ(r)})}},ZQ=class extends TQ{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZQ.create=(e,t)=>new ZQ({getter:e,typeName:Q.ZodLazy,...wQ(t)});var QQ=class extends TQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return fQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),mQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};QQ.create=(e,t)=>new QQ({value:e,typeName:Q.ZodLiteral,...wQ(t)});function $Q(e,t){return new e$({values:e,typeName:Q.ZodEnum,...wQ(t)})}var e$=class e extends TQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{expected:aQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return fQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),mQ}return gQ(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};e$.create=$Q;var t$=class extends TQ{_parse(e){let t=aQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==oQ.string&&n.parsedType!==oQ.number){let e=aQ.objectValues(t);return fQ(n,{expected:aQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),mQ}if(this._cache||=new Set(aQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=aQ.objectValues(t);return fQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),mQ}return gQ(e.data)}get enum(){return this._def.values}};t$.create=(e,t)=>new t$({values:e,typeName:Q.ZodNativeEnum,...wQ(t)});var n$=class extends TQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==oQ.promise&&t.common.async===!1?(fQ(t,{code:Z.invalid_type,expected:oQ.promise,received:t.parsedType}),mQ):gQ((t.parsedType===oQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};n$.create=(e,t)=>new n$({type:e,typeName:Q.ZodPromise,...wQ(t)});var r$=class extends TQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{fQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return mQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(r.value):r});{if(t.value===`aborted`)return mQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?mQ:r.status===`dirty`||t.value===`dirty`?hQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?mQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?mQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!yQ(e))return mQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>yQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):mQ);aQ.assertNever(r)}};r$.create=(e,t,n)=>new r$({schema:e,typeName:Q.ZodEffects,effect:t,...wQ(n)}),r$.createWithPreprocess=(e,t,n)=>new r$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...wQ(n)});var i$=class extends TQ{_parse(e){return this._getType(e)===oQ.undefined?gQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};i$.create=(e,t)=>new i$({innerType:e,typeName:Q.ZodOptional,...wQ(t)});var a$=class extends TQ{_parse(e){return this._getType(e)===oQ.null?gQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};a$.create=(e,t)=>new a$({innerType:e,typeName:Q.ZodNullable,...wQ(t)});var o$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===oQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};o$.create=(e,t)=>new o$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...wQ(t)});var s$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return bQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new cQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new cQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};s$.create=(e,t)=>new s$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...wQ(t)});var c$=class extends TQ{_parse(e){if(this._getType(e)!==oQ.nan){let t=this._getOrReturnCtx(e);return fQ(t,{code:Z.invalid_type,expected:oQ.nan,received:t.parsedType}),mQ}return{status:`valid`,value:e.data}}};c$.create=e=>new c$({typeName:Q.ZodNaN,...wQ(e)});var l$=class extends TQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},u$=class e extends TQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?mQ:e.status===`dirty`?(t.dirty(),hQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?mQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},d$=class extends TQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(yQ(e)&&(e.value=Object.freeze(e.value)),e);return bQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};d$.create=(e,t)=>new d$({innerType:e,typeName:Q.ZodReadonly,...wQ(t)}),UQ.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),kQ.create,AQ.create,c$.create,jQ.create,MQ.create,NQ.create,PQ.create,FQ.create,IQ.create,LQ.create,RQ.create,zQ.create,BQ.create,VQ.create;const Xve=UQ.create;UQ.strictCreate,WQ.create,qve.create,qQ.create,JQ.create,Jve.create,YQ.create,XQ.create,Yve.create,ZQ.create,QQ.create,e$.create,t$.create,n$.create,r$.create,i$.create,a$.create,r$.createWithPreprocess,u$.create;const Zve=fe(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);d.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>h(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>m(e,t,n),e.parseAsync=async(t,n)=>Te(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>oe(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)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Qve=fe(`ZodMiniObject`,(e,t)=>{ie.init(e,t),Zve.init(e,t),T(e,`shape`,()=>t.shape)});function f$(e,t){return new Qve({type:`object`,shape:e??{},...r(t)})}function p$(e){return!!e._zod}function m$(e){let t=Object.values(e);if(t.length===0)return f$({});let n=t.every(p$),r=t.every(e=>!p$(e));if(n)return f$(e);if(r)return Xve(e);throw Error(`Mixed Zod versions detected in object shape.`)}function h$(e,t){return p$(e)?m(e,t):e.safeParse(t)}async function g$(e,t){return p$(e)?await oe(e,t):await e.safeParseAsync(t)}function _$(e){if(!e)return;let t;if(t=p$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function v$(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 m$(e)}}if(p$(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 y$(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 $ve(e){return e.description}function eye(e){if(p$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function b$(e){if(p$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const x$=`2025-11-25`,S$=[x$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],C$=`io.modelcontextprotocol/related-task`,w$=s(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),T$=p([u(),i().int()]),E$=u();ve({ttl:i().optional(),pollInterval:i().optional()});const tye=M({ttl:i().optional()}),nye=M({taskId:u()}),D$=ve({progressToken:T$.optional(),[C$]:nye.optional()}),O$=M({_meta:D$.optional()}),k$=O$.extend({task:tye.optional()}),rye=e=>k$.safeParse(e).success,A$=M({method:u(),params:O$.loose().optional()}),j$=M({_meta:D$.optional()}),M$=M({method:u(),params:j$.loose().optional()}),N$=ve({_meta:D$.optional()}),P$=p([u(),i().int()]),F$=M({jsonrpc:x(`2.0`),id:P$,...A$.shape}).strict(),I$=e=>F$.safeParse(e).success,L$=M({jsonrpc:x(`2.0`),...M$.shape}).strict(),iye=e=>L$.safeParse(e).success,R$=M({jsonrpc:x(`2.0`),id:P$,result:N$}).strict(),z$=e=>R$.safeParse(e).success;var B$;(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`})(B$||={});const V$=M({jsonrpc:x(`2.0`),id:P$.optional(),error:M({code:i().int(),message:u(),data:_().optional()})}).strict(),H$=e=>V$.safeParse(e).success,U$=p([F$,L$,R$,V$]);p([R$,V$]);const W$=N$.strict(),aye=j$.extend({requestId:P$.optional(),reason:u().optional()}),G$=M$.extend({method:x(`notifications/cancelled`),params:aye}),K$=M({icons:N(M({src:u(),mimeType:u().optional(),sizes:N(u()).optional(),theme:Me([`light`,`dark`]).optional()})).optional()}),q$=M({name:u(),title:u().optional()}),J$=q$.extend({...q$.shape,...K$.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),oye=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,c(M({form:c(M({applyDefaults:D().optional()}),C(u(),_())).optional(),url:w$.optional()}),C(u(),_()).optional())),sye=ve({list:w$.optional(),cancel:w$.optional(),requests:ve({sampling:ve({createMessage:w$.optional()}).optional(),elicitation:ve({create:w$.optional()}).optional()}).optional()}),cye=ve({list:w$.optional(),cancel:w$.optional(),requests:ve({tools:ve({call:w$.optional()}).optional()}).optional()}),lye=M({experimental:C(u(),w$).optional(),sampling:M({context:w$.optional(),tools:w$.optional()}).optional(),elicitation:oye.optional(),roots:M({listChanged:D().optional()}).optional(),tasks:sye.optional(),extensions:C(u(),w$).optional()}),uye=O$.extend({protocolVersion:u(),capabilities:lye,clientInfo:J$}),Y$=A$.extend({method:x(`initialize`),params:uye}),X$=e=>Y$.safeParse(e).success,dye=M({experimental:C(u(),w$).optional(),logging:w$.optional(),completions:w$.optional(),prompts:M({listChanged:D().optional()}).optional(),resources:M({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:M({listChanged:D().optional()}).optional(),tasks:cye.optional(),extensions:C(u(),w$).optional()}),fye=N$.extend({protocolVersion:u(),capabilities:dye,serverInfo:J$,instructions:u().optional()}),Z$=M$.extend({method:x(`notifications/initialized`),params:j$.optional()}),pye=e=>Z$.safeParse(e).success,Q$=A$.extend({method:x(`ping`),params:O$.optional()}),mye=M({progress:i(),total:v(i()),message:v(u())}),hye=M({...j$.shape,...mye.shape,progressToken:T$}),$$=M$.extend({method:x(`notifications/progress`),params:hye}),gye=O$.extend({cursor:E$.optional()}),e1=A$.extend({params:gye.optional()}),t1=N$.extend({nextCursor:E$.optional()}),_ye=Me([`working`,`input_required`,`completed`,`failed`,`cancelled`]),n1=M({taskId:u(),status:_ye,ttl:p([i(),Ie()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:v(i()),statusMessage:v(u())}),r1=N$.extend({task:n1}),vye=j$.merge(n1),i1=M$.extend({method:x(`notifications/tasks/status`),params:vye}),a1=A$.extend({method:x(`tasks/get`),params:O$.extend({taskId:u()})}),o1=N$.merge(n1),s1=A$.extend({method:x(`tasks/result`),params:O$.extend({taskId:u()})});N$.loose();const c1=e1.extend({method:x(`tasks/list`)}),l1=t1.extend({tasks:N(n1)}),u1=A$.extend({method:x(`tasks/cancel`),params:O$.extend({taskId:u()})}),yye=N$.merge(n1),d1=M({uri:u(),mimeType:v(u()),_meta:C(u(),_()).optional()}),f1=d1.extend({text:u()}),p1=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),m1=d1.extend({blob:p1}),h1=Me([`user`,`assistant`]),g1=M({audience:N(h1).optional(),priority:i().min(0).max(1).optional(),lastModified:a({offset:!0}).optional()}),_1=M({...q$.shape,...K$.shape,uri:u(),description:v(u()),mimeType:v(u()),size:v(i()),annotations:g1.optional(),_meta:v(ve({}))}),bye=M({...q$.shape,...K$.shape,uriTemplate:u(),description:v(u()),mimeType:v(u()),annotations:g1.optional(),_meta:v(ve({}))}),v1=e1.extend({method:x(`resources/list`)}),xye=t1.extend({resources:N(_1)}),y1=e1.extend({method:x(`resources/templates/list`)}),Sye=t1.extend({resourceTemplates:N(bye)}),b1=O$.extend({uri:u()}),Cye=b1,x1=A$.extend({method:x(`resources/read`),params:Cye}),wye=N$.extend({contents:N(p([f1,m1]))}),Tye=M$.extend({method:x(`notifications/resources/list_changed`),params:j$.optional()}),Eye=b1,Dye=A$.extend({method:x(`resources/subscribe`),params:Eye}),Oye=b1,kye=A$.extend({method:x(`resources/unsubscribe`),params:Oye}),Aye=j$.extend({uri:u()}),jye=M$.extend({method:x(`notifications/resources/updated`),params:Aye}),Mye=M({name:u(),description:v(u()),required:v(D())}),Nye=M({...q$.shape,...K$.shape,description:v(u()),arguments:v(N(Mye)),_meta:v(ve({}))}),S1=e1.extend({method:x(`prompts/list`)}),Pye=t1.extend({prompts:N(Nye)}),Fye=O$.extend({name:u(),arguments:C(u(),u()).optional()}),C1=A$.extend({method:x(`prompts/get`),params:Fye}),w1=M({type:x(`text`),text:u(),annotations:g1.optional(),_meta:C(u(),_()).optional()}),T1=M({type:x(`image`),data:p1,mimeType:u(),annotations:g1.optional(),_meta:C(u(),_()).optional()}),E1=M({type:x(`audio`),data:p1,mimeType:u(),annotations:g1.optional(),_meta:C(u(),_()).optional()}),Iye=M({type:x(`tool_use`),name:u(),id:u(),input:C(u(),_()),_meta:C(u(),_()).optional()}),Lye=M({type:x(`resource`),resource:p([f1,m1]),annotations:g1.optional(),_meta:C(u(),_()).optional()}),D1=p([w1,T1,E1,_1.extend({type:x(`resource_link`)}),Lye]),Rye=M({role:h1,content:D1}),zye=N$.extend({description:u().optional(),messages:N(Rye)}),Bye=M$.extend({method:x(`notifications/prompts/list_changed`),params:j$.optional()}),Vye=M({title:u().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),Hye=M({taskSupport:Me([`required`,`optional`,`forbidden`]).optional()}),O1=M({...q$.shape,...K$.shape,description:u().optional(),inputSchema:M({type:x(`object`),properties:C(u(),w$).optional(),required:N(u()).optional()}).catchall(_()),outputSchema:M({type:x(`object`),properties:C(u(),w$).optional(),required:N(u()).optional()}).catchall(_()).optional(),annotations:Vye.optional(),execution:Hye.optional(),_meta:C(u(),_()).optional()}),k1=e1.extend({method:x(`tools/list`)}),Uye=t1.extend({tools:N(O1)}),A1=N$.extend({content:N(D1).default([]),structuredContent:C(u(),_()).optional(),isError:D().optional()});A1.or(N$.extend({toolResult:_()}));const Wye=k$.extend({name:u(),arguments:C(u(),_()).optional()}),j1=A$.extend({method:x(`tools/call`),params:Wye}),Gye=M$.extend({method:x(`notifications/tools/list_changed`),params:j$.optional()});M({autoRefresh:D().default(!0),debounceMs:i().int().nonnegative().default(300)});const M1=Me([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Kye=O$.extend({level:M1}),N1=A$.extend({method:x(`logging/setLevel`),params:Kye}),qye=j$.extend({level:M1,logger:u().optional(),data:_()}),Jye=M$.extend({method:x(`notifications/message`),params:qye}),Yye=M({hints:N(M({name:u().optional()})).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),Xye=M({mode:Me([`auto`,`required`,`none`]).optional()}),Zye=M({type:x(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:N(D1).default([]),structuredContent:M({}).loose().optional(),isError:D().optional(),_meta:C(u(),_()).optional()}),Qye=Pe(`type`,[w1,T1,E1]),P1=Pe(`type`,[w1,T1,E1,Iye,Zye]),$ye=M({role:h1,content:p([P1,N(P1)]),_meta:C(u(),_()).optional()}),ebe=k$.extend({messages:N($ye),modelPreferences:Yye.optional(),systemPrompt:u().optional(),includeContext:Me([`none`,`thisServer`,`allServers`]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:N(u()).optional(),metadata:w$.optional(),tools:N(O1).optional(),toolChoice:Xye.optional()}),tbe=A$.extend({method:x(`sampling/createMessage`),params:ebe}),F1=N$.extend({model:u(),stopReason:v(Me([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:h1,content:Qye}),I1=N$.extend({model:u(),stopReason:v(Me([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:h1,content:p([P1,N(P1)])}),nbe=M({type:x(`boolean`),title:u().optional(),description:u().optional(),default:D().optional()}),rbe=M({type:x(`string`),title:u().optional(),description:u().optional(),minLength:i().optional(),maxLength:i().optional(),format:Me([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),ibe=M({type:Me([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),abe=M({type:x(`string`),title:u().optional(),description:u().optional(),enum:N(u()),default:u().optional()}),obe=M({type:x(`string`),title:u().optional(),description:u().optional(),oneOf:N(M({const:u(),title:u()})),default:u().optional()}),sbe=p([p([M({type:x(`string`),title:u().optional(),description:u().optional(),enum:N(u()),enumNames:N(u()).optional(),default:u().optional()}),p([abe,obe]),p([M({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:M({type:x(`string`),enum:N(u())}),default:N(u()).optional()}),M({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:M({anyOf:N(M({const:u(),title:u()}))}),default:N(u()).optional()})])]),nbe,rbe,ibe]),cbe=p([k$.extend({mode:x(`form`).optional(),message:u(),requestedSchema:M({type:x(`object`),properties:C(u(),sbe),required:N(u()).optional()})}),k$.extend({mode:x(`url`),message:u(),elicitationId:u(),url:u().url()})]),lbe=A$.extend({method:x(`elicitation/create`),params:cbe}),ube=j$.extend({elicitationId:u()}),dbe=M$.extend({method:x(`notifications/elicitation/complete`),params:ube}),L1=N$.extend({action:Me([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,C(u(),p([u(),i(),D(),N(u())])).optional())}),fbe=M({type:x(`ref/resource`),uri:u()}),pbe=M({type:x(`ref/prompt`),name:u()}),mbe=O$.extend({ref:p([pbe,fbe]),argument:M({name:u(),value:u()}),context:M({arguments:C(u(),u()).optional()}).optional()}),R1=A$.extend({method:x(`completion/complete`),params:mbe});function hbe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function gbe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const _be=N$.extend({completion:ve({values:N(u()).max(100),total:v(i().int()),hasMore:v(D())})}),vbe=M({uri:u().startsWith(`file://`),name:u().optional(),_meta:C(u(),_()).optional()}),ybe=A$.extend({method:x(`roots/list`),params:O$.optional()}),z1=N$.extend({roots:N(vbe)}),bbe=M$.extend({method:x(`notifications/roots/list_changed`),params:j$.optional()});p([Q$,Y$,R1,N1,C1,S1,v1,y1,x1,Dye,kye,j1,k1,a1,s1,c1,u1]),p([G$,$$,Z$,bbe,i1]),p([W$,F1,I1,L1,z1,o1,l1,r1]),p([Q$,tbe,lbe,ybe,a1,s1,c1,u1]),p([G$,$$,Jye,jye,Tye,Gye,Bye,i1,dbe]),p([W$,fye,_be,zye,Pye,xye,Sye,wye,A1,Uye,o1,l1,r1]);var B1=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===B$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new xbe(e.elicitations,n)}return new e(t,n,r)}},xbe=class extends B1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(B$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function V1(e){return e===`completed`||e===`failed`||e===`cancelled`}const Sbe=Symbol(`Let zodToJsonSchema decide on which parser to use`),H1={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`},Cbe=e=>typeof e==`string`?{...H1,name:e}:{...H1,...e},wbe=e=>{let t=Cbe(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 U1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function W1(e,t,n,r,i){e[t]=n,U1(e,t,r,i)}const G1=(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 K1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?G1(t,e.currentPath):t.join(`/`)}}function Tbe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=a0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&W1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&W1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(W1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),W1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Ebe(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?W1(n,`minimum`,r.value,r.message,t):W1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),W1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?W1(n,`maximum`,r.value,r.message,t):W1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),W1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:W1(n,`multipleOf`,r.value,r.message,t);break}return n}function Dbe(){return{type:`boolean`}}function q1(e,t){return a0(e.type._def,t)}const Obe=(e,t)=>a0(e.innerType._def,t);function J1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>J1(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 kbe(e,t)}}const kbe=(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`:W1(n,`minimum`,r.value,r.message,t);break;case`max`:W1(n,`maximum`,r.value,r.message,t);break}return n};function Abe(e,t){return{...a0(e.innerType._def,t),default:e.defaultValue()}}function jbe(e,t){return t.effectStrategy===`input`?a0(e.schema._def,t):K1(t)}function Mbe(e){return{type:`string`,enum:Array.from(e.values)}}const Nbe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Pbe(e,t){let n=[a0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),a0(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(Nbe(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 Fbe(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 Y1;const X1={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:()=>(Y1===void 0&&(Y1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Y1),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 Z1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:W1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:W1(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`:$1(n,`email`,r.message,t);break;case`format:idn-email`:$1(n,`idn-email`,r.message,t);break;case`pattern:zod`:e0(n,X1.email,r.message,t);break}break;case`url`:$1(n,`uri`,r.message,t);break;case`uuid`:$1(n,`uuid`,r.message,t);break;case`regex`:e0(n,r.regex,r.message,t);break;case`cuid`:e0(n,X1.cuid,r.message,t);break;case`cuid2`:e0(n,X1.cuid2,r.message,t);break;case`startsWith`:e0(n,RegExp(`^${Q1(r.value,t)}`),r.message,t);break;case`endsWith`:e0(n,RegExp(`${Q1(r.value,t)}$`),r.message,t);break;case`datetime`:$1(n,`date-time`,r.message,t);break;case`date`:$1(n,`date`,r.message,t);break;case`time`:$1(n,`time`,r.message,t);break;case`duration`:$1(n,`duration`,r.message,t);break;case`length`:W1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),W1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:e0(n,RegExp(Q1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&$1(n,`ipv4`,r.message,t),r.version!==`v4`&&$1(n,`ipv6`,r.message,t);break;case`base64url`:e0(n,X1.base64url,r.message,t);break;case`jwt`:e0(n,X1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&e0(n,X1.ipv4Cidr,r.message,t),r.version!==`v4`&&e0(n,X1.ipv6Cidr,r.message,t);break;case`emoji`:e0(n,X1.emoji(),r.message,t);break;case`ulid`:e0(n,X1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:$1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:W1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:e0(n,X1.base64,r.message,t);break}break;case`nanoid`:e0(n,X1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Q1(e,t){return t.patternStrategy===`escape`?Lbe(e):e}const Ibe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Lbe(e){let t=``;for(let n=0;n<e.length;n++)Ibe.has(e[n])||(t+=`\\`),t+=e[n];return t}function $1(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}}})):W1(e,`format`,t,n,r)}function e0(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:t0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):W1(e,`pattern`,t0(t,r),n,r)}function t0(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
|
|
1174
1174
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
1175
1175
|
]))`;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===Q.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:a0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??K1(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:a0(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Q.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Z1(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Q.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=q1(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Rbe(e,t){return t.mapStrategy===`record`?n0(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[a0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||K1(t),a0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||K1(t)],minItems:2,maxItems:2}}}function zbe(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 Bbe(e){return e.target===`openAi`?void 0:{not:K1({...e,currentPath:[...e.currentPath,`not`]})}}function Vbe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const r0={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Hbe(e,t){if(t.target===`openApi3`)return i0(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in r0&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=r0[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 i0(e,t)}const i0=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>a0(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 Ube(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:r0[e.innerType._def.typeName],nullable:!0}:{type:[r0[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=a0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=a0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Wbe(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`,U1(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?W1(n,`minimum`,r.value,r.message,t):W1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),W1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?W1(n,`maximum`,r.value,r.message,t):W1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),W1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:W1(n,`multipleOf`,r.value,r.message,t);break}return n}function Gbe(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=qbe(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=a0(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=Kbe(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Kbe(e,t){if(e.catchall._def.typeName!==`ZodNever`)return a0(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 qbe(e){try{return e.isOptional()}catch{return!0}}const Jbe=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return a0(e.innerType._def,t);let n=a0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:K1(t)},n]}:K1(t)},Ybe=(e,t)=>{if(t.pipeStrategy===`input`)return a0(e.in._def,t);if(t.pipeStrategy===`output`)return a0(e.out._def,t);let n=a0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,a0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Xbe(e,t){return a0(e.type._def,t)}function Zbe(e,t){let n={type:`array`,uniqueItems:!0,items:a0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&W1(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&W1(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Qbe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>a0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:a0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>a0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function $be(e){return{not:K1(e)}}function exe(e){return K1(e)}const txe=(e,t)=>a0(e.innerType._def,t),nxe=(e,t,n)=>{switch(t){case Q.ZodString:return Z1(e,n);case Q.ZodNumber:return Wbe(e,n);case Q.ZodObject:return Gbe(e,n);case Q.ZodBigInt:return Ebe(e,n);case Q.ZodBoolean:return Dbe();case Q.ZodDate:return J1(e,n);case Q.ZodUndefined:return $be(n);case Q.ZodNull:return Vbe(n);case Q.ZodArray:return Tbe(e,n);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return Hbe(e,n);case Q.ZodIntersection:return Pbe(e,n);case Q.ZodTuple:return Qbe(e,n);case Q.ZodRecord:return n0(e,n);case Q.ZodLiteral:return Fbe(e,n);case Q.ZodEnum:return Mbe(e);case Q.ZodNativeEnum:return zbe(e);case Q.ZodNullable:return Ube(e,n);case Q.ZodOptional:return Jbe(e,n);case Q.ZodMap:return Rbe(e,n);case Q.ZodSet:return Zbe(e,n);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return Xbe(e,n);case Q.ZodNaN:case Q.ZodNever:return Bbe(n);case Q.ZodEffects:return jbe(e,n);case Q.ZodAny:return K1(n);case Q.ZodUnknown:return exe(n);case Q.ZodDefault:return Abe(e,n);case Q.ZodBranded:return q1(e,n);case Q.ZodReadonly:return txe(e,n);case Q.ZodCatch:return Obe(e,n);case Q.ZodPipeline:return Ybe(e,n);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(e=>void 0)(t)}};function a0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Sbe)return i}if(r&&!n){let e=rxe(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=nxe(e,e.typeName,t),o=typeof a==`function`?a0(a(),t):a;if(o&&ixe(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const rxe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:G1(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`),K1(t)):t.$refStrategy===`seen`?K1(t):void 0}},ixe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),axe=(e,t)=>{let n=wbe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:a0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??K1(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=a0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??K1(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 oxe(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function o0(e,t){return p$(e)?A(e,{target:oxe(t?.target),io:t?.pipeStrategy??`input`}):axe(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function s0(e){let t=_$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=b$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function c0(e,t){let n=h$(e,t);if(!n.success)throw n.error;return n.data}var sxe=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(G$,e=>{this._oncancel(e)}),this.setNotificationHandler($$,e=>{this._onprogress(e)}),this.setRequestHandler(Q$,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(a1,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new B1(B$.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(s1,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 B1(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 B1(B$.InvalidParams,`Task not found: ${r}`);if(!V1(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(V1(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[C$]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(c1,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 B1(B$.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(u1,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new B1(B$.InvalidParams,`Task not found: ${e.params.taskId}`);if(V1(n.status))throw new B1(B$.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 B1(B$.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof B1?e:new B1(B$.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),B1.fromError(B$.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),z$(e)||H$(e)?this._onresponse(e):I$(e)?this._onrequest(e,t):iye(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=B1.fromError(B$.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?.[C$]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:B$.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=rye(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 B1(B$.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:B$.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),z$(e)?n(e):n(new B1(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(z$(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),z$(e)?r(e):r(B1.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 B1?e:new B1(B$.InternalError,String(e))}}return}let i;try{let r=await this.request(e,r1,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new B1(B$.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},V1(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new B1(B$.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new B1(B$.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 B1?e:new B1(B$.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||{},[C$]: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 B1?e:new B1(B$.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=h$(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(B1.fromError(B$.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},o1,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},l1,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},yye,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||{},[C$]: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||{},[C$]: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||{},[C$]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=s0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=c0(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=s0(e);this._notificationHandlers.set(n,n=>{let r=c0(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`&&I$(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new B1(B$.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 B1(B$.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new B1(B$.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 B1(B$.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=i1.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),V1(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 B1(B$.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(V1(a.status))throw new B1(B$.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=i1.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),V1(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function l0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cxe(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];l0(a)&&l0(i)?n[r]={...a,...i}:n[r]=i}return n}var lxe=t(Qa(),1),uxe=t(Vo(),1);function dxe(){let e=new lxe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,uxe.default)(e),e}var fxe=class{constructor(e){this._ajv=e??dxe()}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)}}},pxe=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},F1,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},L1,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 mxe(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 hxe(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 gxe=class extends sxe{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(M1.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 fxe,this.setRequestHandler(Y$,e=>this._oninitialize(e)),this.setNotificationHandler(Z$,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(N1,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=M1.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new pxe(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=cxe(this._capabilities,e)}setRequestHandler(e,t){let n=_$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(p$(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=h$(j1,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new B1(B$.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=h$(r1,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new B1(B$.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=h$(A1,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new B1(B$.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){hxe(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&mxe(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:S$.includes(t)?t:x$,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},W$)}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},I1,t):this.request({method:`sampling/createMessage`,params:e},F1,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},L1,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},L1,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new B1(B$.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof B1?e:new B1(B$.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},z1,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const u0=Symbol.for(`mcp.completable`);function d0(e){return!!e&&typeof e==`object`&&u0 in e}function _xe(e){return e[u0]?.complete}var vxe;(function(e){e.Completable=`McpCompletable`})(vxe||={});const yxe=/^[A-Za-z0-9._-]{1,128}$/;function bxe(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`),!yxe.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 xxe(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 f0(e){let t=bxe(e);return xxe(e,t.warnings),t.isValid}var Sxe=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)}},p0=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 gxe(e,t)}get experimental(){return this._experimental||={tasks:new Sxe(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(v0(k1)),this.server.assertCanSetRequestHandler(v0(j1)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(k1,()=>({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=v$(t.inputSchema);return e?o0(e,{strictUnions:!0,pipeStrategy:`input`}):Cxe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=v$(t.outputSchema);e&&(n.outputSchema=o0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(j1,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B1(B$.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B1(B$.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 B1(B$.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new B1(B$.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 B1&&e.code===B$.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$(v$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=y$(`error`in r?r.error:`Unknown error`);throw new B1(B$.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 B1(B$.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await g$(v$(e.outputSchema),t.structuredContent);if(!r.success){let e=y$(`error`in r?r.error:`Unknown error`);throw new B1(B$.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 B1(B$.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(v0(R1)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(R1,async e=>{switch(e.params.ref.type){case`ref/prompt`:return hbe(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return gbe(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B1(B$.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new B1(B$.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new B1(B$.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return b0;let r=_$(n.argsSchema)?.[e.params.argument.name];if(!d0(r))return b0;let i=_xe(r);return i?y0(await i(e.params.argument.value,e.params.context)):b0}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 b0;throw new B1(B$.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?y0(await r(e.params.argument.value,e.params.context)):b0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(v0(v1)),this.server.assertCanSetRequestHandler(v0(y1)),this.server.assertCanSetRequestHandler(v0(x1)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(v1,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(y1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(x1,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new B1(B$.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 B1(B$.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(v0(S1)),this.server.assertCanSetRequestHandler(v0(C1)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(S1,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?wxe(t.argsSchema):void 0}))})),this.server.setRequestHandler(C1,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B1(B$.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B1(B$.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await g$(v$(n.argsSchema),e.params.arguments);if(!r.success){let t=y$(`error`in r?r.error:`Unknown error`);throw new B1(B$.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:m$(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=m$(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=>d0(e instanceof ce?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){f0(e);let l={title:t,description:n,inputSchema:_0(r),outputSchema:_0(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`&&f0(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=m$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=m$(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(g0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!g0(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 Cxe={type:`object`,properties:{}};function m0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function h0(e){return`_def`in e||`_zod`in e||m0(e)}function g0(e){return typeof e!=`object`||!e||h0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(m0)}function _0(e){if(e){if(g0(e))return m$(e);if(!h0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function wxe(e){let t=_$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:$ve(t),required:!eye(t)})):[]}function v0(e){let t=_$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=b$(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function y0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const b0={completion:{values:[],hasMore:!1}};var x0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Txe=e=>e instanceof x0?e:new x0(e.message,{cause:e}),Exe=global.Request,S0=class extends Exe{constructor(e,t){typeof e==`object`&&w0 in e&&(e=e[w0]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Dxe=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)},C0=Symbol(`wrapBodyStream`),Oxe=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new S0(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[C0]){let e;a.body=new ReadableStream({async pull(t){try{e||=vd.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=vd.toWeb(r);return new S0(t,a)},w0=Symbol(`getRequestCache`),T0=Symbol(`requestCache`),E0=Symbol(`incomingKey`),D0=Symbol(`urlKey`),kxe=Symbol(`headersKey`),O0=Symbol(`abortControllerKey`),k0={get method(){return this[E0].method||`GET`},get url(){return this[D0]},get headers(){return this[kxe]||=Dxe(this[E0])},[Symbol(`getAbortController`)](){return this[w0](),this[O0]},[w0](){return this[O0]||=new AbortController,this[T0]||=Oxe(this.method,this[D0],this.headers,this[E0],this[O0])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(k0,e,{get(){return this[w0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(k0,e,{value:function(){return this[w0]()[e]()}})}),Object.defineProperty(k0,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[T0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(k0,S0.prototype);var Axe=(e,t)=>{let n=Object.create(k0);n[E0]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof wd)throw new x0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[D0]=new URL(r).href}catch(e){throw new x0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof wd?e.authority:e.headers.host)||t;if(!i)throw new x0(`Missing host header`);let a;if(e instanceof wd){if(a=e.scheme,!(a===`http`||a===`https`))throw new x0(`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 x0(`Invalid host header`);return n[D0]=o.href,n},A0=Symbol(`responseCache`),j0=Symbol(`getResponseCache`),M0=Symbol(`cache`),N0=global.Response,P0=class e{#e;#t;[j0](){return delete this[M0],this[A0]||=new N0(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[A0];if(e){this.#t=e,this[j0]();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[M0]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[M0];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[j0]().headers}get status(){return this[M0]?.[0]??this[j0]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(P0.prototype,e,{get(){return this[j0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(P0.prototype,e,{value:function(){return this[j0]()[e]()}})}),Object.defineProperty(P0.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[A0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(P0,N0),Object.setPrototypeOf(P0.prototype,N0.prototype);async function jxe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function F0(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 Mxe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:F0(e.getReader(),t)}var I0=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},Nxe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=vte);var L0=Symbol(`outgoingEnded`),R0=Symbol(`incomingDraining`),Pxe=500,Fxe=64*1024*1024,z0=e=>{let t=e;if(e.destroyed||t[R0])return;if(t[R0]=!0,e instanceof wd){try{e.stream?.close?.(jte.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,Pxe);a.unref?.();let o=e=>{n+=e.length,n>Fxe&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},Ixe=()=>new Response(null,{status:400}),B0=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),V0=(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))},H0=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},U0=async(e,t)=>{let[n,r,i]=e[M0],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=I0(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=I0(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())):(H0(t),await Mxe(r,t)?.catch(e=>V0(e,t))),t[L0]?.()},Lxe=e=>typeof e.then==`function`,Rxe=async(e,t,n={})=>{if(Lxe(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(B0);if(M0 in e)return U0(e,t);let r=I0(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 jxe(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&&H0(t),await F0(n,t,o))}else r[Nxe]||(t.writeHead(e.status,r),t.end());t[L0]?.()},W0=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==S0&&(Object.defineProperty(global,`Request`,{value:S0}),Object.defineProperty(global,`Response`,{value:P0})),async(r,i)=>{let a,o;try{o=Axe(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[C0]=!0,r.on(`end`,()=>{s=!0}),r instanceof wd&&(i[L0]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{z0(r)})})}),i.on(`finish`,()=>{s||z0(r)})),i.on(`close`,()=>{o[O0]&&(r.errored?o[O0].abort(r.errored.toString()):i.writableFinished||o[O0].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{z0(r)})})}),a=e(o,{incoming:r,outgoing:i}),M0 in a)return U0(a,i)}catch(e){if(a)return V0(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:Txe(e)),!a)return}else a=o?B0(e):Ixe()}try{return await Rxe(a,i,t)}catch(e){return V0(e,i)}}},zxe=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
|
|
1176
1176
|
`;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=>U$.parse(e)):[U$.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(X$);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(I$)){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=>X$(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)I$(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)I$(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;I$(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&&!S$.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${S$.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${S$.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((z$(e)||H$(e))&&(n=e.id),n===void 0){if(z$(e)||H$(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(z$(e)||H$(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)}}}},Bxe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new zxe(e),this._requestListener=W0(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 W0(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};function G0(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||!Vxe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=ae(i.error);throw new B1(B$.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function Vxe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const K0=2e3,q0=2e3,Hxe=[/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 J0(e){return Hxe.some(t=>t.test(e))}function Uxe(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 Eu(e)?e:null}catch{return null}}function Wxe(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&&Eu(a)?a:null}function Gxe(e){let t=[];for(let n of e.split(`
|
|
@@ -2011,7 +2011,7 @@ native-divergence-injected
|
|
|
2011
2011
|
`,`utf-8`),o&&E!==void 0){let r=null;try{B(O)&&(r=V(O,`utf-8`))}catch(e){r=null,E7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&fa(r)!==fa(E)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:E.length,candidateBytes:S.length})),ve(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=Vx(e);if(t.length===0)return;o?.record({event:Vb,docName:i,writerId:kx.id,direction:`b`,site:j,lostLen:t.reduce((e,t)=>e+t.length,0),digest:Rn(t.join(`
|
|
2012
2012
|
`))})}catch(e){E7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},WR)}catch(e){throw t.recordStoreFailure(i,k7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(hoe(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let re=`${O}.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 Ns(re,S,`utf-8`),await Qs(re,O),pz(O,hz(S)),t.clearStoreFailure(i),boe();try{d?.(i,f,S,E??null)}catch(e){E7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{zs(re)}catch{}throw C.delete(i),t.recordStoreFailure(i,k7(e)),E7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}E7.info({filePath:O,bytes:S.length},`[persistence] Wrote ${O} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){E7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Ts({"persistence.bytes":S.length}),oe()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),Se?.record((Date.now()-o)/1e3)})}function Ee({document:e,documentName:n,lastTransactionOrigin:r}){k.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function De(e=`within-branch`){return re?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,re):(re=(async()=>{let n=e;for(;;){let e=[...k.entries()];if(k.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await Te({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=Rn(r),a;try{a=qje(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:Rn(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}gse(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),E7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,k.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{re=null}),re)}let Oe={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),tS(i))return;if(nS(i)){RAe(n,i,h);return}if(rS(i)){QK(n,i,_);return}if(iS(i)||aS(i)){Vje(n,i,v);return}we();let o=Date.now();return Ms(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{E7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=GM(i,r);if(!B(a))return;let o=a;try{let e=H(a);if(!KM(e,r)){E7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(wc(e)===`ELOOP`){E7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=Qu(o).size;if(s>524288)throw E7.warn({documentName:i,fileSize:s,limit:$e},`[persistence] Document exceeds open byte limit; refusing to load`),new Gje(i,s);let c=V(a,`utf-8`),l=n.getXmlFragment(`default`);E7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{GR(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(Ea,crypto.randomUUID())},WR),E7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{E7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):E7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{xe?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!tS(n)){if(nS(n)){let t=await BAe(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){E7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(rS(n)){if(await tq(e,n,r,_)===`persisted`){let e=D7(r,c);if(e&&e.id!==jx.id&&!e.id.startsWith(`agent-`)){let t=WK(n);t&&(Dj(t.docKey,e.id,e.name,e.id,t.subject),oe())}}return}if(iS(n)||aS(n)){await Hje(e,n,r,v);return}if(t.isBatchInProgress()){Ee({document:e,documentName:n,lastTransactionOrigin:r});return}return Te({document:e,documentName:n,lastTransactionOrigin:r})}}};async function ke(){ne&&await ne}async function Ae(){if(ne){await ne;return}jj()!==0&&(ne=A().finally(()=>{ne=null,O&&(O=!1,oe())}),await ne)}function je(){return{branchDeferred:k.size,quiescenceDeferred:C.size}}async function Me(e,n){if(!cS(n)){if(t.isBatchInProgress()){Ee({document:e,documentName:n,lastTransactionOrigin:null});return}return Te({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:Oe,durabilityState:t,flushDeferredStores:De,flushPendingGitCommit:se,flushContributors:Ae,waitForPendingCommits:ke,getQueueDepths:je,forceStore:Me,configPersistenceCtx:h,managedArtifactCtx:_}}const j7=P(`persistence-staleness`);var M7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function Xje(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??nC,c=new Map,l=!1,u=null;function d(e){return O7(e)}function f(e){return e===void 0?void 0:fa(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Ka(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),cS(n)||yS(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S,y,b)){c.delete(n);continue}m++;let C=r(),w=s(v,C);if(w!==null&&w<t)continue;let T=c.get(n);if(T&&T.fingerprint===x&&(T.declined||C-T.atMs<t))continue;let E=T?.fingerprint!==x;E&&Poe();let ee=!E&&T?T.firstDetectedAtMs:C,te=C-ee,D=null,ne=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(D=`disk-file-never-loaded`):t===null?D=`disk-file-missing`:fa(t)!==S&&(D=`disk-diverged-from-base`)}catch(e){e instanceof M7?(D=`disk-read-refused`,j7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(D=`disk-read-failed`,ne=!0,j7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(D!==null){g++,Ioe(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!ne}),j7.warn({docName:n,ageMs:w,staleForMs:te,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:D},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}j7.warn({docName:n,ageMs:w,staleForMs:te,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!1}),Foe(),h++;try{await e.forceStore(v,n)}catch(e){j7.error({err:e,docName:n,staleForMs:te},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let O=v.getText(`source`).toString(),re=i(n),k=d(O);p(k,f(re),O,re)&&k===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!0}),j7.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?j7.info(v,`[persistence-staleness] sweep complete`):j7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{j7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function Zje(e){try{let t=mc({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 N7(e){let t=Bk(e),n=R(t,`principal.json`),{name:r,email:i}=await Zje(e);if(B(n)){let e;try{e=JSON.parse(V(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${gd()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?dh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?dh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return ed(n,JSON.stringify(s,null,2),`utf-8`),s}Hu(t,{recursive:!0});let a=`principal-${gd()}`,o=a.slice(10,18),s={id:a,display_name:r?dh(r):`Local User`,display_email:i?dh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return ed(n,JSON.stringify(s,null,2),`utf-8`),s}var Qje=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?.()}};const $je=P(`recovered-file-target`);function eMe({watcher:e,contentDir:t,relativePath:n,exists:r,invalidateReferencedAssetsCache:i}){let a=I(t,n);if(!r){e.mutateFileIndex({kind:`file-delete`,path:a,relativePath:n}),i?.();return}try{let t=H(a),r=Qu(t);e.mutateFileIndex({kind:`file-create`,path:t,relativePath:n,size:r.size,modifiedTs:r.mtimeMs,inode:r.ino})}catch(t){let r=t instanceof Error&&`code`in t&&typeof t.code==`string`?t.code:`UNKNOWN`;r!==`ENOENT`&&$je.warn({code:r},`recovered file metadata unavailable; treating local target as deleted`),e.mutateFileIndex({kind:`file-delete`,path:a,relativePath:n})}i?.()}function P7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function tMe(e,t){try{if(oS(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(P7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw sx(),Ts({"auth.reason":`doc-deleted`}),new KZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){bse(),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 ox(),Ts({"auth.reason":`rename-redirect`}),new KZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw P7(t,i)?(t.recentlyRemovedDocs.delete(i),ox(),Ts({"auth.reason":`rename-redirect`}),new KZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(sx(),Ts({"auth.reason":`doc-deleted`}),new KZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof KZ)throw t;yse(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const F7=P(`removed-docs-journal`);function I7(e){return I(Bk(e),`removed-docs.json`)}function nMe(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 rMe(e){let t=I7(e);if(!B(t))return[];try{let e=JSON.parse(V(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return F7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!nMe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return F7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function L7(e,t){let n=I7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};Ws(F(n),{recursive:!0});let i=`${n}.tmp`;$s(i,JSON.stringify(r),`utf-8`),Ls(i,n)}const R7=P(`server-observers`);function z7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(tS(r)||nS(r)||iS(r)||aS(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=pw({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 R7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),rx(`a`),rx(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(R7.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){R7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const B7=`state.json`;function V7(e){return e.lockDir,B(e.shadowRepoDir)?`adopt`:`fresh`}function H7(e){return R(e,B7)}function iMe(e,t){return e===t||e===0&&t===1}var U7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function aMe(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 W7(e){let t=H7(e);if(!B(t))return{status:`absent`};let n;try{n=V(t,`utf-8`)}catch(e){throw new U7({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 U7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!aMe(r))throw new U7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function G7(e,t){let n=H7(e);Hu(F(n),{recursive:!0}),ed(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function K7(e){let t=P(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Sc,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=H7(e.lockDir),s=W7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!iMe(c.stateSchemaVersion,n))throw new U7({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 G7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(V7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return G7(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 G7(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 oMe(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 sMe(e){return e.git?.toString()??e.message??``}function q7(e,t){return t.some(t=>t.test(e))}const cMe={"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`},lMe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],J7=[/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],uMe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],dMe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],fMe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],pMe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],mMe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],hMe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],gMe=[/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],_Me=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],vMe=[/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],yMe=[/\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],bMe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function Y7(e){let t=xMe(e);return{...t,userFacingCode:oMe(t.class,t.subclass)}}function xMe(e){let t=e instanceof Error?e:Error(String(e)),n=sMe(t),r=`${t.message}\n${n}`.toLowerCase();if(q7(r,hMe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(q7(r,gMe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(q7(r,_Me))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=Lt(t);return i.kind===`auth`?i.subclass===`403`&&q7(r,J7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:cMe[i.subclass],rawStderr:n}:q7(r,J7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:q7(r,lMe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:q7(r,uMe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:q7(r,dMe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:q7(r,fMe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:q7(r,mMe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:q7(r,pMe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:q7(r,bMe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:q7(r,yMe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:q7(r,vMe)?/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 SMe(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 X7=P(`github-permissions`);function CMe(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function wMe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function TMe(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 EMe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return X7.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=TMe(t);return n===null?(X7.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 X7.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function DMe(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){X7.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function OMe(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 DMe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(X7.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`}):(X7.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${CMe(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;X7.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:wMe(l)}),t=await EMe(e,l!==void 0);return X7.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?(X7.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(X7.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function kMe(e){let t=performance.now(),n=await OMe(e);return NMe(n,performance.now()-t),n}function AMe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let Z7=null;function jMe(){return Z7||=nc().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}.`}),Z7}let Q7=null;function MMe(){return Q7||=nc().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),Q7}function NMe(e,t){let n=AMe(e);jMe().add(1,n),MMe().record(t,{outcome:n.outcome})}function $7(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 PMe(e,t){return t===`anonymous`?Math.max(180,e):e}const e9=P(`sync-engine`),t9=/^[0-9a-f]{40}$/i,FMe=Sd(vu);var n9=class extends Error{constructor(e,t){super(`Shareable .ok subtree "${e}" could not be fully enumerated; sync staging aborted`,{cause:t}),this.name=`ShareableOkEnumerationError`}};function IMe(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 LMe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function r9(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}const i9={syncScope:{pathBase:`content`}},a9={syncScope:{pathBase:`project`}};function o9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function s9(e){let t=Ed(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 RMe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const c9=12e4;var zMe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;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.rootOkOutsideContentWalk=UM(L(this.contentDir,I(this.projectDir,`.ok`))).startsWith(`..`),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=SMe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??kMe,this.statePath=R(Bk(this.projectDir),`sync-state.json`),this.conflictStore=new XZ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return RF(this.projectDir)}gitHandle(e){return _c(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){e9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),e9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){e9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=Pd(this.projectDir),n=t?I(t,`MERGE_HEAD`):null,r=n!==null&&B(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){e9.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 Jb(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&&e9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){e9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){e9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){e9.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`),e9.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=$7(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=$7(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),e9.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,e9.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){e9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await xd(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||s9(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||s9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){e9.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){e9.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 hc(()=>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,e9.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`,e9.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`?e9.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}`):e9.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 e9.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||s9(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?sme(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 gB(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=LF(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,r9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,e9.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){e9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=LMe(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,e9.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,e9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!r9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,e9.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(!B(I(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return e9.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=Pd(this.projectDir),r=n?I(n,`MERGE_HEAD`):null;if(r!==null&&B(r))try{let n=this.gitHandle(),r=new Set(await Jb(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&&e9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){e9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{e9.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&&(e9.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=>{e9.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??o9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{e9.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){e9.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`?PMe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=RMe(this.consecutiveFailures);return o9(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(s9(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`,e9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError(Y7(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=Y7(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=Y7(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`),e9.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 Jb(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await Jb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(Y7(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(Y7(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){e9.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 e9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(Y7(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 e9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(Y7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(e9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(Y7(Error(`git merge --ff-only timed out after ${c9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),e9.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 e9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(Y7(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 e9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(Y7(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 e9.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 FMe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:c9}),{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:IMe({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(!B(I(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),e9.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=V(I(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`&&e9.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=Di(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){e9.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=I(this.projectDir,t);gL(e,this.projectDir),$s(e,n)}for(let e of t){let t=I(this.projectDir,e);gL(t,this.projectDir);try{zs(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=I(this.projectDir,e),n=UM(L(this.contentDir,t));return!n.startsWith(`..`)&&Ux(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 Jb(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(s9(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=I(ad(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;this.transitionTo(`pushing`);try{let e=this.gatherContentFilesSync();await hc(async()=>{let r=this.gitHandle(t);if(s9(this.projectDir)){e9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await r.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)){e9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(Y7(e instanceof Error?e:Error(String(e))),`push`);return}await r.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(r,i),o=await this.stageContentFiles(r,e),s=new Set(o.map(e=>e.projectRelPath)),c=[...a].filter(e=>!s.has(e));await this.removePathsFromIndex(r,c);let l=(await r.git.raw([`write-tree`])).trim(),u=``;try{u=(await r.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(u&&u===l){let t=null;try{t=(await r.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(t===i){e9.info({contentFileCount:e.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}e9.info({headSha:i,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=i;return}let d=[],f=[];try{let t=await Jb(r.git,[`diff-tree`,`--name-only`,`-r`,i,l]);if(t.length>0){let n=new Map(e.map(e=>[e.projectRelPath,e.contentRelPath]));for(let e of t){d.push(e);let t=n.get(e)??UM(L(this.contentDir,I(this.projectDir,e)));t&&!t.startsWith(`..`)&&f.push(t)}}}catch{d=e.map(e=>e.projectRelPath).concat(c),f=e.map(e=>e.contentRelPath)}let p=this.buildCommitMessage(f),m=await gB(this.projectDir),h=m===null;this.identityUnresolved!==h&&(this.identityUnresolved=h,this.cc1Broadcaster?.signal(`sync-status`));let g=m?.name??`OpenKnowledge`,_=m?.email??`sync@open-knowledge.local`;yc(r,{GIT_AUTHOR_NAME:g,GIT_AUTHOR_EMAIL:_,GIT_COMMITTER_NAME:g,GIT_COMMITTER_EMAIL:_});let v=(await r.git.raw([`commit-tree`,l,`-p`,i,`-m`,p])).trim();if(!v||!t9.test(v)){e9.warn({raw:v},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,v,i]),await this.resetRealIndexForPaths(d);let y=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),y=!0}catch{}y?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=v}),n&&(this.lastPushedSha=n,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=t instanceof Error?t:Error(String(t));n instanceof n9&&e9.warn({err:n},`[sync] push cycle: staging error detail`);let r=Y7(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){e9.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=Y7(e instanceof Error?e:Error(String(e)));if(t.class===`semantic`&&t.subclass===`merge-conflict`)await this.handleMergeConflict();else if(e instanceof n9)throw e;else this.handleError(t,`pull`);this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}e9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{$u(t)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=I(ad(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);let i=await this.stageContentFiles(a,n),o=new Set(i.map(e=>e.projectRelPath)),s=[...r].filter(e=>!o.has(e));await this.removePathsFromIndex(a,s);let c=(await a.git.raw([`write-tree`])).trim();if(c===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let l=[];try{l=await Jb(a.git,[`diff-tree`,`--name-only`,`-r`,t,c])}catch{l=n.map(e=>e.projectRelPath).concat(s)}let u=await gB(this.projectDir),d=u?.name??`OpenKnowledge`,f=u?.email??`sync@open-knowledge.local`;yc(a,{GIT_AUTHOR_NAME:d,GIT_AUTHOR_EMAIL:f,GIT_COMMITTER_NAME:d,GIT_COMMITTER_EMAIL:f});let p=(await a.git.raw([`commit-tree`,c,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!p||!t9.test(p)?(e9.warn({raw:p},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,p,t]),await this.resetRealIndexForPaths(l,e),p)}finally{try{$u(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await Jb(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return e9.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 Jb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return e9.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(),e9.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 e9.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){e9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await Jb(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`--`,...a]);for(let e of t)n.add(e)}catch(e){r=!1,e9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&e9.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=r?t.filter(e=>!n.has(e.projectRelPath)):t,a=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),o=r?i.filter(e=>a(e.projectRelPath)):[],s=r?i.filter(e=>!a(e.projectRelPath)):i;for(let[t,n]of[[[`add`,`--`],s],[[`add`,`-f`,`--`],o]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...i])}return i}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new n9(UM(L(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=qu(r,{withFileTypes:!0})}catch(e){o?.(e,r);return}for(let c of s){let s=I(r,c.name);if(c.isDirectory()){let e=UM(L(i,s));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e,a))continue;let r=e.split(`/`).some(e=>e.toLowerCase()===`.ok`);n(s,i,a,o??(r?t:void 0))}else if(c.isFile()||c.isSymbolicLink()){let t=UM(L(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=UM(L(this.contentDir,s)),n=UM(L(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(B(this.contentDir)&&n(this.contentDir,this.contentDir,i9),this.rootOkOutsideContentWalk){let e=I(this.projectDir,`.ok`);B(e)&&!this.contentFilter.isDirExcluded(`.ok`,a9)&&n(e,this.projectDir,a9,t)}return e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await Jb(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=I(this.projectDir,e),r=UM(L(this.contentDir,t)),i=!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r,i9),a=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,a9);(i||a)&&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 Jb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){e9.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){e9.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)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=UM(L(this.projectDir,Us(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),t.toLowerCase()===a.toLowerCase()?e9.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):e9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){e9.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){e9.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(),e9.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`),e9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=Pd(this.projectDir);t=n===null||!B(I(n,`MERGE_HEAD`))}catch(e){e9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),e9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){e9.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`),e9.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){e9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){e9.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),e9.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,e9.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)};ed(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){e9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(B(this.statePath))try{let e=V(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){e9.warn({err:e},`[sync] failed to load sync state`)}}};bs();const BMe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function VMe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(tS(e)||nS(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&BMe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Es(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),xs.with(vs.extract(xs.active(),r),e)}else e()}catch(e){P(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let l9=!1;function u9(){if(l9)return;let e=Pte;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){l9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),l9=!0}catch(e){P(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const HMe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),UMe=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function WMe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(z6).join(` `)} auth git-credential`]}function GMe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=xu(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],YM({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return P(`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 P(`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(`
|
|
2013
2013
|
`)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=R(e,r);if(!KM(a,t))continue;let s=Ez(a,t);i.has(s)||B(a)&&i.set(s,o)}return i}function d9(e){u9();let t=e.ingressPolicy??kB({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,authStreamHeartbeatMs:g,skipStateManifestCheck:_=!1,singleDocRelPath:v,ephemeral:y=!1}=e,b=P(`server`),x=new n7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),E=e=>x.switchReconciledBaseScope(e),ee=e=>x.setBatchInProgress(e),te=()=>x.isBatchInProgress();function D(e){let t=Ds({absPath:Us(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=be(t.error)&&t.error.code===`SCHEMA_INVALID`?t.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(n.length>0){let e=n.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}if(e?.requireValid)throw Error(`Project config is invalid`,{cause:t.error});b.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function ne(){let e=Ds({absPath:Us(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=me(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||b.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=Ds({absPath:Us(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});return n.valid||b.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:xe(n.value.autoSync?.default)??`off`,source:`committed-default`}}function O(){let e=Ds({absPath:Us(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?Et(e):Or;return bje(r,t.plugins.okf),t}function re(){return Ds({absPath:Us(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function k(){return eM(r,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function A(){let e=Ds({absPath:Us(`project-local`,r,u),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function ie(){return ks({cwd:r,homedirOverride:u,warn:e=>b.debug({message:e},`[config] diagnostics read`)})}function ae(){for(let e of ie().diagnostics)e.code===`REMOVED_KEY`&&b.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 oe(e){return`${Wj(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}let se;function ce(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=ne();i=t.mode,$t?.setMode(t.mode,t.source).catch(n=>{b.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let a=k();if(N.applyConfig({enabled:a.enabled,providerFingerprint:oe(a)}),e===`__config__/project`){try{let e=D({requireValid:!0});ge?.setAttachmentFolderPath(e),se!==void 0&&e!==se&&b.warn({previous:se,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),se=e}catch(e){b.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}ke?.signal(`lint-config`),(t??O().plugins.okf?.generate?.index===!0)||U5({projectDir:r,contentDir:n,generatedDocNames:xt(),enabled:!1}).then(e=>{e.ok||b.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),gt()}b.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}tc();let le=gd(),ue=Bk(r),de=new _f({localDir:ue,log:P(`acp-registry`)}),j=new sf(ue,P(`acp-permissions`));if(jc(ue,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!_)try{K7({lockDir:ue,shadowRepoDir:Fd(r)})}catch(e){throw Cc(ue),e}let fe=Po(),pe=(e,t)=>fe.resolveEmbed(e,t),he=(e,t)=>{let r=fe.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=R(n,r);if(!WM(i,R(n)))return null;try{let e=Qu(i);return e.isFile()?e.size:null}catch{return null}},ge,_e,M,ve,ye,Se,Ce,Te,Ee,De,Oe,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=null,Fe=k(),N=new hde({loadEmbedder:e.embedderLoader??(()=>{let t=k();return tde({keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:I(Bk(r),`embeddings`),enabled:Fe.enabled,providerFingerprint:oe(Fe)}),Ie=null,Le=new Set,Re=!1,ze=[],Be,Ve,He,Ue=new Promise((e,t)=>{Ve=e,He=t}),We,Ge=new Promise(e=>{We=e});async function Ke(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Ge,n])!==t)return S()}finally{e&&clearTimeout(e)}try{return a7(r).branch??null}catch(e){return b.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function qe(e){ke?.signal(e)}let Je,Ye,Xe,Ze=!1,Qe=!1,$e=new AbortController,et=new Set,tt=!1,nt=!1,rt=!1,it=0,at,ot=new Promise(e=>{at=e});function st(e){rt||(rt=!0,at(e))}function ct(){return tt||et.size>0}function lt(){Qe||!Ze||(Je!==void 0&&clearTimeout(Je),Je=setTimeout(()=>{Je=void 0,dt()},500),Je.unref?.())}function ut(){if(Qe){st({status:`cancelled`,indexCount:0});return}tt=!0,nt=!0,Ye=setImmediate(()=>{Ye=void 0,dt()})}function dt(){if(Qe||!Ze||!ct())return;if(Xe!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(x.isBatchInProgress()){lt();return}let t=tt,n=new Set(et),r=nt;tt=!1,et.clear(),nt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Xe=(async()=>{let e=await Tt(i,$e.signal);if(e.status===`deferred`){tt=!0,r&&(it+=e.indexCount,nt=!0);return}r&&(it+=e.indexCount,e.status===`completed`&&ct()?nt=!0:st({...e,indexCount:it}))})().catch(e=>{b.warn({err:e},`[index] index regeneration coordinator failed`),r&&st({status:`failed`,indexCount:0})}).finally(()=>{if(Xe=void 0,Qe){r&&st({status:`cancelled`,indexCount:0});return}ct()&&Je===void 0?lt():!ct()&&Je===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function ft(){if(!Qe){let e=Xe;Qe=!0,$e.abort(),Je!==void 0&&(clearTimeout(Je),Je=void 0),Ye!==void 0&&(clearImmediate(Ye),Ye=void 0),et.clear(),tt=!1,nt=!1,e===void 0&&st({status:`cancelled`,indexCount:0})}await Xe}function pt(e){Qe||cje(e)||(et.add(X5(e)),lt())}function mt(e){if(!Qe){for(let t of sje(e))et.add(t);lt()}}function ht(e){let t=Zt?.getFileIndex();if(!t){pt(e);return}let n=X5(e);if($5(t.keys()).has(n)){pt(e);return}mt(X5(n))}function gt(){Qe||(tt=!0,lt())}function _t(e){let t=Zt?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let vt=!1,yt={origin:UMe,writer:Rse,isConflict:e=>$t?.getConflicts().some(t=>O5(t,e,r,n))===!0,getDocument:e=>Ce.documents.get(e),writeDisk:async(e,t)=>{Ws(F(e),{recursive:!0}),await As(e,t,{fs:Ps})},registerWrite:(e,t)=>pz(e,hz(t)),noteFileIndex:e=>Zt?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>qe(`files`),attribute:async(e,t)=>{Dj(e,t.id,t.name,t.id),vt=!0}};function bt(e){return e===``?J5:`${e}/${J5}`}function xt(){return[...Zt?$5(Zt.getFileIndex().keys()):new Set([``])].map(bt)}function St(e){let t=O().plugins.okf?.generate?.index===!0,n=e.state===`ready`||e.state===`not-applicable`;return{enabled:t,active:t&&n,git:e.state===`ready`?{state:e.state,ownership:e.ownership}:{state:e.state}}}function Ct(){return St(V5({projectDir:r,contentDir:n,generatedDocNames:xt()}))}async function wt(e){let t=await U5({projectDir:r,contentDir:n,generatedDocNames:xt(),enabled:e});if(!t.ok)return{...Ct(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await ws({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){b.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...Ct(),applied:!1,reason:`config-write`}}try{let e=V(i.path,`utf-8`);D5(Ce.documents.get(`__config__/project`)??null,ln,e,ye.configPersistenceCtx)}catch(e){b.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return ce(ln,e),{...Ct(),applied:!0}}async function Tt(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>O().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=Zt?.getFileIndex();if(!c)return{status:`failed`,indexCount:0};try{if(await e.generatedIndexTestHooks?.beforePlan?.({fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=lje({docs:c,docExtension:Xx,currentMarkdownFor:()=>null}),l=V5({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>bt(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return b.warn({state:l.state},`[index] generated index regeneration paused by Git attributes`),{status:`blocked`,indexCount:a};for(let{directory:r,markdown:c}of o){if(!t.fullSweep&&!t.directories.has(r))continue;if(i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};if(await e.generatedIndexTestHooks?.beforeDecision?.({directory:r,fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};let o=bt(r),l=R(n,`${o}.md`),u;try{u=V(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&b.warn({err:e,path:Ks(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await k5({docName:o,absPath:l,markdown:c,currentMarkdown:u},yt);d===`blocked-conflict`?b.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):b.info({event:`generated-index-regeneration`,outcome:d===`unchanged`?`unchanged`:`written`,directory:r},`[index] generated index regeneration completed`),await e.generatedIndexTestHooks?.afterWrite?.({docName:o,fullSweep:t.fullSweep,signal:i}),!t.fullSweep&&r!==``&&u===null&&mt(X5(r))}}finally{vt&&=(await ye.waitForPendingCommits(),await ye.flushContributors(),!1),o!==void 0&&(EL(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),DL(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return b.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Dt=null,Ot=!1,kt=()=>{try{L7(r,At.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},At=new Qje(void 0,{onEviction:()=>_se(),onSizeChange:e=>vse(e),onMutate:()=>{!Ot||Dt!==null||(Dt=setTimeout(()=>{Dt=null,kt()},2e3))}});for(let[e,t]of rMe(r))oS(e)||LZ(e)&&([`.md`,`.mdx`].some(t=>{let r=R(n,`${e}${t}`);return WM(r,R(n))&&B(r)})||At.restore(e,t));Ot=!0;let jt={current:null},Mt=(e,t)=>{oS(e)||At.setRenamed(e,t)},Nt=e=>{if(!oS(e)){if(At.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}At.setDeleted(e),jt.current?.deleted(e)}},Pt=e=>{oS(e)||At.delete(e)};try{let m=`./`;try{m=D()}catch(e){b.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}se=m,ge=tP({projectDir:r,contentDir:n,singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:hL(n),rescanInPlaceSkillDirs:()=>hL(n),skillRootPaths:ohe(n),onAfterRebuild:()=>{_e.refreshContentScope().catch(e=>{P(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Qz(Zt).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?P(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):P(`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=>{P(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),_e=new UR({projectDir:r,contentDir:n,contentFilter:ge,getGlobalSkillRoots:()=>KK(ye.managedArtifactCtx),signalChannel:qe,getLocalTargetInventory:()=>BK(Zt,n),onRecoveredFileTarget:(e,t)=>{Zt&&eMe({watcher:Zt,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Ne})}}),M={current:f},ve=s?zje({getShadow:()=>M.current??null,getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Pd(r)??void 0,isWriterLive:e=>{if(!Me&&!Te)return P(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Me?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Te?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ye=A7({contentDir:n,projectDir:r,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:M,ephemeral:y,contentRoot:p,derivedDocumentIndex:_e,configHomedirOverride:u,getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,resolveEmbed:pe,resolveSize:he,getPrincipal:()=>Ie,onAgentCommit:()=>ke?.signal(`session-activity`),onFlushCommit:()=>ve?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{ke?.emitDiskAck(e,t),!oS(e)&&(uje(r,n,e)&&pt(e),JB(r,n)&&(Ne?.(),qe(`files`)))},onConfigRejected:(e,t)=>ke?.emitConfigValidationRejected(e,t),onConfigPersisted:ce,isRecentlyRemoved:e=>At.has(e),mdManager:e.mdManager,getLossRing:()=>Se,durabilityState:x}),Ce=new OAe({quiet:i,debounce:a,maxDebounce:o,extensions:[ye.extension]});let _=Ce;ze.push(FC(()=>_.documents.size),IC(()=>ye.getQueueDepths()),RC(()=>{let e=0;for(let t of _.documents.values())e+=t.directConnectionsCount;return{websocket:_.getConnectionsCount()-e,direct:e}})),BC(),y||(Pe=Xje({getLoadedDocuments:()=>_.documents,forceStore:(e,t)=>ye.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let t=GM(e,n),r,i;try{r=H(t),i=Qu(r).size}catch(t){let n=wc(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new M7(`symlink cycle at content path: ${e}`):t}if(!KM(r,n))throw new M7(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new M7(`document exceeds the open byte limit: ${e}`);try{return V(r,`utf-8`)}catch(e){if(wc(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let S=Ce.shouldUnloadDocument.bind(Ce);Ce.shouldUnloadDocument=e=>{if(Le.has(e)||Re&&S(e))return!0;let t=e.name;return oS(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:S(e)},Be=async e=>{Le.add(e);try{await Ce.unloadDocument(e)}finally{Le.delete(e)}},ke=new lS(Ce),je=new dD(Ce),Me=new pD(Ce),Te=new Pw(Ce,e.agentSessionOptions);let w=Te;ze.push(zC(()=>({active:w.liveSessionCount,limit:w.sessionLimit})));let T=c7({derivedDocumentIndex:_e,onDocumentSettled:e=>jt.current?.changed(e)});Ce.configuration.extensions.push(T);function E(e,t,n={}){b.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Ce.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=qZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==le)throw E(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:le}),new KZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${le}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await Ke();if(t!==null&&i!==t)throw E(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new KZ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(Ie&&n.principalId===Ie.id?a.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Ie.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Ce.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!nS(e.documentName)&&!rS(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!AB(r,t))throw E(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!MB(a,t))throw E(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let ee=R(n);function te(e){if(!LZ(e))return null;let t=R(ee,Qx(e));return WM(t,ee)?t:null}Ce.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await tMe(e.documentName,{recentlyRemovedDocs:At,resolveFilePath:te,fileExists:B})}}),Ce.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=qZ(e.token);dje(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ce.documents.get(e)})}}),Ce.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new q8(e.update);if(t.readVarString(),t.readVarUint()===i5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ar} rejected — server-only channel`)}});let ne=RZ({hocuspocus:Ce,durabilityState:x,ingressPolicy:t,sessionManager:Te,commentDocHooksRef:jt,contentDir:n,getGeneratedIndexSettingsStatus:Ct,setGeneratedIndexEnabled:wt,contentFilter:ge,serverInstanceId:le,getFileIndex:()=>Zt?Zt.getFileIndex():new Map,getAttachmentFolderPath:D,getAllFilesIndex:()=>Zt?Zt.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Zt?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?_t(e.docName):void 0;switch(Zt?.mutateFileIndex(e),e.kind){case`update`:t7(t,e.content,e.docName)&&pt(e.docName);break;case`create`:case`conflict`:pt(e.docName);break;case`delete`:ht(e.docName);break;case`rename`:ht(e.oldDocName),pt(e.newDocName);break;case`folder-create`:case`folder-delete`:mt(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:cz(e)}},getFolderIndex:()=>Zt?Zt.getFolderIndex():new Map,getAliasMap:()=>Zt?Zt.getAliasMap():new Map,getFolderAliasIndex:()=>Zt?Zt.getFolderAliasIndex():new Map,rescanFiles:()=>Zt?.rescanFromDisk(),enableTestRoutes:d,shadowRef:M,flushGitCommit:()=>ye.flushPendingGitCommit(),flushContributors:()=>ye.flushContributors(),getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ke?.getLatestDiskAckSVsAsBase64()??{},contentRoot:p,derivedDocumentIndex:_e,signalChannel:qe,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>$t,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:pe,getBridgeLossReporter:()=>Oe,getPrincipal:()=>Ie,acpRegistry:de,loadAcpCustomAgents:()=>vf(ue,P(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Be,ready:Ue,recentlyRemovedDocs:At,serializeDoc:Bt,evictManagedArtifactLkg:e=>{ye.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:N,getSemanticSimilarityFloor:()=>k().similarityFloor,getLinterBaseConfig:()=>O(),getLinksValidationSetting:()=>re(),getLinkPreviewsEnabled:A,getConfigDiagnostics:ie,embeddingsSecretsFile:Zj(u),readSemanticProviderConfig:k,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Ne=e}});Ce.configuration.extensions.push(ne),Ee=ne.nativeApi,De=ne.localApi;let ae=Ds({absPath:Us(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),oe=ae.value.bridge.deferGuard.enabled,j=ae.value.bridge.fixedPoint.enabled,fe=ae.value.bridge.preDrain.enabled;Se=ae.value.lossCapture.enabled?new ooe({projectDir:r,maxBytes:ae.value.lossCapture.maxBytes}):void 0,ae.value.bridge.lossDetector.enabled&&(Oe=Qse({shadow:()=>M.current,ring:Se,getBranch:()=>Qt?.getLastKnownBranch()??`main`,contentRoot:p??``}),Te.attachBridgeLossReporter(Oe)),Ce.configuration.extensions.push(z7({mdManager:Cs,schema:Ss,shadowRef:M,contentRoot:p,getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,resolveEmbed:pe,resolveSize:he,deferGuardEnabled:oe,lossDetectorEnabled:ae.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:j,preDrainEnabled:fe,lossRing:Se})),Ce.configuration.extensions.push(VMe()),Ce.configuration.extensions.push(UAe({getSyncEngine:()=>$t,projectDir:r,contentDir:n}))}catch(e){for(let e of ze.splice(0))e();throw Pe?.dispose(),Pe=null,Cc(ue),e}let Ft=null,It=new Map,Lt=[];function Rt(e,t){let n=R(e,`rescue`),r=R(n,Qx(t));return WM(r,n)?r:null}function Bt(e){let t=Ce.documents.get(e);return t?nz(t):null}let Vt=(e,t)=>$R(x,Ce,e,t,pe,he,Oe);function Ht(e){if(!vS(e)||$t?.getConflicts().some(t=>O5(t,e.name,r,n)))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ut=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Ce.documents){if(oS(n))continue;let r=Ce.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{GR(r,i,pe,n)},WR)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},Wt=null,Gt=e=>{e&&(Wt===null&&(Wt=new Set,setImmediate(()=>{let e=Wt;if(Wt=null,e)try{for(let t of e)Ut(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Wt.add(e))};function Kt(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 cz(e)}}async function qt(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await _e.recordDiskUpsert(e.docName,e.content),qe(`files`),pt(e.docName),Pt(e.docName);break;case`update`:{let{docName:t,content:n}=e;t7(e.previousIndexedFields,n,t)&&pt(t);let r=Ce.documents.get(t);if(!r){await _e.recordDiskUpsert(t,n);return}let i=C(t)??``,a=Bt(t)??i,o=YR({docName:t,base:i,ours:a,theirs:n}),s=hz(i).slice(0,6),c=hz(a).slice(0,6),l=hz(n).slice(0,6);switch(b.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:Ht(r),await _e.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{Vt(t,o.newContent),w(t,o.newContent),Yb(),Ht(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),Ht(r)}e&&await _e.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{Vt(t,o.newContent),w(t,n),Yb(),Ht(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),Ht(r)}e&&await _e.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{Vt(t,o.newContent),w(t,o.newContent),Yb(),Xb(),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await _e.recordDiskUpsert(t,n);break}case`refused`:{Xb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Ce.documents.get(t);if(!n){await _e.recordDiskDelete(t),qe(`files`),Nt(t),ht(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=Bt(t)??``,a=i!==r;if(a&&M.current){let e=M.current,n=Qt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Ix(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Qb(),b.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{b.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await _e.recordDiskDelete(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Ce.closeConnections(t),await Be(n),qe(`files`),Nt(t),ht(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=Ce.documents.get(t);if(T(t),w(n,r),await _e.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}b.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),qe(`files`),Mt(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),ht(t),pt(n);break}case`conflict`:{let{docName:t}=e,n=Ce.documents.get(t);if(!n)return;let r=Bt(t);r===null?b.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),b.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:fe.add(e.relativePath),qe(`files`),Gt(Cu(e.relativePath));break;case`asset-delete`:fe.remove(e.relativePath),qe(`files`),Gt(Cu(e.relativePath));break;case`folder-create`:case`folder-delete`:qe(`files`),mt(e.relativePath);break;case`file-create`:case`file-update`:await _e.recordFileTargetUpsert(e.relativePath),Ne?.(),qe(`files`);break;case`file-delete`:await _e.recordFileTargetDelete(e.relativePath),Ne?.(),qe(`files`);break;default:cz(e)}}catch(t){let n=Kt(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Jt=[];async function Yt(e){if(te()){Jt.push(e);return}await qt(e)}async function Xt(){let e=Jt.splice(0,Jt.length);for(let t of e)await qt(t)}let Zt=null,Qt=null,$t=null,en=null;async function tn(e){if(Ce.documents.size===0)return;let t=!1,n=new Promise(e=>{Ce.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Ce.documents.keys());Ce.closeConnections(),Ce.flushPendingStores();for(let e of Ce.documents.values())e.getConnectionsCount()===0&&Ce.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(Ce.documents.keys()),i=[],o=[];if(M.current){for(let e of n)if(!oS(e))try{let t=Bt(e);if(t===null){b.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Rt(M.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:M.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Hu(F(n),{recursive:!0}),ed(n,t,`utf-8`),Qb(),i.push(e),b.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),b.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else b.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function nn(){return en||(en=(async()=>{let e=Date.now(),t=[];Re=!0;try{await ft()}catch(e){b.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of ze.splice(0))e();try{await Pe?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Pe=null;try{Nc(ue)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}if(Dt!==null&&(clearTimeout(Dt),Dt=null),Ot)try{L7(r,At.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let n,i=await Promise.race([Ue.then(()=>`completed`,e=>(b.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{n=setTimeout(()=>e(`timeout`),5e3)})]);n!==void 0&&clearTimeout(n),i===`timeout`&&b.warn({},`[server] init did not complete within 5s during shutdown`);let a=Ce.documents.size;ve?.destroy();try{try{try{Ae&&=(clearTimeout(Ae),null),Qt&&=(await Qt.unsubscribe(),null),Zt&&=(await Zt.unsubscribe(),null);for(let{docName:e,cleanup:t}of Lt)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Lt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ke?.destroy(),Me?.destroy(),Ft&&=(await Ft.disconnect(),null);for(let[e,t]of It)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}It.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await Te.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await mce()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await tn(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-3 flush failed`)}_e.close();let e;try{await Promise.race([(async()=>{await ye.flushPendingGitCommit(),await ye.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{$t&&=(await $t.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(M.current){let e;try{await Promise.race([gx(M.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await mc({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&ed(R(M.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Mse(M.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let n=Date.now()-e;t.length===0?b.info({documentCount:a,durationMs:n},`[server] shutdown flushed ${a} documents in ${n}ms`):b.warn({documentCount:a,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{Cc(ue,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await ec()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),en)}let rn=[];async function an(){try{Ie=await N7(r),b.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!M.current)try{M.current=await Sx(r),b.info({gitDir:M.current.gitDir},`[server] history repo initialized at ${M.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),rn.push(`shadow-repo`)}if(M.current){let e=null;try{e=Hq(M.current.gitDir),dJ(M.current.gitDir,e),qq(M.current.gitDir,e),b.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){b.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([fJ(M.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){b.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ve?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(M.current)try{await bx(M.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){b.warn({},`[server] history repo appears corrupted — reinitializing`);try{M.current=await Sx(r)}catch(e){b.error({err:e},`[server] history repo reinit failed`),M.current=void 0,rn.includes(`shadow-repo`)||rn.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(M.current)try{let e=R(M.current.gitDir,`last-known-head`),t=null;try{t=V(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await mc({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await mc({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}b.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await Nx(M.current,p??``,t,n,e),Zb()}catch(e){b.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else b.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{ed(e,n,`utf-8`)}catch(e){b.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){b.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=Sq(n,r);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;b.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){b.error({err:e},`[server] managed rename recovery failed`),rn.push(`managed-rename-recovery`)}try{let e=phe(r);(e.deleted>0||e.errors>0)&&b.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){b.error({err:e},`[server] upload-tempfile sweep failed`),rn.push(`upload-tempfile-sweep`)}try{Ft=await Ce.openDirectConnection(Ar),ke?.emitServerInfo(le,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),rn.push(`cc1-push`)}let t=y?[]:tr;for(let e of t)try{let t=await Ce.openDirectConnection(e);It.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),rn.push(`config-doc:${e}`)}let i=new Map([[ln,Us(`project`,r)],[Mn,Us(`project-local`,r)],[pr,Us(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{b.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await _5(t,t=>{let n=Ce.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=D5(n??null,e,t,ye.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),ce(e)});Lt.push({docName:e,cleanup:n}),b.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){b.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),rn.push(`config-file-watcher:${e}`)}}if(!y){let e=(e,t)=>{let n=ZK(e,ye.managedArtifactCtx);if(!n)return;let r=nq(Ce.documents.get(n)??null,n,t,ye.managedArtifactCtx);b.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),qe(`files`),wo(n)&&_e.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=ZK(e,ye.managedArtifactCtx);qe(`files`),t&&wo(t)&&_e.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=KK(ye.managedArtifactCtx),r=await Bje(n,e,t);Lt.push({docName:`__skill-files__`,cleanup:r}),b.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),rn.push(`managed-artifact-watcher:skills`)}try{let e=R(UK(ye.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await _5(e,()=>{qe(`files`)});Lt.push({docName:`__skill-state__`,cleanup:t}),b.info({path:e},`[skill-state-watcher] started`)}catch(e){b.warn({err:e},`[skill-state-watcher] failed to start`),rn.push(`skill-state-watcher`)}}try{let e=R(n,`.okignore`),t=R(r,`.gitignore`),i=null;try{let e=xu(`git`,[`rev-parse`,`--git-common-dir`],YM({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=I(R(r,e.stdout.trim()),`info`,`exclude`);B(F(t))&&(i=t)}}catch{}let a=i?[e,t,i]:[e,t],o=b;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await PAe(a,(t,n)=>{(async()=>{if(t===e)try{let e=D5(Ce.documents.get(`__config__/okignore`)??null,zt,n,ye.configPersistenceCtx);o.info({docName:zt,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:L(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ge.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:L(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ke?.signal(`files`);else{let e=L(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ke?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:L(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Lt.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){b.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),rn.push(`ignore-files-watcher`)}let a=a7(r).branch??`main`;E(a),We();let o=_e.beginStartup(a),s=!1,c=performance.now();try{await Ms(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&rn.push(`backlink-index`);let i=0;for(let t of e)oS(t)||At.peek(t)?.kind!==`renamed`&&(At.setDeleted(t),i++);i>0&&b.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,l=ge?hL(n):new Set,d=e=>{e.some(e=>c.test(L(n,e).split(z).join(`/`)))&&(Ae&&clearTimeout(Ae),Ae=setTimeout(()=>{Ae=null;try{_X(r,n).then(e=>{e>0&&(b.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),ke?.signal(`files`))}).catch(e=>b.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=hL(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,ge.rebuildIgnorePatterns().then(t=>{t.ok?(b.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),ke?.signal(`files`)):b.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>b.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){b.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};Zt=await Ms(`ok.boot.seed-walk`,void 0,async()=>Zz(n,Yt,ge,{onRawBatch:d})),_X(r,n).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??nd();_X(e,e,pL(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] global copy re-sync failed`))}EL(`seedWalkMs`,Math.round(performance.now()-a));{let e=R(n),t=0;for(let[n]of At.entries()){if(!LZ(n))continue;let r=R(e,`${n}${Xx(n)}`);WM(r,e)&&B(r)&&(At.delete(n),t++)}t>0&&b.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await _e.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&rn.push(`tag-index`);let p=0;try{v===void 0?await VZ({contentDir:n,contentFilter:ge,basenameIndex:fe,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):gve({contentDir:n,basenameIndex:fe,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(b.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),rn.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),rn.push(`basename-index`)}})}catch(e){if(b.error({err:e},`[server] disk bridge watcher failed to start`),rn.push(`file-watcher`),!s){let e=await _e.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&rn.push(`tag-index`)}}finally{EL(`indexesMs`,Math.round(performance.now()-c)),Zt&&DL(`fileCount`,Zt.getFileIndex().size)}try{Qt=await gje(r,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),moe(),Ce.flushPendingStores(),await ye.flushPendingGitCommit(),ee(!0),M.current){let e=S(),t=a7(r).branch??e,n=[];for(let[e,t]of Ce.documents){if(oS(e))continue;let r=null;if(t.transact(()=>{r=Bt(e)},HMe),r===null)continue;let i=C(e)??r;n.push({docName:e,markdown:r,diskSnapshot:i})}if(n.length>0)try{let r=await Use(M.current,e,jx.id,n,t);r&&(_oe(),b.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){b.error({err:e},`[shadow] park failed`)}}},async e=>{let t=Jt.length,i=e.newBranch??`main`;if(b.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(ee(!1),await Xt(),e.headMoved&&e.newHead){let t=GMe(r,R(n),e.oldHead,e.newHead);if(t.size>0){Oue(t.keys());for(let[e,n]of t)Dj(e,Vte(n.email),n.name,n.email,qd(e));await ye.flushContributors()}}if(await ye.flushDeferredStores(`within-branch`),$t!==null)try{await $t.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{goe(),Jt.splice(0,Jt.length);let t=!1,r;try{E(i),r=await _e.beginBranchSwitch(i),ge.rebuildDirCount();try{let e=0;fe.clear(),await VZ({contentDir:n,contentFilter:ge,basenameIndex:fe,onSkip:(t,n,r)=>{e++,b.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(b.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),rn.includes(`basename-index-partial`)||rn.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of Ce.documents)if(!oS(e))try{let r=GM(e,n);if(!B(r)){let n=C(e)??``,r=Bt(e)??``;if(r!==n&&M.current){let t=M.current;queueMicrotask(()=>{Ix(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Qb(),b.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{b.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),b.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=V(r,`utf-8`);Vt(e,a),w(e,a),b.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){b.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}b.info({branch:i,docCount:Ce.documents.size},`[branch-switch] loaded branch ${i} (${Ce.documents.size} docs)`);try{await _e.settleBranchFromDisk(r)}catch(e){_e.abortBranchSwitch(r),b.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(M.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Ce.documents)if(!oS(t))try{let n=await Gse(M.current,i,jx.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=YR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:Vt(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:Vt(t,a.newContent),w(t,a.newContent),Xb(),e++;{let e=Ce.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){b.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&b.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&M.current)try{let t=bx(M.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await gx(M.current).withMutator(async()=>{for(let e of n.split(`
|
|
2014
|
-
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}ee(!1),await ye.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{_e.abortBranchSwitch(r),t||(ee(!1),await ye.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&M.current&&t>0){let t=p??`.`;try{let n=await Nx(M.current,t,e.oldHead,e.newHead,i);Zb(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),rn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=UM(L(n,I(r,t)));if(e.startsWith(`..`))continue;let i=Gx(e),a=Ce.documents.get(i);if(!a)continue;let o=Bt(i);o===null?b.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=UM(L(n,I(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Gx(e));i&&Ht(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=WMe(h),m=ne();m.mode!==`off`&&b.info({mode:m.mode,source:m.source},`[sync] mode active at boot`);try{$t=new zMe({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mode:m.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:f,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||ye.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=M.current;n&&await Fx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=M.current;n&&await Fx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ws({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:we(t.error),configPath:Us(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await $t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}qe(`files`),_e.announceReadyViews();let g=TL();g!==void 0&&EL(`readyMs`,g),ae()}return an().then(()=>{Ze=!0,Ve(),ut()},e=>{Qe=!0,$e.abort(),st({status:`failed`,indexCount:0}),_e.close(),We(),He(e)}),{hocuspocus:Ce,durabilityState:x,sessionManager:Te,nativeApi:Ee,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:ve,contentFilter:ge,basenameIndex:fe,serverInstanceId:le,destroy:nn,ready:Ue,generatedIndexSweepReady:ot,degraded:rn,lockDir:ue,get syncEngine(){return $t},getLinkPreviewsEnabled:A,resolveEmbed:pe,acpRegistry:de,acpPermissions:j}}function f9(e){return e/1048576}function KMe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:f9(e.rss),heapTotalMb:f9(e.heapTotal),heapUsedMb:f9(e.heapUsed),externalMb:f9(e.external),arrayBuffersMb:f9(e.arrayBuffers)}}}let p9=null,m9=null,h9=null;const g9=1e6;let _9=null,v9=null;js(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function qMe(){if(p9)return;let e=nc().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}=KMe();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`})}),p9=e}function JMe(){if(!m9){let e=nc().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(!_9){_9=xte({resolution:20}),_9.enable();return}e.observe(_9.percentile(50)/g9,{stat:`p50`}),e.observe(_9.percentile(99)/g9,{stat:`p99`}),_9.reset()}),m9=e}if(!h9){let e=nc().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=v9;if(v9={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`}))}),h9=e}}const y9=P(`skill-migrate`);function b9(e){return[{host:`agents`,root:Ue},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=oO.indexOf(e.host),r=oO.indexOf(t.host);return(n===-1?oO.length:n)-(r===-1?oO.length:r)||e.host.localeCompare(t.host)})}const YMe=b9(br),XMe=b9(ht);function ZMe(e,t){return B(R(e,Aa(t)))}function QMe(e,t){Ws(F(t),{recursive:!0});try{Ls(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;qs(e,t,{recursive:!0}),Js(e,{recursive:!0,force:!0})}}function $Me(e,t,n){let r=AI(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function x9(e,t){let n;try{n=H(R(e,`.ok`,`skills`))}catch{n=R(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!H(R(e,t.dir)).startsWith(n+z)}catch{return!0}}).map(e=>e.name))}async function S9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??YMe,a={migrated:[],skipped:[]};if(!B(n))return a;let o;try{o=qu(n)}catch{return a}let s=L(t,n).split(z).join(`/`),c=new Set;for(let[e,n]of Object.entries(mX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ji.test(e)||ZF.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=R(n,e);if(!B(I(o,`SKILL.md`)))continue;let s=YD(o)?.contentHash;if(s===void 0)continue;let l=H(o),u=i.map(({host:n,root:r})=>{let i=R(t,r);return{host:n,root:r,path:I(i,e),escapes:RI(t,i),state:$Me(I(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>ZMe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?Js(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&Js(d.path,{recursive:!0,force:!0}),QMe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(Js(e.path,{recursive:!0,force:!0}),qs(d.path,e.path,{recursive:!0}));await wN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),y9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),y9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const C9=P(`skill-reconcile`),eNe=ZF;function w9(){let e=[];for(let t of Tr){let n=br[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:Ue,editor:null}),e}function tNe(e,t){let n=L(e,R(t));return Eu(n)?R(t):n}function T9(e){let{frontmatter:t,body:n}=So(e),r={};if(t!==``)try{let e=(0,ck.parse)(hn(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function nNe(e,t){let n=T9(e),r=T9(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 E9(e,t){let n=D9(e),r=D9(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=I(e,o),c=I(t,o);if(i+=Qu(s).size+Qu(c).size,i>1048576)return!1;let l=V(s),u=V(c);if(!l.equals(u)&&(o!==`SKILL.md`||!nNe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of qu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(I(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){Js(t,{recursive:!0,force:!0}),Ws(e,{recursive:!0}),Bs(tNe(e,n),t,`dir`)}function k9(e,t){try{let n=Ju(e);return R(Eu(n)?n:R(F(e),n))===R(t)}catch{return!1}}function rNe(e,t){try{let n=Ju(e),r=Eu(n)?R(n):R(F(e),n);if(!B(r))return!1;let i=L(R(t),r);return i!==``&&(i.startsWith(`..`)||Eu(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const iNe=[...Tr,`agents`];function aNe(e){for(let t of iNe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function oNe(e){let{projectDir:t,skillsRoot:n}=e;if(!B(n))return;let r;try{r=qu(n)}catch{return}let i=w9();for(let e of r){let r=aNe(e);if(r===null)continue;let a=R(n,e),o=R(n,r);if(B(o))try{let n=Vu(a);if(n.isSymbolicLink()||!n.isDirectory()||!B(I(a,`SKILL.md`))||!B(I(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=R(t,n);if(RI(t,r))continue;let i=I(r,e);k9(i,a)&&O9(r,i,o)}Js(a,{recursive:!0,force:!0}),C9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){C9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function sNe(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 w9()){let o=R(t,e);if(!B(o)||RI(t,o))continue;let s;try{s=qu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(eNe.has(e))continue;let t=I(o,e),s=R(n,e),c=B(s);try{let l=Vu(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(rNe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(Js(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ji.test(e)){C9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&E9(t,s)){O9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){C9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=xN(t);for(let[r,a]of i){let i=R(n,r);if(!B(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await CN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??NI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{oNe({projectDir:t,skillsRoot:n})}catch(e){C9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let A9=null,j9=!1;function M9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function N9(e){if(!M9())return;let t=Bk(e);A9=new dc({currentPath:R(t,`tolerance-telemetry.jsonl`),previousPath:R(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ja(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};A9?.append(`${JSON.stringify(t)}\n`).catch(e=>{j9||(j9=!0,P(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){ja(null),await A9?.drain(),A9=null,j9=!1}bs();const cNe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],lNe=[`cache`,`tmp`];function uNe(e){let t=R(e,he);if(!(()=>{if(!B(t))return!0;try{return qu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of cNe)B(R(e,t))&&n.push(t);for(let t of lNe){let r=R(e,t);try{B(r)&&Qu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function dNe(e){let t=Nd(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 F9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function fNe(e){mhe();let t=e.projectDir??e.contentDir,n=Cve({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}`)}sc.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}tc({localSink:n?.telemetry}),N9(t),qMe(),JMe();let{kind:r,gitdir:i}=dNe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Ks(i));let o=xve(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ms(`ok.boot`,{attributes:a},async()=>pNe(e)),l=()=>{if(s)try{let e=vs.extract(xs.active(),{traceparent:s});return xs.with(e,c)}catch(e){P(`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 pNe(e){let t=e.skipAutoInit??!1,n=e.log??P(`boot`),r=e.serverRuntime??{...ba(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((Oo(r)||!Ya(i))&&!r.allowExternal)throw new EB(`refusing to start: the server would bind a non-loopback address (${(Ya(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=kB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrlSource!==`server`&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-CXt9yQWS.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=R(p,`.ok`);if(!B(R(m,`config.yml`)))throw new g8(B(m)?`config`:`okdir`,p);let h=R(m,`.gitignore`);B(h)||P(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??nK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof $G||e instanceof eK){let t=e instanceof eK?e.detected:``,r=e instanceof eK?`too_old`:`not_available`;xK(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ec(),await Promise.race([P9(),new Promise(e=>setTimeout(e,F9))]),e}let _=uNe(m);_.length>0&&P(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${he}/.`);let v=d9({contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,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,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te}=v,D=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ne=e.port??0,O=()=>r.externalUrlSource===`server`&&r.externalUrl!==void 0?r.externalUrl.replace(/\/+$/,``):`http://${D}:${ne}`,re=e.ephemeral?void 0:l8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>O(),localApi:v.localApi,log:n}),k=c();k.headersTimeout=3e4,k.requestTimeout=6e4;let A=e.serveContentAssets===!1?void 0:zZ({contentFilter:v.contentFilter,contentSirv:zc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ge,assetExtensions:w,blocklistExtensions:Ae,ingressPolicy:a}),ie=!1;if(e.reactShellDistDir)try{HX(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ie=!0}catch(e){if(e instanceof VX)n.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let ae=e.reactShellDistDir?zc(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new qE({contentDir:e.contentDir,localDir:C,globalDir:R(nd(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:T,agentPresenceBroadcaster:ee,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>O(),getMcpStdioCommand:()=>KE(e.localOpCliArgs,ne),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let ce=m8({httpServer:k,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:re,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:A,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;e.idleShutdownMs!==null&&(ue=$Z({httpServer:k,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],j=de[0],fe=async()=>{if(ie)try{GX(C)}catch(e){n.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},pe=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await pe(k,e.port??0,j??`127.0.0.1`)}catch(e){throw await fe(),e}let me=k.address(),_e=typeof me==`object`&&me?me.port:e.port??0,M=[];for(let e of de.slice(1)){let t=c();t.headersTimeout=k.headersTimeout,t.requestTimeout=k.requestTimeout;for(let e of k.listeners(`request`))t.on(`request`,e);for(let e of k.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,_e,e)}catch(t){n.error({err:t,failedAddress:e,port:_e,alreadyBound:M.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...M,k])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await fe(),t}M.push(t)}let ve=TL();ve!==void 0&&EL(`httpListenMs`,ve);let ye=k.address(),be=typeof ye==`object`&&ye?ye.port:e.port??0;ne=be;let xe=`http://${D}:${be}`;d(C,be,xe),ie&&UX(C,be,xe);let Se=!1,Ce=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${F9}ms`))},F9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(Se)return;Se=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await Ce(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C),ie&&G_e(C)}catch(e){n.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of M)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await t(`mount.shutdown`,()=>ce.shutdown()),re!==void 0&&await t(`mcpHttpHandler.close`,()=>re.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{k.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{k.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ie&&await t(`releaseUiLock`,async()=>GX(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ec()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>sc.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:R(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,fL(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=nd(),t=await S9({projectDir:e,skillsRoot:R(e,`.ok`,`skills`),hostRoots:XMe,inPlaceNames:x9(e,pL(e))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await sNe({projectDir:p,skillsRoot:R(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:k,destroy:le,lockDir:C,contentDir:e.contentDir,port:be,ready:x,generatedIndexSweepReady:v.generatedIndexSweepReady,degraded:S,didAutoInit:f,serverInstance:v,runtime:jke(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function I9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new XZ(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=Pd(n),t=e?I(e,`MERGE_HEAD`):null;if(!t||!B(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=gc({baseDir:n,timeout:{block:5e3}});s=new Set(await Jb(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=Gx(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const mNe=Ne;function hNe(e={}){let t=e.home??nd(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?B(I(t,`Library`,`Application Support`,`Claude`)):n===`win32`?B(I(r.APPDATA??I(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(uc(),1);const R9=I(nd(),`.ok`,`logs`),gNe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function _Ne(){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 vNe(e){Hu(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function yNe(e){try{if(Qu(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{Yu(n,r)}catch{}}try{$u(`${e}.3`)}catch{}}function bNe(e){try{let t=Date.now(),n=10080*60*1e3,r=qu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Qu(I(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{$u(I(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{$u(I(e,t.name)),a-=t.size}catch{}}}catch{}}function xNe(e){vNe(R9);let t=z9(),n=e.filePath??I(R9,`${e.name}.${t}.log`);yNe(n),(e._setTimeout??setTimeout)(()=>bNe(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:_Ne(),name:e.name,redact:{paths:gNe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:L9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function SNe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[L9.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 CNe(e){return I(R9,`${e}.${z9()}.log`)}function wNe(){return R9}function TNe(e){let t=R(e),n=0;for(;n<30;){let e=!1;try{e=B(R(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=F(t);if(r===t)return null;t=r,n+=1}return null}const B9=Sd(vu),V9=P(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ENe(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],YM({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function DNe(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],YM({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return V9.warn({path:t,stderr:U9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function ONe(e){let t=R(e,`packed-refs`);if(B(t))try{if(V(t,`utf-8`).split(`
|
|
2014
|
+
`))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}ee(!1),await ye.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{_e.abortBranchSwitch(r),t||(ee(!1),await ye.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&M.current&&t>0){let t=p??`.`;try{let n=await Nx(M.current,t,e.oldHead,e.newHead,i);Zb(),b.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),rn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=UM(L(n,I(r,t)));if(e.startsWith(`..`))continue;let i=Gx(e),a=Ce.documents.get(i);if(!a)continue;let o=Bt(i);o===null?b.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=UM(L(n,I(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Gx(e));i&&Ht(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=WMe(h),m=ne();m.mode!==`off`&&b.info({mode:m.mode,source:m.source},`[sync] mode active at boot`);try{$t=new zMe({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mode:m.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:f,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||ye.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=M.current;n&&await Fx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=M.current;n&&await Fx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ws({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:we(t.error),configPath:Us(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await $t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}qe(`files`),_e.announceReadyViews();let g=TL();g!==void 0&&EL(`readyMs`,g),ae()}return an().then(()=>{Ze=!0,Ve(),ut()},e=>{Qe=!0,$e.abort(),st({status:`failed`,indexCount:0}),_e.close(),We(),He(e)}),{hocuspocus:Ce,durabilityState:x,sessionManager:Te,nativeApi:Ee,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:ve,contentFilter:ge,basenameIndex:fe,serverInstanceId:le,destroy:nn,ready:Ue,generatedIndexSweepReady:ot,degraded:rn,lockDir:ue,get syncEngine(){return $t},getLinkPreviewsEnabled:A,resolveEmbed:pe,acpRegistry:de,acpPermissions:j}}function f9(e){return e/1048576}function KMe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:f9(e.rss),heapTotalMb:f9(e.heapTotal),heapUsedMb:f9(e.heapUsed),externalMb:f9(e.external),arrayBuffersMb:f9(e.arrayBuffers)}}}let p9=null,m9=null,h9=null;const g9=1e6;let _9=null,v9=null;js(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function qMe(){if(p9)return;let e=nc().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}=KMe();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`})}),p9=e}function JMe(){if(!m9){let e=nc().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(!_9){_9=xte({resolution:20}),_9.enable();return}e.observe(_9.percentile(50)/g9,{stat:`p50`}),e.observe(_9.percentile(99)/g9,{stat:`p99`}),_9.reset()}),m9=e}if(!h9){let e=nc().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=v9;if(v9={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`}))}),h9=e}}const y9=P(`skill-migrate`);function b9(e){return[{host:`agents`,root:Ue},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=oO.indexOf(e.host),r=oO.indexOf(t.host);return(n===-1?oO.length:n)-(r===-1?oO.length:r)||e.host.localeCompare(t.host)})}const YMe=b9(br),XMe=b9(ht);function ZMe(e,t){return B(R(e,Aa(t)))}function QMe(e,t){Ws(F(t),{recursive:!0});try{Ls(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;qs(e,t,{recursive:!0}),Js(e,{recursive:!0,force:!0})}}function $Me(e,t,n){let r=AI(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function x9(e,t){let n;try{n=H(R(e,`.ok`,`skills`))}catch{n=R(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!H(R(e,t.dir)).startsWith(n+z)}catch{return!0}}).map(e=>e.name))}async function S9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??YMe,a={migrated:[],skipped:[]};if(!B(n))return a;let o;try{o=qu(n)}catch{return a}let s=L(t,n).split(z).join(`/`),c=new Set;for(let[e,n]of Object.entries(mX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ji.test(e)||ZF.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=R(n,e);if(!B(I(o,`SKILL.md`)))continue;let s=YD(o)?.contentHash;if(s===void 0)continue;let l=H(o),u=i.map(({host:n,root:r})=>{let i=R(t,r);return{host:n,root:r,path:I(i,e),escapes:RI(t,i),state:$Me(I(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>ZMe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?Js(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&Js(d.path,{recursive:!0,force:!0}),QMe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(Js(e.path,{recursive:!0,force:!0}),qs(d.path,e.path,{recursive:!0}));await wN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),y9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),y9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const C9=P(`skill-reconcile`),eNe=ZF;function w9(){let e=[];for(let t of Tr){let n=br[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:Ue,editor:null}),e}function tNe(e,t){let n=L(e,R(t));return Eu(n)?R(t):n}function T9(e){let{frontmatter:t,body:n}=So(e),r={};if(t!==``)try{let e=(0,ck.parse)(hn(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function nNe(e,t){let n=T9(e),r=T9(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 E9(e,t){let n=D9(e),r=D9(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=I(e,o),c=I(t,o);if(i+=Qu(s).size+Qu(c).size,i>1048576)return!1;let l=V(s),u=V(c);if(!l.equals(u)&&(o!==`SKILL.md`||!nNe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of qu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(I(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){Js(t,{recursive:!0,force:!0}),Ws(e,{recursive:!0}),Bs(tNe(e,n),t,`dir`)}function k9(e,t){try{let n=Ju(e);return R(Eu(n)?n:R(F(e),n))===R(t)}catch{return!1}}function rNe(e,t){try{let n=Ju(e),r=Eu(n)?R(n):R(F(e),n);if(!B(r))return!1;let i=L(R(t),r);return i!==``&&(i.startsWith(`..`)||Eu(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const iNe=[...Tr,`agents`];function aNe(e){for(let t of iNe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function oNe(e){let{projectDir:t,skillsRoot:n}=e;if(!B(n))return;let r;try{r=qu(n)}catch{return}let i=w9();for(let e of r){let r=aNe(e);if(r===null)continue;let a=R(n,e),o=R(n,r);if(B(o))try{let n=Vu(a);if(n.isSymbolicLink()||!n.isDirectory()||!B(I(a,`SKILL.md`))||!B(I(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=R(t,n);if(RI(t,r))continue;let i=I(r,e);k9(i,a)&&O9(r,i,o)}Js(a,{recursive:!0,force:!0}),C9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){C9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function sNe(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 w9()){let o=R(t,e);if(!B(o)||RI(t,o))continue;let s;try{s=qu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(eNe.has(e))continue;let t=I(o,e),s=R(n,e),c=B(s);try{let l=Vu(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(rNe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(Js(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ji.test(e)){C9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&E9(t,s)){O9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){C9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=xN(t);for(let[r,a]of i){let i=R(n,r);if(!B(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await CN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??NI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{oNe({projectDir:t,skillsRoot:n})}catch(e){C9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let A9=null,j9=!1;function M9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function N9(e){if(!M9())return;let t=Bk(e);A9=new dc({currentPath:R(t,`tolerance-telemetry.jsonl`),previousPath:R(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ja(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};A9?.append(`${JSON.stringify(t)}\n`).catch(e=>{j9||(j9=!0,P(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){ja(null),await A9?.drain(),A9=null,j9=!1}bs();const cNe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],lNe=[`cache`,`tmp`];function uNe(e){let t=R(e,he);if(!(()=>{if(!B(t))return!0;try{return qu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of cNe)B(R(e,t))&&n.push(t);for(let t of lNe){let r=R(e,t);try{B(r)&&Qu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function dNe(e){let t=Nd(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 F9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function fNe(e){mhe();let t=e.projectDir??e.contentDir,n=Cve({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}`)}sc.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}tc({localSink:n?.telemetry}),N9(t),qMe(),JMe();let{kind:r,gitdir:i}=dNe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Ks(i));let o=xve(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ms(`ok.boot`,{attributes:a},async()=>pNe(e)),l=()=>{if(s)try{let e=vs.extract(xs.active(),{traceparent:s});return xs.with(e,c)}catch(e){P(`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 pNe(e){let t=e.skipAutoInit??!1,n=e.log??P(`boot`),r=e.serverRuntime??{...ba(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((Oo(r)||!Ya(i))&&!r.allowExternal)throw new EB(`refusing to start: the server would bind a non-loopback address (${(Ya(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=kB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrlSource!==`server`&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-BJIPnZ6Y.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=R(p,`.ok`);if(!B(R(m,`config.yml`)))throw new g8(B(m)?`config`:`okdir`,p);let h=R(m,`.gitignore`);B(h)||P(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??nK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof $G||e instanceof eK){let t=e instanceof eK?e.detected:``,r=e instanceof eK?`too_old`:`not_available`;xK(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ec(),await Promise.race([P9(),new Promise(e=>setTimeout(e,F9))]),e}let _=uNe(m);_.length>0&&P(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${he}/.`);let v=d9({contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,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,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te}=v,D=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ne=e.port??0,O=()=>r.externalUrlSource===`server`&&r.externalUrl!==void 0?r.externalUrl.replace(/\/+$/,``):`http://${D}:${ne}`,re=e.ephemeral?void 0:l8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>O(),localApi:v.localApi,log:n}),k=c();k.headersTimeout=3e4,k.requestTimeout=6e4;let A=e.serveContentAssets===!1?void 0:zZ({contentFilter:v.contentFilter,contentSirv:zc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ge,assetExtensions:w,blocklistExtensions:Ae,ingressPolicy:a}),ie=!1;if(e.reactShellDistDir)try{HX(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ie=!0}catch(e){if(e instanceof VX)n.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let ae=e.reactShellDistDir?zc(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new qE({contentDir:e.contentDir,localDir:C,globalDir:R(nd(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:T,agentPresenceBroadcaster:ee,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>O(),getMcpStdioCommand:()=>KE(e.localOpCliArgs,ne),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let ce=m8({httpServer:k,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:re,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:A,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;e.idleShutdownMs!==null&&(ue=$Z({httpServer:k,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],j=de[0],fe=async()=>{if(ie)try{GX(C)}catch(e){n.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},pe=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await pe(k,e.port??0,j??`127.0.0.1`)}catch(e){throw await fe(),e}let me=k.address(),_e=typeof me==`object`&&me?me.port:e.port??0,M=[];for(let e of de.slice(1)){let t=c();t.headersTimeout=k.headersTimeout,t.requestTimeout=k.requestTimeout;for(let e of k.listeners(`request`))t.on(`request`,e);for(let e of k.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,_e,e)}catch(t){n.error({err:t,failedAddress:e,port:_e,alreadyBound:M.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...M,k])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await fe(),t}M.push(t)}let ve=TL();ve!==void 0&&EL(`httpListenMs`,ve);let ye=k.address(),be=typeof ye==`object`&&ye?ye.port:e.port??0;ne=be;let xe=`http://${D}:${be}`;d(C,be,xe),ie&&UX(C,be,xe);let Se=!1,Ce=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${F9}ms`))},F9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(Se)return;Se=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await Ce(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C),ie&&G_e(C)}catch(e){n.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of M)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await t(`mount.shutdown`,()=>ce.shutdown()),re!==void 0&&await t(`mcpHttpHandler.close`,()=>re.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{k.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{k.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ie&&await t(`releaseUiLock`,async()=>GX(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ec()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>sc.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:R(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,fL(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=nd(),t=await S9({projectDir:e,skillsRoot:R(e,`.ok`,`skills`),hostRoots:XMe,inPlaceNames:x9(e,pL(e))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await sNe({projectDir:p,skillsRoot:R(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:k,destroy:le,lockDir:C,contentDir:e.contentDir,port:be,ready:x,generatedIndexSweepReady:v.generatedIndexSweepReady,degraded:S,didAutoInit:f,serverInstance:v,runtime:jke(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function I9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new XZ(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=Pd(n),t=e?I(e,`MERGE_HEAD`):null;if(!t||!B(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=gc({baseDir:n,timeout:{block:5e3}});s=new Set(await Jb(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=Gx(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const mNe=Ne;function hNe(e={}){let t=e.home??nd(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?B(I(t,`Library`,`Application Support`,`Claude`)):n===`win32`?B(I(r.APPDATA??I(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(uc(),1);const R9=I(nd(),`.ok`,`logs`),gNe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function _Ne(){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 vNe(e){Hu(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function yNe(e){try{if(Qu(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{Yu(n,r)}catch{}}try{$u(`${e}.3`)}catch{}}function bNe(e){try{let t=Date.now(),n=10080*60*1e3,r=qu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Qu(I(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{$u(I(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{$u(I(e,t.name)),a-=t.size}catch{}}}catch{}}function xNe(e){vNe(R9);let t=z9(),n=e.filePath??I(R9,`${e.name}.${t}.log`);yNe(n),(e._setTimeout??setTimeout)(()=>bNe(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:_Ne(),name:e.name,redact:{paths:gNe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:L9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function SNe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[L9.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 CNe(e){return I(R9,`${e}.${z9()}.log`)}function wNe(){return R9}function TNe(e){let t=R(e),n=0;for(;n<30;){let e=!1;try{e=B(R(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=F(t);if(r===t)return null;t=r,n+=1}return null}const B9=Sd(vu),V9=P(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ENe(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],YM({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function DNe(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],YM({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return V9.warn({path:t,stderr:U9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function ONe(e){let t=R(e,`packed-refs`);if(B(t))try{if(V(t,`utf-8`).split(`
|
|
2015
2015
|
`).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return qu(R(e,`refs/heads`)).length>0}catch{return!1}}function U9(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function W9(e,t){if(await DNe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await ENe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await B9(e,i,YM({cwd:t,encoding:`utf-8`})),r||V9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){V9.warn({path:t,stderr:U9(e)},`could not create initial commit`)}}async function kNe(e,t){try{let{stdout:n}=await B9(e,[`rev-parse`,`--is-inside-work-tree`],YM({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function ANe(e){let t=R(e),n=R(t,`.git`),r=R(n,`HEAD`),i=!1,a=!1;if(B(n)){if(!Qu(n).isDirectory())return{didInit:!1};if(B(r)){if(ONe(n))return{didInit:!1};a=!0}else V9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=nK()}catch(e){throw e instanceof $G||e instanceof eK?(xK(e),V9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof eK?`too_old`:`not_available`,detectedVersion:e instanceof eK?e.detected:``},e instanceof eK?`git binary too old`:`git binary not found`)):V9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await W9(s,t),{didInit:!1};if(!i&&await kNe(s,t))return{didInit:!1};let c=``;try{c=(await B9(s,[`init`,`--initial-branch=main`,t],YM({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new H9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!B(r))throw new H9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await W9(s,t),i?(V9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(V9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=P(`project-skill-git`),K9=/^[0-9a-f]{40}$/,jNe=jt.map(e=>e.replace(/\/$/,``));async function MNe(e){let t=Pd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(INe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=_c(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await hc(async()=>{let t=await NNe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await PNe(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=_c(e,{gitIndexFile:I(ad(),`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 FNe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await gB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;yc(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 \`${Ct}\` 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 jNe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function NNe(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 PNe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function FNe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function INe(e){return B(I(e,`MERGE_HEAD`))||B(I(e,`rebase-merge`))||B(I(e,`rebase-apply`))||B(I(e,`CHERRY_PICK_HEAD`))||B(I(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function LNe(e,t){let n;try{n=_u(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=F(n),r=0;r<32;r+=1){let n=I(t,`package.json`);if(B(n))try{let t=JSON.parse(await ld(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=F(t);if(r===t)return;t=r}}const RNe=[{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 RNe)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 zNe(e){if(!Ux(e))throw new $9(e);let t;try{t=H(R(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Qu(t).isFile())throw new Q9(e);let n=F(t),r=eB(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Gx(L(BNe(e),t).split(z).join(`/`)),canonicalFilePath:t}}let i=Cu(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Gx(i)}}function BNe(e){return R(e,Ds({absPath:Us(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function VNe(e){let t=Uu(R(ad(),`ok-ephemeral-`)),n=R(t,`.ok`);return Hu(n,{recursive:!0}),ed(R(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),ed(R(n,`.gitignore`),`local/
|
|
2016
2016
|
`,`utf-8`),t}export{g2 as $,Nx as $i,WR as $n,jM as $r,IJ as $t,G7 as A,hw as Ai,bB as An,zP as Ar,IZ as At,a7 as B,K as Bi,jz as Bn,Kfe as Br,BJ as Bt,d9 as C,Ld as Ca,dD as Ci,EB as Cn,XF as Cr,VZ as Ct,K7 as D,KE as Di,MB as Dn,QP as Dr,tve as Dt,U7 as E,Dd as Ea,RE as Ei,wB as En,RF as Er,iZ as Et,Fje as F,xw as Fi,cz as Fn,jP as Fr,GX as Ft,p8 as G,rS as Gi,Mz as Gn,sN as Gr,GJ as Gt,h8 as H,lS as Hi,pz as Hn,jfe as Hr,Ohe as Ht,g7 as I,UC as Ii,Pz as In,kP as Ir,UX as It,o8 as J,Rx as Ji,ez as Jn,tN as Jr,JJ as Jt,d8 as K,oS as Ki,dz as Kn,aN as Kr,khe as Kt,h7 as L,WC as Li,hz as Ln,qfe as Lr,Lhe as Lt,N7 as M,Pw as Mi,vB as Mn,Qfe as Mr,VX as Mt,A7 as N,kw as Ni,eB as Nn,AP as Nr,HX as Nt,V7 as O,Fw as Oi,NB as On,LP as Or,nve as Ot,m7 as P,Aw as Pi,$z as Pn,MP as Pr,WX as Pt,d2 as Q,Ex as Qi,JR as Qn,GM as Qr,FJ as Qt,Cje as R,pw as Ri,mz as Rn,OP as Rr,tY as Rt,P9 as S,Rd as Sa,pD as Si,AW as Sn,eI as Sr,qZ as St,B7 as T,Fd as Ta,qE as Ti,LB as Tn,vme as Tr,aZ as Tt,g8 as U,nS as Ui,Nz as Un,iN as Ur,XJ as Ut,n7 as V,gS as Vi,Ez as Vn,tP as Vr,Ahe as Vt,m8 as W,sS as Wi,Zz as Wn,rN as Wr,WJ as Wt,l2 as X,Ax as Xi,qR as Xn,$M as Xr,YJ as Xt,X6 as Y,kx as Yi,KR as Yn,XM as Yr,qJ as Yt,u2 as Z,jx as Zi,YR as Zn,YM as Zr,KJ as Zt,mNe as _,ph as _a,Oj as _i,OW as _n,lI as _r,KZ as _t,zNe as a,Fx as aa,ade as ai,eK as an,Ime as ar,Yxe as at,N9 as b,vf as ba,Vk as bi,kW as bn,oI as br,WZ as bt,MNe as c,bx as ca,Yue as ci,yK as cn,bI as cr,p0 as ct,TNe as d,lx as da,jue as di,iK as dn,vI as dr,pye as dt,wx as ea,AM as ei,TK as en,FR as er,sSe as et,xNe as f,nx as fa,jj as fi,JG as fn,_I as fr,I$ as ft,hNe as g,mh as ga,kj as gi,DW as gn,cI as gr,UZ as gt,wNe as h,fh as ha,Dj as hi,yW as hn,uI as hr,JZ as ht,VNe as i,Lx as ia,cde as ii,$G as in,OI as ir,Jxe as it,z7 as j,jw as ji,yB as jn,IP as jr,cZ as jt,W7 as k,Lw as ki,AB as kn,RP as kr,RZ as kt,H9 as l,px as la,zj as li,tK as ln,xI as lr,U$ as lt,CNe as m,kie as ma,Aj as mi,WG as mn,yI as mr,$Z as mt,Z9 as n,zx as na,$j as ni,bK as nn,dR as nr,n2 as nt,X9 as o,Ix as oa,sde as oi,ZG as on,TI as or,Xxe as ot,SNe as p,Tse as pa,kue as pi,qG as pn,wme as pr,z$ as pt,l8 as q,tS as qi,$R as qn,oN as qr,ZJ as qt,$9 as r,Sx as ra,Xj as ri,xK as rn,kI as rr,Z0 as rt,LNe as s,Bx as sa,ode as si,nK as sn,CI as sr,G0 as st,Q9 as t,Ox as ta,eM as ti,CK as tn,bR as tr,r2 as tt,ANe as u,dx as ua,Kj as ui,cK as un,SI as ur,x$ as ut,fNe as v,_f as va,Bk as vi,CW as vn,sI as vr,HZ as vt,u9 as w,rf as wa,lD as wi,kB as wn,tI as wr,zZ as wt,M9 as x,sf as xa,ek as xi,xW as xn,$F as xr,_ve as xt,I9 as y,cf as ya,zk as yi,MW as yn,iI as yr,GZ as yt,c7 as z,_S as zi,Fz as zn,DP as zr,$J as zt};
|
|
2017
|
-
//# sourceMappingURL=src-
|
|
2017
|
+
//# sourceMappingURL=src-Dhqa-DT-.mjs.map
|