openpond 0.2.56 → 0.2.57
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/app-server.js +1 -1
- package/dist/chunks/{app-server-runtime-DVKOZ5B6.js → app-server-runtime-VCRNCNX2.js} +1 -1
- package/dist/chunks/chunk-6FDWRG55.js +2 -0
- package/dist/chunks/{chunk-YCJO3YVD.js → chunk-MULXCKG7.js} +1 -1
- package/dist/chunks/host-profile-evaluation-tools-NRLXL2S5.js +2 -0
- package/dist/chunks/{hosted-app-server-composition-BCOO5ANF.js → hosted-app-server-composition-HPL3CRXN.js} +1 -1
- package/dist/chunks/{src-CJM6HY5Y.js → src-INHPJ63Z.js} +2 -2
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/chunk-UHFZHBGW.js +0 -2
- package/dist/chunks/host-profile-evaluation-tools-JJQWJUBT.js +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
3
|
-
import{a as BL,b as $L,c as NL}from"./chunk-2D4Y3HNW.js";import{a as cL,b as dL,c as Yh,d as lL,e as Ja,f as $e,g as uL,h as Ie,i as pL,j as mL,k as fL,l as hL,m as gL,n as wL,o as yL,p as vL,q as bL,r as kL,s as IL,t as nn,u as on,v as xe,w as SL}from"./chunk-Z54O534A.js";import{a as Bb,b as $m,c as PL,d as RL}from"./chunk-F4KOGISR.js";import{a as xL,b as _L}from"./chunk-KUERKVEU.js";import{a as TL,b as EL,c as AL}from"./chunk-QEFHOJFE.js";import{a as Xh,b as CL}from"./chunk-74IIXVAE.js";import{a as jL,b as OL,c as HL,d as j,e as DL,f as Ka,g as V,h as Qh,j as LL}from"./chunk-S5ESN275.js";import"./chunk-DUURYZOI.js";import{a as Jh,b as FD,c as zD,d as WD,e as VD}from"./chunk-QHWGQ3A4.js";import"./chunk-SH5CBAFC.js";import{b as JD}from"./chunk-SWUEFLOH.js";import{a as KD,b as Kh,c as YD,d as XD,e as QD}from"./chunk-XXYGGNVM.js";import{b as ZD}from"./chunk-PUZQU66L.js";import{a as eL,b as tL,c as hI,d as rL,e as nL,f as oL,g as aL,h as iL,j as sL}from"./chunk-WMKYHXVM.js";import{a as DO,b as j1,c as O1,d as H1,e as mH,f as fH,g as hH,h as gH,i as wH,j as yH}from"./chunk-YOBN7KTF.js";import{A as tI,c as gh,d as uo,e as VO,f as zo,g as yh,h as KO,i as Na,j as vh,k as YO,o as XO,q as Ih,r as Sh,s as Ua,t as t1,u as P1,v as R1,w as x1,x as _1,z as T1}from"./chunk-7HPDGZOR.js";import{c as eI}from"./chunk-PPAPVGJP.js";import{a as qt,b as mu,c as Go,d as Dh,e as Lh,f as Va}from"./chunk-HZEIRHEB.js";import{b as Vh,d as Jc,l as HD,n as Gh}from"./chunk-G3RXYI2L.js";import{b as qD}from"./chunk-UHFZHBGW.js";import{b as vH,c as nI}from"./chunk-PF5R6CMP.js";import"./chunk-DMVD2RFZ.js";import"./chunk-JYKRR7E5.js";import{a as GD}from"./chunk-OIUTWU6K.js";import"./chunk-X4OSOOSU.js";import"./chunk-3K4VVB7S.js";import{a as dH,b as lH,c as uH}from"./chunk-ZUJ3XUCP.js";import{a as QO,b as ZO,c as bh,d as kh}from"./chunk-XVDFJ3ZF.js";import{a as ee}from"./chunk-EQFGBL3O.js";import{d as e1}from"./chunk-GZ7M5XBP.js";import{a as Vo,b as rH,c as nH}from"./chunk-OUVIWDL2.js";import"./chunk-W45RKGM6.js";import"./chunk-GLDYJM7O.js";import{b as GO,c as JO,d as Lc,f as wh,g as cu}from"./chunk-HCYX6RHP.js";import{a as eH,b as tH}from"./chunk-YOQRYNLP.js";import{a as K1,c as Y1,d as X1,e as Q1,f as Wo,g as Z1,h as Hh,k as uu}from"./chunk-YY7LEQGP.js";import{a as YC,d as XC,e as Wi,h as AO}from"./chunk-3Z47M3YY.js";import{a as An}from"./chunk-ABD5M2D2.js";import{d as Nf}from"./chunk-TRQQNFMO.js";import{a as KC}from"./chunk-FEAKTSRS.js";import{a as En,b as Uf,c as Ck,d as QC}from"./chunk-OSIO7PLX.js";import"./chunk-F74GBN6K.js";import{a as Wf}from"./chunk-SDAUS5PY.js";import{a as aM}from"./chunk-I2NXNMRZ.js";import{a as Ff,d as zf,e as nM,f as oM,i as Xl,j as zi}from"./chunk-O72BSKSO.js";import{a as ph,b as jO,c as Wk}from"./chunk-OPNRWESL.js";import{b as CO,c as MO}from"./chunk-2QUCCP6Z.js";import{c as OO,d as mh,i as HO}from"./chunk-FY5KHLMW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-XEOEKFG6.js";import{b as Nm,e as sE,f as cE,g as dE,l as hc,m as lE,n as uE,p as pE,q as Um,r as qm}from"./chunk-HY3GOBFJ.js";import{a as K0,d as Y0,f as pC}from"./chunk-DBK66CJP.js";import{a as bH,b as iY,c as SH,d as PH,e as LH,f as BH,g as $H,h as NH,i as UH,j as cD,k as LD,m as ML}from"./chunk-YCJO3YVD.js";import{b as qH,c as zc,d as Wc,e as cI}from"./chunk-D74JEERO.js";import{a as tt,b as kH,c as IH,d as dI,e as KH,f as qh,g as Fh,h as YH}from"./chunk-JDEEWOD7.js";import{$ as jD,A as uD,B as pD,C as mD,D as fD,E as hD,F as gD,G as uI,H as wD,I as ID,J as SD,K as Zi,L as xD,M as Br,N as zh,O as es,P as jn,Q as On,R as _D,S as TD,T as ED,U as Hn,V as AD,W as Wh,X as CD,Y as MD,Z as ir,_ as ts,aa as Jo,b as RH,ba as pI,c as jH,ca as mI,d as OH,da as Gc,e as DH,ea as fI,f as FH,fa as OD,g as Vc,ga as DD,h as zH,ha as BD,i as WH,j as VH,k as XH,l as QH,m as ZH,n as eD,o as tD,p as rD,q as lI,r as nD,s as oD,t as aD,u as iD,x as sD,y as dD,z as lD}from"./chunk-OGDADQGH.js";import{a as HH}from"./chunk-4NESNOK5.js";import{a as xH,b as Bh,c as $h,d as Nh,e as _H,f as TH,g as EH,h as AH,i as oI,j as Qi,k as aI,l as fu,m as hu,n as Fc,o as Uh,p as iI,q as gu,r as ho,s as CH,t as de,u as MH,v as sI}from"./chunk-BLXEAZCQ.js";import{a as RD}from"./chunk-UCPGRPWY.js";import{a as $D,b as ND,c as UD}from"./chunk-L6K7ERG5.js";import{a as pH}from"./chunk-J2TWKFML.js";import{b as Ah}from"./chunk-773TH7FN.js";import{b as E1,c as A1,d as C1,e as M1}from"./chunk-HDL5YSAA.js";import{H as Qk,I as Zk,M as S1,a as r1,h as i1,i as s1,j as Vk,u as I1,y as Eh}from"./chunk-ZFSHBFG5.js";import{a as k1}from"./chunk-AN525SPP.js";import"./chunk-SYUKES6H.js";import{b as D1}from"./chunk-HIOKCIL7.js";import{a as GH,b as JH}from"./chunk-GW766ZSO.js";import{a as wr,b as LO,c as Mn,d as BO,e as fh,f as hh,h as $O,i as $a,k as NO,l as UO,m as qO,n as FO,o as zO,p as WO}from"./chunk-UKMA4R6X.js";import"./chunk-OQKJGTTO.js";import{a as qa}from"./chunk-KVTBX2UP.js";import{a as n1}from"./chunk-IZ6DLEVY.js";import{b as PD}from"./chunk-A6USMRWK.js";import{a as yD,b as wu,c as vD,d as bD,e as kD,f as Ga}from"./chunk-PCSIOUHF.js";import{a as Dc}from"./chunk-7KWD2I6W.js";import{b as oH,c as aH,d as iH,e as sH,f as cH,g as pu,h as Wa}from"./chunk-GPVCOEUH.js";import"./chunk-OLLLZVHF.js";import"./chunk-7PXZ4X4P.js";import"./chunk-N73MU2C3.js";import{a as Th,b as po,c as f1,d as Kk,e as h1,f as Yk,i as g1,j as Xk,k as w1,l as y1,m as v1,n as b1,o as Nc}from"./chunk-ZGTOK7ZK.js";import{A as m1,C as _h,b as Rh,d as c1,e as d1,h as l1,k as Gk,l as Jk,m as $c,n as u1,p as xh,q as p1,s as du}from"./chunk-XW6HGSIT.js";import{a as o1,b as Ph,d as he,e as _t,f as Bc,g as se,i as a1}from"./chunk-KG325WTN.js";import{A as Oh,B as J1,C as qc,d as Ch,e as Mh,f as L1,g as B1,i as $1,j as N1,k as U1,l as q1,m as Fa,n as lu,o as F1,p as z1,q as Uc,r as rI,s as W1,t as za,u as V1,v as Xi,y as jh,z as G1}from"./chunk-3RCRSMWZ.js";import"./chunk-UGL7WF3W.js";import"./chunk-DMFUEUAZ.js";import{a as mo,b as fo,c as ar}from"./chunk-PSGGOZFM.js";import{a as ZC,b as eM,c as tM,d as qf,e as rM}from"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import{b as oE,g as JC}from"./chunk-VRIEKBBH.js";import{b as WC,i as VC,j as GC,m as _c,n as Ak}from"./chunk-QNG27G3T.js";import{A as UC,C as qC,D as FC,E as Tn,d as xC,e as _C,f as TC,g as EC,h as Tk,i as AC,j as CC,k as MC,l as jC,m as OC,n as Lf,o as HC,p as Ek,q as DC,r as LC,s as Ut,t as BC,u as et,v as ft,w as $C,x as NC,y as Yl,z as Bf}from"./chunk-EIRYMSEG.js";import{$ as dj,$a as gO,A as KM,Aa as th,Ba as Cj,Ca as Mj,D as Ac,Da as jj,E as so,Ea as Ji,F as YM,Fa as Oj,G as Zl,Ga as uO,I as XM,J as QM,K as ZM,Ka as dh,L as ej,La as pO,M as tj,Ma as mO,Na as lo,O as Cc,Oa as fO,P as rj,Pa as Yi,Qa as hO,R as eu,S as eh,T as nj,U as Dk,V as oj,W as aj,X as Lk,Y as ij,Z as sj,_ as cj,aa as lj,b as Tc,ba as uj,bb as wO,ca as pj,cb as au,da as Bk,db as yO,e as iM,ea as mj,eb as iu,fa as fj,fb as vO,g as Gf,ga as hj,gb as zk,ha as gj,hb as bO,i as wM,ia as $k,ib as su,ja as wj,jb as kO,ka as yj,kb as lh,l as yM,la as vj,lb as IO,ma as bj,mb as SO,n as Jf,na as kj,nb as PO,o as vM,oa as Ij,ob as RO,pa as Sj,pb as uh,q as Yf,qa as Pj,qb as xO,r as JM,ra as Rj,rb as _O,s as Cn,t as Xf,ta as xj,tb as TO,u as Hk,ua as _j,ub as EO,v as Qf,va as Tj,wa as Ej,x as Zf,xa as Aj,y as Ql,ya as tu}from"./chunk-QOTVNQDI.js";import{d as gC}from"./chunk-OQPJ7FJF.js";import{B as OM,C as Kf,D as HM,E as DM,F as LM,G as BM,H as $M,I as NM,J as UM,K as qM,L as FM,M as zM,N as WM,O as VM,P as GM,a as Mk,b as sM,c as gr,d as Vi,e as Gi,f as jk,g as cM,h as dM,i as lM,j as uM,k as pM,o as qo,p as Ec,q as gM,s as _M,t as TM,u as io,v as EM,w as AM,x as CM,y as MM,z as jM}from"./chunk-WJ43MJ3F.js";import{e as fM,g as hM,h as Ok,j as st}from"./chunk-Q4TBTRIG.js";import{b as mM,c as Vf}from"./chunk-T5AACNJI.js";import{$ as La,A as Jj,B as Kj,C as Yj,E as jc,F as Xj,V as Ki,W as Qj,X as Fo,Y as Zj,Z as eO,_ as tO,a as rh,aa as Oc,b as Hj,ba as ah,c as Nk,ca as rO,d as co,da as nO,e as Dj,ea as oO,f as Lj,fa as nu,g as Uk,ga as Hc,h as ru,ha as ih,i as Bj,ia as aO,j as nh,ja as sh,k as $j,ka as Ba,l as Nj,la as iO,m as Mc,ma as sO,n as Uj,na as cO,o as oh,oa as ch,p as qj,pa as dO,q as Fj,qa as ou,r as qk,ra as lO,t as zj,u as or,w as Wj,x as Vj,y as Gj,z as Fk}from"./chunk-QOGJAQDO.js";import{g as wC,j as yC,l as Rc,m as vC,o as Of,s as Hf}from"./chunk-EYPCBBMS.js";import{b as bM,c as kM,d as IM,e as SM,f as PM,g as RM,h as xM}from"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import{c as RC}from"./chunk-BFKYRQMA.js";import"./chunk-6QSSIT62.js";import{a as mC,b as fC,c as tn,d as Mf,e as Fi,f as Jl,g as _k,h as jf,i as hC,k as $f,n as zC}from"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import{a as bC,b as rn,c as kC,d as IC,e as Df,f as SC}from"./chunk-3VUATFZD.js";import{a as Kl}from"./chunk-4EPSHPZL.js";import{a as aY,b as iE,c as $b,d as Nb}from"./chunk-H6IW2R22.js";import{b as xc,c as PC}from"./chunk-L3KS6MOV.js";import"./chunk-MQULU465.js";import{a as V0,e as G0,f as J0,g as oC,h as Pk,i as qi,j as aC,k as iC,l as sC,n as Af,o as cC,q as dC,r as Vl,s as Rk,v as Cf,x as xk,y as lC,z as uC}from"./chunk-PRGBLQVH.js";import{d as Pc,e as Wl,f as tC,g as rC,h as nC,j as Ik,l as Sk}from"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import{b as X0,k as Z0,n as eC}from"./chunk-XDQMGUWL.js";import{B as vf,D as kc,a as uf,b as Ui,c as v0,h as b0,i as hr,k as gf,u as wf,v as lk,w as I0,x as S0,y as yf,z as P0}from"./chunk-FTEOCCPB.js";import{$a as wk,Aa as bf,Ab as Ha,Ba as kf,Bb as z0,C as u0,Ca as uk,Cb as W0,Da as pk,Db as _r,E as bc,Ea as _0,Fb as Q0,Ga as T0,Ha as E0,Ib as Da,J as p0,Ja as If,Ka as A0,L as m0,Ma as C0,N as f0,Oa as M0,P as h0,Q as g0,Ra as Sf,Ta as Pf,Ua as Rf,Va as Ic,Wa as mk,Xa as fk,Y as w0,Ya as xf,Za as hk,_a as gk,ab as yk,bb as vk,c as QA,ca as ja,cb as bk,da as zl,i as ZA,ja as ff,jb as j0,ka as y0,kb as O0,l as n0,la as Ze,lb as Sc,m as o0,mb as H0,n as a0,nb as D0,o as i0,ob as _f,p as s0,pb as Tf,q as mf,qb as Ef,r as dk,rb as L0,s as c0,sb as kk,t as d0,tb as B0,u as l0,ua as Oa,va as k0,vb as $0,wa as hf,wb as N0,xa as _n,xb as U0,ya as R0,yb as q0,za as x0,zb as F0}from"./chunk-25MBPJVY.js";import{e as ik,l as ao}from"./chunk-WN3V6KDN.js";import{A as Fl,C as t0,D as pf,G as r0,K as ck,L as Ma,b as sk,i as nr,j as ql,n as en,u as e0}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-FWIPHEVA.js";import{b as QE,c as eA}from"./chunk-QDC4OW3S.js";import"./chunk-ZZWAQBA2.js";import{g as XA}from"./chunk-YR5ID2SS.js";import{b as ZE,e as tA}from"./chunk-YBT2NB32.js";import{k as Lb}from"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import{C as $A,D as NA,I as FA,K as rk,L as nk,M as zA,S as ok,U as WA,V as ak,Z as VA,_ as GA,ca as JA,da as KA,f as $l,fa as Ni,ga as YA,ha as lf,v as vc,x as Ul}from"./chunk-I7AQMAQI.js";import{M as yc,O as HA,Q as DA,R as LA,S as BA,a as $i,b as xA,c as Nl,d as xn,e as _A,f as of,g as TA,h as EA,i as af,j as sf,l as AA,m as CA,n as MA,o as jA,p as OA,z as tk}from"./chunk-Z4Z5UOZM.js";import{a as Gl}from"./chunk-6FA3GG5B.js";import{Ba as fA,Ua as hA,Wa as tf,ba as rA,bb as Xb,d as OE,db as gA,f as Qm,fb as wA,gb as rf,hb as yA,l as HE,lb as vA,m as DE,ob as bA,pa as nA,sb as Qb,ub as Zb,va as mA,wb as kA,x as LE,xb as IA,yb as SA,zb as ek}from"./chunk-Y4OWBBDD.js";import{A as iA,E as sA,F as cA,G as Li,H as dA,I as lA,J as uA,N as pA,h as oA,z as aA}from"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import{b as rE,d as Bm,e as Rn,f as rr}from"./chunk-FFRFSDBM.js";import{$ as zE,Ab as wc,Fb as JE,H as qE,Hb as KE,Mb as YE,N as We,O as xt,Q as FE,Ra as ef,Tb as XE,b as xE,ba as Zm,d as Zr,g as BE,j as $E,kb as WE,l as NE,lb as Ca,m as UE,mb as pt,nb as VE,qb as GE,yb as gc,zb as $o}from"./chunk-VYLGI3IH.js";import{$ as Gb,Aa as PE,Ab as AE,Bb as CE,Cb as ME,D as hE,Db as jE,E as Fm,Ea as RE,F as zm,G as Wm,H as Vm,Ja as Km,K as Gm,L as Ub,La as Ll,M as Hi,N as Di,P as gE,R as wE,S as yE,Va as Ym,W as qb,Wa as _E,X as Fb,Y as zb,Z as Wb,_ as Vb,_a as Yb,a as aE,aa as Jb,ba as Kb,db as TE,ea as vE,fb as EE,h as _e,ib as Xm,l as Aa,oa as bE,qa as kE,ta as IE,v as mE,wa as Jm,x as fE,za as SE}from"./chunk-ACYFMLWG.js";import{q as nE,r as Ea}from"./chunk-TVQAPBLZ.js";import{f as eE,g as Db,h as tE,k as ot,l as Re,m as A,n as Lm}from"./chunk-KGNCKIFP.js";import{a as Nt,b}from"./chunk-ES2ISFJC.js";import{a as PA,c as Bi,f as nf,h as Bl,i as RA,n as cf,o as UA,p as No,q as qA,r as Uo,s as df}from"./chunk-H7IWJN7L.js";import{a as i,b as He,c as Ce,e as Qr}from"./chunk-FTQLQJQV.js";var Ko=Ce((JSe,$B)=>{"use strict";var LB=["nodebuffer","arraybuffer","fragments"],BB=typeof Blob<"u";BB&&LB.push("blob");$B.exports={BINARY_TYPES:LB,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:BB,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:i(()=>{},"NOOP")}});var Ru=Ce((YSe,ag)=>{"use strict";var{EMPTY_BUFFER:ZY}=Ko(),OI=Buffer[Symbol.species];function eX(e,t){if(e.length===0)return ZY;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let a=e[o];r.set(a,n),n+=a.length}return n<t?new OI(r.buffer,r.byteOffset,n):r}i(eX,"concat");function NB(e,t,r,n,o){for(let a=0;a<o;a++)r[n+a]=e[a]^t[a&3]}i(NB,"_mask");function UB(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}i(UB,"_unmask");function tX(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}i(tX,"toArrayBuffer");function HI(e){if(HI.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new OI(e):ArrayBuffer.isView(e)?t=new OI(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),HI.readOnly=!1),t}i(HI,"toBuffer");ag.exports={concat:eX,mask:NB,toArrayBuffer:tX,toBuffer:HI,unmask:UB};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=He("bufferutil");ag.exports.mask=function(t,r,n,o,a){a<48?NB(t,r,n,o,a):e.mask(t,r,n,o,a)},ag.exports.unmask=function(t,r){t.length<32?UB(t,r):e.unmask(t,r)}}catch{}});var zB=Ce((QSe,FB)=>{"use strict";var qB=Symbol("kDone"),DI=Symbol("kRun"),LI=class{static{i(this,"Limiter")}constructor(t){this[qB]=()=>{this.pending--,this[DI]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[DI]()}[DI](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[qB])}}};FB.exports=LI});var nd=Ce((ePe,JB)=>{"use strict";var xu=He("zlib"),WB=Ru(),rX=zB(),{kStatusCode:VB}=Ko(),nX=Buffer[Symbol.species],oX=Buffer.from([0,0,255,255]),sg=Symbol("permessage-deflate"),Yo=Symbol("total-length"),td=Symbol("callback"),Qa=Symbol("buffers"),rd=Symbol("error"),ig,BI=class{static{i(this,"PerMessageDeflate")}constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ig){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ig=new rX(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[td];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,n=t.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),t}decompress(t,r,n){ig.add(o=>{this._decompress(t,r,(a,s)=>{o(),n(a,s)})})}compress(t,r,n){ig.add(o=>{this._compress(t,r,(a,s)=>{o(),n(a,s)})})}_decompress(t,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?xu.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=xu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[sg]=this,this._inflate[Yo]=0,this._inflate[Qa]=[],this._inflate.on("error",iX),this._inflate.on("data",GB)}this._inflate[td]=n,this._inflate.write(t),r&&this._inflate.write(oX),this._inflate.flush(()=>{let a=this._inflate[rd];if(a){this._inflate.close(),this._inflate=null,n(a);return}let s=WB.concat(this._inflate[Qa],this._inflate[Yo]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yo]=0,this._inflate[Qa]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(t,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?xu.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=xu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Yo]=0,this._deflate[Qa]=[],this._deflate.on("data",aX)}this._deflate[td]=n,this._deflate.write(t),this._deflate.flush(xu.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=WB.concat(this._deflate[Qa],this._deflate[Yo]);r&&(a=new nX(a.buffer,a.byteOffset,a.length-4)),this._deflate[td]=null,this._deflate[Yo]=0,this._deflate[Qa]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,a)})}};JB.exports=BI;function aX(e){this[Qa].push(e),this[Yo]+=e.length}i(aX,"deflateOnData");function GB(e){if(this[Yo]+=e.length,this[sg]._maxPayload<1||this[Yo]<=this[sg]._maxPayload){this[Qa].push(e);return}this[rd]=new RangeError("Max payload size exceeded"),this[rd].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rd][VB]=1009,this.removeListener("data",GB),this.reset()}i(GB,"inflateOnData");function iX(e){if(this[sg]._inflate=null,this[rd]){this[td](this[rd]);return}e[VB]=1007,this[td](e)}i(iX,"inflateOnError")});var od=Ce((rPe,cg)=>{"use strict";var{isUtf8:KB}=He("buffer"),{hasBlob:sX}=Ko(),cX=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function dX(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}i(dX,"isValidStatusCode");function $I(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}i($I,"_isValidUTF8");function lX(e){return sX&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}i(lX,"isBlob");cg.exports={isBlob:lX,isValidStatusCode:dX,isValidUTF8:$I,tokenChars:cX};if(KB)cg.exports.isValidUTF8=function(e){return e.length<24?$I(e):KB(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=He("utf-8-validate");cg.exports.isValidUTF8=function(t){return t.length<32?$I(t):e(t)}}catch{}});var zI=Ce((oPe,r$)=>{"use strict";var{Writable:uX}=He("stream"),YB=nd(),{BINARY_TYPES:pX,EMPTY_BUFFER:XB,kStatusCode:mX,kWebSocket:fX}=Ko(),{concat:NI,toArrayBuffer:hX,unmask:gX}=Ru(),{isValidStatusCode:wX,isValidUTF8:QB}=od(),dg=Buffer[Symbol.species],an=0,ZB=1,e$=2,t$=3,UI=4,qI=5,lg=6,FI=class extends uX{static{i(this,"Receiver")}constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||pX[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[fX]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=an}_write(t,r,n){if(this._opcode===8&&this._state==an)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(n)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new dg(n.buffer,n.byteOffset+t,n.length-t),new dg(n.buffer,n.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let n=this._buffers[0],o=r.length-t;t>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,t),o),this._buffers[0]=new dg(n.buffer,n.byteOffset+t,n.length-t)),t-=n.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case an:this.getInfo(t);break;case ZB:this.getPayloadLength16(t);break;case e$:this.getPayloadLength64(t);break;case t$:this.getMask();break;case UI:this.getData(t);break;case qI:case lg:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[YB.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=ZB:this._payloadLength===127?this._state=e$:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=t$:this._state=UI}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=UI}getData(t){let r=XB;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&gX(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(n);return}if(this._compressed){this._state=qI,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[YB.extensionName].decompress(t,this._fin,(o,a)=>{if(o)return r(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(s);return}this._fragments.push(a)}this.dataMessage(r),this._state===an&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=an;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=NI(n,r):this._binaryType==="arraybuffer"?o=hX(NI(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=an):(this._state=lg,setImmediate(()=>{this.emit("message",o,!0),this._state=an,this.startLoop(t)}))}else{let o=NI(n,r);if(!this._skipUTF8Validation&&!QB(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(a);return}this._state===qI||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=an):(this._state=lg,setImmediate(()=>{this.emit("message",o,!1),this._state=an,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,XB),this.end();else{let n=t.readUInt16BE(0);if(!wX(n)){let a=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(a);return}let o=new dg(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!QB(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(a);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=an;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=an):(this._state=lg,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=an,this.startLoop(r)}))}createError(t,r,n,o,a){this._loop=!1,this._errored=!0;let s=new t(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=a,s[mX]=o,s}};r$.exports=FI});var GI=Ce((sPe,a$)=>{"use strict";var{Duplex:iPe}=He("stream"),{randomFillSync:yX}=He("crypto"),{types:{isUint8Array:vX}}=He("util"),n$=nd(),{EMPTY_BUFFER:bX,kWebSocket:kX,NOOP:IX}=Ko(),{isBlob:ad,isValidStatusCode:SX}=od(),{mask:o$,toBuffer:os}=Ru(),sn=Symbol("kByteLength"),PX=Buffer.alloc(4),ug=8*1024,as,id=ug,Dn=0,RX=1,xX=2,WI=class e{static{i(this,"Sender")}constructor(t,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Dn,this.onerror=IX,this[kX]=void 0}static frame(t,r){let n,o=!1,a=2,s=!1;r.mask&&(n=r.maskBuffer||PX,r.generateMask?r.generateMask(n):(id===ug&&(as===void 0&&(as=Buffer.alloc(ug)),yX(as,0,ug),id=0),n[0]=as[id++],n[1]=as[id++],n[2]=as[id++],n[3]=as[id++]),s=(n[0]|n[1]|n[2]|n[3])===0,a=6);let c;typeof t=="string"?(!r.mask||s)&&r[sn]!==void 0?c=r[sn]:(t=Buffer.from(t),c=t.length):(c=t.length,o=r.mask&&r.readOnly&&!s);let d=c;c>=65536?(a+=8,d=127):c>125&&(a+=2,d=126);let l=Buffer.allocUnsafe(o?c+a:a);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],s?[l,t]:o?(o$(t,n,l,a,c),[l]):(o$(t,n,t,0,c),[l,t])):[l,t]}close(t,r,n,o){let a;if(t===void 0)a=bX;else{if(typeof t!="number"||!SX(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(a=Buffer.allocUnsafe(2+c),a.writeUInt16BE(t,0),typeof r=="string")a.write(r,2);else if(vX(r))a.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[sn]:a.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Dn?this.enqueue([this.dispatch,a,!1,s,o]):this.sendFrame(e.frame(a,s),o)}ping(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):ad(t)?(o=t.size,a=!1):(t=os(t),o=t.length,a=os.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[sn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};ad(t)?this._state!==Dn?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==Dn?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}pong(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):ad(t)?(o=t.size,a=!1):(t=os(t),o=t.length,a=os.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[sn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};ad(t)?this._state!==Dn?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==Dn?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}send(t,r,n){let o=this._extensions[n$.extensionName],a=r.binary?2:1,s=r.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):ad(t)?(c=t.size,d=!1):(t=os(t),c=t.length,d=os.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=c>=o._threshold),this._compress=s):(s=!1,a=0),r.fin&&(this._firstFragment=!0);let l={[sn]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:d,rsv1:s};ad(t)?this._state!==Dn?this.enqueue([this.getBlobData,t,this._compress,l,n]):this.getBlobData(t,this._compress,l,n):this._state!==Dn?this.enqueue([this.dispatch,t,this._compress,l,n]):this.dispatch(t,this._compress,l,n)}getBlobData(t,r,n,o){this._bufferedBytes+=n[sn],this._state=xX,t.arrayBuffer().then(a=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(VI,this,c,o);return}this._bufferedBytes-=n[sn];let s=os(a);r?this.dispatch(s,r,n,o):(this._state=Dn,this.sendFrame(e.frame(s,n),o),this.dequeue())}).catch(a=>{process.nextTick(_X,this,a,o)})}dispatch(t,r,n,o){if(!r){this.sendFrame(e.frame(t,n),o);return}let a=this._extensions[n$.extensionName];this._bufferedBytes+=n[sn],this._state=RX,a.compress(t,n.fin,(s,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");VI(this,d,o);return}this._bufferedBytes-=n[sn],this._state=Dn,n.readOnly=!1,this.sendFrame(e.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===Dn&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][sn],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][sn],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};a$.exports=WI;function VI(e,t,r){typeof r=="function"&&r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],a=o[o.length-1];typeof a=="function"&&a(t)}}i(VI,"callCallbacks");function _X(e,t,r){VI(e,t,r),e.onerror(t)}i(_X,"onError")});var f$=Ce((dPe,m$)=>{"use strict";var{kForOnEventAttribute:_u,kListener:JI}=Ko(),i$=Symbol("kCode"),s$=Symbol("kData"),c$=Symbol("kError"),d$=Symbol("kMessage"),l$=Symbol("kReason"),sd=Symbol("kTarget"),u$=Symbol("kType"),p$=Symbol("kWasClean"),Xo=class{static{i(this,"Event")}constructor(t){this[sd]=null,this[u$]=t}get target(){return this[sd]}get type(){return this[u$]}};Object.defineProperty(Xo.prototype,"target",{enumerable:!0});Object.defineProperty(Xo.prototype,"type",{enumerable:!0});var is=class extends Xo{static{i(this,"CloseEvent")}constructor(t,r={}){super(t),this[i$]=r.code===void 0?0:r.code,this[l$]=r.reason===void 0?"":r.reason,this[p$]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[i$]}get reason(){return this[l$]}get wasClean(){return this[p$]}};Object.defineProperty(is.prototype,"code",{enumerable:!0});Object.defineProperty(is.prototype,"reason",{enumerable:!0});Object.defineProperty(is.prototype,"wasClean",{enumerable:!0});var cd=class extends Xo{static{i(this,"ErrorEvent")}constructor(t,r={}){super(t),this[c$]=r.error===void 0?null:r.error,this[d$]=r.message===void 0?"":r.message}get error(){return this[c$]}get message(){return this[d$]}};Object.defineProperty(cd.prototype,"error",{enumerable:!0});Object.defineProperty(cd.prototype,"message",{enumerable:!0});var Tu=class extends Xo{static{i(this,"MessageEvent")}constructor(t,r={}){super(t),this[s$]=r.data===void 0?null:r.data}get data(){return this[s$]}};Object.defineProperty(Tu.prototype,"data",{enumerable:!0});var TX={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[_u]&&o[JI]===t&&!o[_u])return;let n;if(e==="message")n=i(function(a,s){let c=new Tu("message",{data:s?a:a.toString()});c[sd]=this,pg(t,this,c)},"onMessage");else if(e==="close")n=i(function(a,s){let c=new is("close",{code:a,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[sd]=this,pg(t,this,c)},"onClose");else if(e==="error")n=i(function(a){let s=new cd("error",{error:a,message:a.message});s[sd]=this,pg(t,this,s)},"onError");else if(e==="open")n=i(function(){let a=new Xo("open");a[sd]=this,pg(t,this,a)},"onOpen");else return;n[_u]=!!r[_u],n[JI]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[JI]===t&&!r[_u]){this.removeListener(e,r);break}}};m$.exports={CloseEvent:is,ErrorEvent:cd,Event:Xo,EventTarget:TX,MessageEvent:Tu};function pg(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}i(pg,"callListener")});var mg=Ce((uPe,h$)=>{"use strict";var{tokenChars:Eu}=od();function go(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}i(go,"push");function EX(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,a=!1,s,c,d=-1,l=-1,u=-1,p=0;for(;p<e.length;p++)if(l=e.charCodeAt(p),s===void 0)if(u===-1&&Eu[l]===1)d===-1&&(d=p);else if(p!==0&&(l===32||l===9))u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let w=e.slice(d,u);l===44?(go(t,w,r),r=Object.create(null)):s=w,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(u===-1&&Eu[l]===1)d===-1&&(d=p);else if(l===32||l===9)u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),go(r,e.slice(d,u),!0),l===44&&(go(t,s,r),r=Object.create(null),s=void 0),d=u=-1}else if(l===61&&d!==-1&&u===-1)c=e.slice(d,p),d=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Eu[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:n||(n=!0),o=!1}else if(a)if(Eu[l]===1)d===-1&&(d=p);else if(l===34&&d!==-1)a=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&e.charCodeAt(p-1)===61)a=!0;else if(u===-1&&Eu[l]===1)d===-1&&(d=p);else if(d!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let w=e.slice(d,u);n&&(w=w.replace(/\\/g,""),n=!1),go(r,c,w),l===44&&(go(t,s,r),r=Object.create(null),s=void 0),c=void 0,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||a||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let m=e.slice(d,u);return s===void 0?go(t,m,r):(c===void 0?go(r,m,!0):n?go(r,c,m.replace(/\\/g,"")):go(r,c,m),go(t,s,r)),t}i(EX,"parse");function AX(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(n=>[t].concat(Object.keys(n).map(o=>{let a=n[o];return Array.isArray(a)||(a=[a]),a.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}i(AX,"format");h$.exports={format:AX,parse:EX}});var wg=Ce((hPe,_$)=>{"use strict";var CX=He("events"),MX=He("https"),jX=He("http"),y$=He("net"),OX=He("tls"),{randomBytes:HX,createHash:DX}=He("crypto"),{Duplex:mPe,Readable:fPe}=He("stream"),{URL:KI}=He("url"),Za=nd(),LX=zI(),BX=GI(),{isBlob:$X}=od(),{BINARY_TYPES:g$,CLOSE_TIMEOUT:NX,EMPTY_BUFFER:fg,GUID:UX,kForOnEventAttribute:YI,kListener:qX,kStatusCode:FX,kWebSocket:Tt,NOOP:v$}=Ko(),{EventTarget:{addEventListener:zX,removeEventListener:WX}}=f$(),{format:VX,parse:GX}=mg(),{toBuffer:JX}=Ru(),b$=Symbol("kAborted"),XI=[8,13],Qo=["CONNECTING","OPEN","CLOSING","CLOSED"],KX=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ct=class e extends CX{static{i(this,"WebSocket")}constructor(t,r,n){super(),this._binaryType=g$[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=fg,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),k$(this,t,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){g$.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){let o=new LX({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),a=new BX(t,this._extensions,n.generateMask);this._receiver=o,this._sender=a,this._socket=t,o[Tt]=this,a[Tt]=this,t[Tt]=this,o.on("conclude",QX),o.on("drain",ZX),o.on("error",eQ),o.on("message",tQ),o.on("ping",rQ),o.on("pong",nQ),a.onerror=oQ,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",P$),t.on("data",gg),t.on("end",R$),t.on("error",x$),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Za.extensionName]&&this._extensions[Za.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){$r(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),S$(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){QI(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||fg,r,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){QI(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||fg,r,n)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){QI(this,t,n);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Za.extensionName]||(o.compress=!1),this._sender.send(t||fg,o,n)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){$r(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(ct,"CONNECTING",{enumerable:!0,value:Qo.indexOf("CONNECTING")});Object.defineProperty(ct.prototype,"CONNECTING",{enumerable:!0,value:Qo.indexOf("CONNECTING")});Object.defineProperty(ct,"OPEN",{enumerable:!0,value:Qo.indexOf("OPEN")});Object.defineProperty(ct.prototype,"OPEN",{enumerable:!0,value:Qo.indexOf("OPEN")});Object.defineProperty(ct,"CLOSING",{enumerable:!0,value:Qo.indexOf("CLOSING")});Object.defineProperty(ct.prototype,"CLOSING",{enumerable:!0,value:Qo.indexOf("CLOSING")});Object.defineProperty(ct,"CLOSED",{enumerable:!0,value:Qo.indexOf("CLOSED")});Object.defineProperty(ct.prototype,"CLOSED",{enumerable:!0,value:Qo.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(ct.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(ct.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[YI])return t[qX];return null},set(t){for(let r of this.listeners(e))if(r[YI]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[YI]:!0})}})});ct.prototype.addEventListener=zX;ct.prototype.removeEventListener=WX;_$.exports=ct;function k$(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:NX,protocolVersion:XI[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!XI.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${XI.join(", ")})`);let a;if(t instanceof KI)a=t;else try{a=new KI(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),e._url=a.href;let s=a.protocol==="wss:",c=a.protocol==="ws+unix:",d;if(a.protocol!=="ws:"&&!s&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!a.pathname?d="The URL's pathname is empty":a.hash&&(d="The URL contains a fragment identifier"),d){let f=new SyntaxError(d);if(e._redirects===0)throw f;hg(e,f);return}let l=s?443:80,u=HX(16).toString("base64"),p=s?MX.request:jX.request,m=new Set,w;if(o.createConnection=o.createConnection||(s?XX:YX),o.defaultPort=o.defaultPort||l,o.port=a.port||l,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(w=new Za({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=VX({[Za.extensionName]:w.offer()})),r.length){for(let f of r){if(typeof f!="string"||!KX.test(f)||m.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(f)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),c){let f=o.path.split(":");o.socketPath=f[0],o.path=f[1]}let g;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=s,e._originalHostOrSocketPath=c?o.socketPath:a.host;let f=n&&n.headers;if(n={...n,headers:{}},f)for(let[y,h]of Object.entries(f))n.headers[y.toLowerCase()]=h}else if(e.listenerCount("redirect")===0){let f=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:a.host===e._originalHostOrSocketPath;(!f||e._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,f||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),g=e._req=p(o),e._redirects&&e.emit("redirect",e.url,g)}else g=e._req=p(o);o.timeout&&g.on("timeout",()=>{$r(e,g,"Opening handshake has timed out")}),g.on("error",f=>{g===null||g[b$]||(g=e._req=null,hg(e,f))}),g.on("response",f=>{let y=f.headers.location,h=f.statusCode;if(y&&o.followRedirects&&h>=300&&h<400){if(++e._redirects>o.maxRedirects){$r(e,g,"Maximum redirects exceeded");return}g.abort();let k;try{k=new KI(y,t)}catch{let I=new SyntaxError(`Invalid URL: ${y}`);hg(e,I);return}k$(e,k,r,n)}else e.emit("unexpected-response",g,f)||$r(e,g,`Unexpected server response: ${f.statusCode}`)}),g.on("upgrade",(f,y,h)=>{if(e.emit("upgrade",f),e.readyState!==ct.CONNECTING)return;g=e._req=null;let k=f.headers.upgrade;if(k===void 0||k.toLowerCase()!=="websocket"){$r(e,y,"Invalid Upgrade header");return}let S=DX("sha1").update(u+UX).digest("base64");if(f.headers["sec-websocket-accept"]!==S){$r(e,y,"Invalid Sec-WebSocket-Accept header");return}let I=f.headers["sec-websocket-protocol"],v;if(I!==void 0?m.size?m.has(I)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":m.size&&(v="Server sent no subprotocol"),v){$r(e,y,v);return}I&&(e._protocol=I);let R=f.headers["sec-websocket-extensions"];if(R!==void 0){if(!w){$r(e,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=GX(R)}catch{$r(e,y,"Invalid Sec-WebSocket-Extensions header");return}let P=Object.keys(T);if(P.length!==1||P[0]!==Za.extensionName){$r(e,y,"Server indicated an extension that was not requested");return}try{w.accept(T[Za.extensionName])}catch{$r(e,y,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[Za.extensionName]=w}e.setSocket(y,h,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(g,e):g.end()}i(k$,"initAsClient");function hg(e,t){e._readyState=ct.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}i(hg,"emitErrorAndClose");function YX(e){return e.path=e.socketPath,y$.connect(e)}i(YX,"netConnect");function XX(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=y$.isIP(e.host)?"":e.host),OX.connect(e)}i(XX,"tlsConnect");function $r(e,t,r){e._readyState=ct.CLOSING;let n=new Error(r);Error.captureStackTrace(n,$r),t.setHeader?(t[b$]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(hg,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}i($r,"abortHandshake");function QI(e,t,r){if(t){let n=$X(t)?t.size:JX(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${e.readyState} (${Qo[e.readyState]})`);process.nextTick(r,n)}}i(QI,"sendAfterClose");function QX(e,t){let r=this[Tt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[Tt]!==void 0&&(r._socket.removeListener("data",gg),process.nextTick(I$,r._socket),e===1005?r.close():r.close(e,t))}i(QX,"receiverOnConclude");function ZX(){let e=this[Tt];e.isPaused||e._socket.resume()}i(ZX,"receiverOnDrain");function eQ(e){let t=this[Tt];t._socket[Tt]!==void 0&&(t._socket.removeListener("data",gg),process.nextTick(I$,t._socket),t.close(e[FX])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}i(eQ,"receiverOnError");function w$(){this[Tt].emitClose()}i(w$,"receiverOnFinish");function tQ(e,t){this[Tt].emit("message",e,t)}i(tQ,"receiverOnMessage");function rQ(e){let t=this[Tt];t._autoPong&&t.pong(e,!this._isServer,v$),t.emit("ping",e)}i(rQ,"receiverOnPing");function nQ(e){this[Tt].emit("pong",e)}i(nQ,"receiverOnPong");function I$(e){e.resume()}i(I$,"resume");function oQ(e){let t=this[Tt];t.readyState!==ct.CLOSED&&(t.readyState===ct.OPEN&&(t._readyState=ct.CLOSING,S$(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}i(oQ,"senderOnError");function S$(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}i(S$,"setCloseTimer");function P$(){let e=this[Tt];if(this.removeListener("close",P$),this.removeListener("data",gg),this.removeListener("end",R$),e._readyState=ct.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[Tt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",w$),e._receiver.on("finish",w$))}i(P$,"socketOnClose");function gg(e){this[Tt]._receiver.write(e)||this.pause()}i(gg,"socketOnData");function R$(){let e=this[Tt];e._readyState=ct.CLOSING,e._receiver.end(),this.end()}i(R$,"socketOnEnd");function x$(){let e=this[Tt];this.removeListener("error",x$),this.on("error",v$),e&&(e._readyState=ct.CLOSING,this.destroy())}i(x$,"socketOnError")});var C$=Ce((yPe,A$)=>{"use strict";var wPe=wg(),{Duplex:aQ}=He("stream");function T$(e){e.emit("close")}i(T$,"emitClose");function iQ(){!this.destroyed&&this._writableState.finished&&this.destroy()}i(iQ,"duplexOnEnd");function E$(e){this.removeListener("error",E$),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}i(E$,"duplexOnError");function sQ(e,t){let r=!0,n=new aQ({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",i(function(a,s){let c=!s&&n._readableState.objectMode?a.toString():a;n.push(c)||e.pause()},"message")),e.once("error",i(function(a){n.destroyed||(r=!1,n.destroy(a))},"error")),e.once("close",i(function(){n.destroyed||n.push(null)},"close")),n._destroy=function(o,a){if(e.readyState===e.CLOSED){a(o),process.nextTick(T$,n);return}let s=!1;e.once("error",i(function(d){s=!0,a(d)},"error")),e.once("close",i(function(){s||a(o),process.nextTick(T$,n)},"close")),r&&e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._final(o)},"open"));return}e._socket!==null&&(e._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",i(function(){o()},"finish")),e.close()))},n._read=function(){e.isPaused&&e.resume()},n._write=function(o,a,s){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._write(o,a,s)},"open"));return}e.send(o,s)},n.on("end",iQ),n.on("error",E$),n}i(sQ,"createWebSocketStream");A$.exports=sQ});var ZI=Ce((bPe,M$)=>{"use strict";var{tokenChars:cQ}=od();function dQ(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let s=e.charCodeAt(o);if(n===-1&&cQ[s]===1)r===-1&&(r=o);else if(o!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=o);else if(s===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=e.slice(r,n);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let a=e.slice(r,o);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return t.add(a),t}i(dQ,"parse");M$.exports={parse:dQ}});var $$=Ce((SPe,B$)=>{"use strict";var lQ=He("events"),yg=He("http"),{Duplex:IPe}=He("stream"),{createHash:uQ}=He("crypto"),j$=mg(),ss=nd(),pQ=ZI(),mQ=wg(),{CLOSE_TIMEOUT:fQ,GUID:hQ,kWebSocket:gQ}=Ko(),wQ=/^[+/0-9A-Za-z]{22}==$/,O$=0,H$=1,L$=2,eS=class extends lQ{static{i(this,"WebSocketServer")}constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:fQ,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:mQ,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=yg.createServer((n,o)=>{let a=yg.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=yQ(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:i((o,a,s)=>{this.handleUpgrade(o,a,s,n)},"upgrade")})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=O$}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===L$){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Au,this);return}if(t&&this.once("close",t),this._state!==H$)if(this._state=H$,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Au,this):process.nextTick(Au,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Au(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,n,o){r.on("error",D$);let a=t.headers["sec-websocket-key"],s=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){cs(this,t,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){cs(this,t,r,400,"Invalid Upgrade header");return}if(a===void 0||!wQ.test(a)){cs(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){cs(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Cu(r,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=pQ.parse(d)}catch{cs(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=t.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let m=new ss({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=j$.parse(u);w[ss.extensionName]&&(m.accept(w[ss.extensionName]),p[ss.extensionName]=m)}catch{cs(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(w,g,f,y)=>{if(!w)return Cu(r,g||401,f,y);this.completeUpgrade(p,a,l,t,r,n,o)});return}if(!this.options.verifyClient(m))return Cu(r,401)}this.completeUpgrade(p,a,l,t,r,n,o)}completeUpgrade(t,r,n,o,a,s,c){if(!a.readable||!a.writable)return a.destroy();if(a[gQ])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>O$)return Cu(a,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${uQ("sha1").update(r+hQ).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(t[ss.extensionName]){let p=t[ss.extensionName].params,m=j$.format({[ss.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),u._extensions=t}this.emit("headers",l,o),a.write(l.concat(`\r
|
|
3
|
+
import{a as BL,b as $L,c as NL}from"./chunk-2D4Y3HNW.js";import{a as cL,b as dL,c as Yh,d as lL,e as Ja,f as $e,g as uL,h as Ie,i as pL,j as mL,k as fL,l as hL,m as gL,n as wL,o as yL,p as vL,q as bL,r as kL,s as IL,t as nn,u as on,v as xe,w as SL}from"./chunk-Z54O534A.js";import{a as Bb,b as $m,c as PL,d as RL}from"./chunk-F4KOGISR.js";import{a as xL,b as _L}from"./chunk-KUERKVEU.js";import{a as TL,b as EL,c as AL}from"./chunk-QEFHOJFE.js";import{a as Xh,b as CL}from"./chunk-74IIXVAE.js";import{a as jL,b as OL,c as HL,d as j,e as DL,f as Ka,g as V,h as Qh,j as LL}from"./chunk-S5ESN275.js";import"./chunk-DUURYZOI.js";import{a as Jh,b as FD,c as zD,d as WD,e as VD}from"./chunk-QHWGQ3A4.js";import"./chunk-SH5CBAFC.js";import{b as JD}from"./chunk-SWUEFLOH.js";import{a as KD,b as Kh,c as YD,d as XD,e as QD}from"./chunk-XXYGGNVM.js";import{b as ZD}from"./chunk-PUZQU66L.js";import{a as eL,b as tL,c as hI,d as rL,e as nL,f as oL,g as aL,h as iL,j as sL}from"./chunk-WMKYHXVM.js";import{a as DO,b as j1,c as O1,d as H1,e as mH,f as fH,g as hH,h as gH,i as wH,j as yH}from"./chunk-YOBN7KTF.js";import{A as tI,c as gh,d as uo,e as VO,f as zo,g as yh,h as KO,i as Na,j as vh,k as YO,o as XO,q as Ih,r as Sh,s as Ua,t as t1,u as P1,v as R1,w as x1,x as _1,z as T1}from"./chunk-7HPDGZOR.js";import{c as eI}from"./chunk-PPAPVGJP.js";import{a as qt,b as mu,c as Go,d as Dh,e as Lh,f as Va}from"./chunk-HZEIRHEB.js";import{b as Vh,d as Jc,l as HD,n as Gh}from"./chunk-G3RXYI2L.js";import{b as qD}from"./chunk-6FDWRG55.js";import{b as vH,c as nI}from"./chunk-PF5R6CMP.js";import"./chunk-DMVD2RFZ.js";import"./chunk-JYKRR7E5.js";import{a as GD}from"./chunk-OIUTWU6K.js";import"./chunk-X4OSOOSU.js";import"./chunk-3K4VVB7S.js";import{a as dH,b as lH,c as uH}from"./chunk-ZUJ3XUCP.js";import{a as QO,b as ZO,c as bh,d as kh}from"./chunk-XVDFJ3ZF.js";import{a as ee}from"./chunk-EQFGBL3O.js";import{d as e1}from"./chunk-GZ7M5XBP.js";import{a as Vo,b as rH,c as nH}from"./chunk-OUVIWDL2.js";import"./chunk-W45RKGM6.js";import"./chunk-GLDYJM7O.js";import{b as GO,c as JO,d as Lc,f as wh,g as cu}from"./chunk-HCYX6RHP.js";import{a as eH,b as tH}from"./chunk-YOQRYNLP.js";import{a as K1,c as Y1,d as X1,e as Q1,f as Wo,g as Z1,h as Hh,k as uu}from"./chunk-YY7LEQGP.js";import{a as YC,d as XC,e as Wi,h as AO}from"./chunk-3Z47M3YY.js";import{a as An}from"./chunk-ABD5M2D2.js";import{d as Nf}from"./chunk-TRQQNFMO.js";import{a as KC}from"./chunk-FEAKTSRS.js";import{a as En,b as Uf,c as Ck,d as QC}from"./chunk-OSIO7PLX.js";import"./chunk-F74GBN6K.js";import{a as Wf}from"./chunk-SDAUS5PY.js";import{a as aM}from"./chunk-I2NXNMRZ.js";import{a as Ff,d as zf,e as nM,f as oM,i as Xl,j as zi}from"./chunk-O72BSKSO.js";import{a as ph,b as jO,c as Wk}from"./chunk-OPNRWESL.js";import{b as CO,c as MO}from"./chunk-2QUCCP6Z.js";import{c as OO,d as mh,i as HO}from"./chunk-FY5KHLMW.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-XEOEKFG6.js";import{b as Nm,e as sE,f as cE,g as dE,l as hc,m as lE,n as uE,p as pE,q as Um,r as qm}from"./chunk-HY3GOBFJ.js";import{a as K0,d as Y0,f as pC}from"./chunk-DBK66CJP.js";import{a as bH,b as iY,c as SH,d as PH,e as LH,f as BH,g as $H,h as NH,i as UH,j as cD,k as LD,m as ML}from"./chunk-MULXCKG7.js";import{b as qH,c as zc,d as Wc,e as cI}from"./chunk-D74JEERO.js";import{a as tt,b as kH,c as IH,d as dI,e as KH,f as qh,g as Fh,h as YH}from"./chunk-JDEEWOD7.js";import{$ as jD,A as uD,B as pD,C as mD,D as fD,E as hD,F as gD,G as uI,H as wD,I as ID,J as SD,K as Zi,L as xD,M as Br,N as zh,O as es,P as jn,Q as On,R as _D,S as TD,T as ED,U as Hn,V as AD,W as Wh,X as CD,Y as MD,Z as ir,_ as ts,aa as Jo,b as RH,ba as pI,c as jH,ca as mI,d as OH,da as Gc,e as DH,ea as fI,f as FH,fa as OD,g as Vc,ga as DD,h as zH,ha as BD,i as WH,j as VH,k as XH,l as QH,m as ZH,n as eD,o as tD,p as rD,q as lI,r as nD,s as oD,t as aD,u as iD,x as sD,y as dD,z as lD}from"./chunk-OGDADQGH.js";import{a as HH}from"./chunk-4NESNOK5.js";import{a as xH,b as Bh,c as $h,d as Nh,e as _H,f as TH,g as EH,h as AH,i as oI,j as Qi,k as aI,l as fu,m as hu,n as Fc,o as Uh,p as iI,q as gu,r as ho,s as CH,t as de,u as MH,v as sI}from"./chunk-BLXEAZCQ.js";import{a as RD}from"./chunk-UCPGRPWY.js";import{a as $D,b as ND,c as UD}from"./chunk-L6K7ERG5.js";import{a as pH}from"./chunk-J2TWKFML.js";import{b as Ah}from"./chunk-773TH7FN.js";import{b as E1,c as A1,d as C1,e as M1}from"./chunk-HDL5YSAA.js";import{H as Qk,I as Zk,M as S1,a as r1,h as i1,i as s1,j as Vk,u as I1,y as Eh}from"./chunk-ZFSHBFG5.js";import{a as k1}from"./chunk-AN525SPP.js";import"./chunk-SYUKES6H.js";import{b as D1}from"./chunk-HIOKCIL7.js";import{a as GH,b as JH}from"./chunk-GW766ZSO.js";import{a as wr,b as LO,c as Mn,d as BO,e as fh,f as hh,h as $O,i as $a,k as NO,l as UO,m as qO,n as FO,o as zO,p as WO}from"./chunk-UKMA4R6X.js";import"./chunk-OQKJGTTO.js";import{a as qa}from"./chunk-KVTBX2UP.js";import{a as n1}from"./chunk-IZ6DLEVY.js";import{b as PD}from"./chunk-A6USMRWK.js";import{a as yD,b as wu,c as vD,d as bD,e as kD,f as Ga}from"./chunk-PCSIOUHF.js";import{a as Dc}from"./chunk-7KWD2I6W.js";import{b as oH,c as aH,d as iH,e as sH,f as cH,g as pu,h as Wa}from"./chunk-GPVCOEUH.js";import"./chunk-OLLLZVHF.js";import"./chunk-7PXZ4X4P.js";import"./chunk-N73MU2C3.js";import{a as Th,b as po,c as f1,d as Kk,e as h1,f as Yk,i as g1,j as Xk,k as w1,l as y1,m as v1,n as b1,o as Nc}from"./chunk-ZGTOK7ZK.js";import{A as m1,C as _h,b as Rh,d as c1,e as d1,h as l1,k as Gk,l as Jk,m as $c,n as u1,p as xh,q as p1,s as du}from"./chunk-XW6HGSIT.js";import{a as o1,b as Ph,d as he,e as _t,f as Bc,g as se,i as a1}from"./chunk-KG325WTN.js";import{A as Oh,B as J1,C as qc,d as Ch,e as Mh,f as L1,g as B1,i as $1,j as N1,k as U1,l as q1,m as Fa,n as lu,o as F1,p as z1,q as Uc,r as rI,s as W1,t as za,u as V1,v as Xi,y as jh,z as G1}from"./chunk-3RCRSMWZ.js";import"./chunk-UGL7WF3W.js";import"./chunk-DMFUEUAZ.js";import{a as mo,b as fo,c as ar}from"./chunk-PSGGOZFM.js";import{a as ZC,b as eM,c as tM,d as qf,e as rM}from"./chunk-FUOEIDMA.js";import"./chunk-NHQ36THU.js";import{b as oE,g as JC}from"./chunk-VRIEKBBH.js";import{b as WC,i as VC,j as GC,m as _c,n as Ak}from"./chunk-QNG27G3T.js";import{A as UC,C as qC,D as FC,E as Tn,d as xC,e as _C,f as TC,g as EC,h as Tk,i as AC,j as CC,k as MC,l as jC,m as OC,n as Lf,o as HC,p as Ek,q as DC,r as LC,s as Ut,t as BC,u as et,v as ft,w as $C,x as NC,y as Yl,z as Bf}from"./chunk-EIRYMSEG.js";import{$ as dj,$a as gO,A as KM,Aa as th,Ba as Cj,Ca as Mj,D as Ac,Da as jj,E as so,Ea as Ji,F as YM,Fa as Oj,G as Zl,Ga as uO,I as XM,J as QM,K as ZM,Ka as dh,L as ej,La as pO,M as tj,Ma as mO,Na as lo,O as Cc,Oa as fO,P as rj,Pa as Yi,Qa as hO,R as eu,S as eh,T as nj,U as Dk,V as oj,W as aj,X as Lk,Y as ij,Z as sj,_ as cj,aa as lj,b as Tc,ba as uj,bb as wO,ca as pj,cb as au,da as Bk,db as yO,e as iM,ea as mj,eb as iu,fa as fj,fb as vO,g as Gf,ga as hj,gb as zk,ha as gj,hb as bO,i as wM,ia as $k,ib as su,ja as wj,jb as kO,ka as yj,kb as lh,l as yM,la as vj,lb as IO,ma as bj,mb as SO,n as Jf,na as kj,nb as PO,o as vM,oa as Ij,ob as RO,pa as Sj,pb as uh,q as Yf,qa as Pj,qb as xO,r as JM,ra as Rj,rb as _O,s as Cn,t as Xf,ta as xj,tb as TO,u as Hk,ua as _j,ub as EO,v as Qf,va as Tj,wa as Ej,x as Zf,xa as Aj,y as Ql,ya as tu}from"./chunk-QOTVNQDI.js";import{d as gC}from"./chunk-OQPJ7FJF.js";import{B as OM,C as Kf,D as HM,E as DM,F as LM,G as BM,H as $M,I as NM,J as UM,K as qM,L as FM,M as zM,N as WM,O as VM,P as GM,a as Mk,b as sM,c as gr,d as Vi,e as Gi,f as jk,g as cM,h as dM,i as lM,j as uM,k as pM,o as qo,p as Ec,q as gM,s as _M,t as TM,u as io,v as EM,w as AM,x as CM,y as MM,z as jM}from"./chunk-WJ43MJ3F.js";import{e as fM,g as hM,h as Ok,j as st}from"./chunk-Q4TBTRIG.js";import{b as mM,c as Vf}from"./chunk-T5AACNJI.js";import{$ as La,A as Jj,B as Kj,C as Yj,E as jc,F as Xj,V as Ki,W as Qj,X as Fo,Y as Zj,Z as eO,_ as tO,a as rh,aa as Oc,b as Hj,ba as ah,c as Nk,ca as rO,d as co,da as nO,e as Dj,ea as oO,f as Lj,fa as nu,g as Uk,ga as Hc,h as ru,ha as ih,i as Bj,ia as aO,j as nh,ja as sh,k as $j,ka as Ba,l as Nj,la as iO,m as Mc,ma as sO,n as Uj,na as cO,o as oh,oa as ch,p as qj,pa as dO,q as Fj,qa as ou,r as qk,ra as lO,t as zj,u as or,w as Wj,x as Vj,y as Gj,z as Fk}from"./chunk-QOGJAQDO.js";import{g as wC,j as yC,l as Rc,m as vC,o as Of,s as Hf}from"./chunk-EYPCBBMS.js";import{b as bM,c as kM,d as IM,e as SM,f as PM,g as RM,h as xM}from"./chunk-DIO5CB6U.js";import"./chunk-7ED24PP6.js";import"./chunk-RNIAFXMB.js";import"./chunk-2IHO4GDJ.js";import"./chunk-KCJVFLBB.js";import"./chunk-N4FFQPLR.js";import"./chunk-AY64VY4E.js";import"./chunk-GJ2ZJFDD.js";import{c as RC}from"./chunk-BFKYRQMA.js";import"./chunk-6QSSIT62.js";import{a as mC,b as fC,c as tn,d as Mf,e as Fi,f as Jl,g as _k,h as jf,i as hC,k as $f,n as zC}from"./chunk-3QIB5FXI.js";import"./chunk-6MI4KKWF.js";import"./chunk-DDMZSZFL.js";import"./chunk-W45RKGM6.js";import{a as bC,b as rn,c as kC,d as IC,e as Df,f as SC}from"./chunk-3VUATFZD.js";import{a as Kl}from"./chunk-4EPSHPZL.js";import{a as aY,b as iE,c as $b,d as Nb}from"./chunk-H6IW2R22.js";import{b as xc,c as PC}from"./chunk-L3KS6MOV.js";import"./chunk-MQULU465.js";import{a as V0,e as G0,f as J0,g as oC,h as Pk,i as qi,j as aC,k as iC,l as sC,n as Af,o as cC,q as dC,r as Vl,s as Rk,v as Cf,x as xk,y as lC,z as uC}from"./chunk-PRGBLQVH.js";import{d as Pc,e as Wl,f as tC,g as rC,h as nC,j as Ik,l as Sk}from"./chunk-7E6T7GP5.js";import"./chunk-DZUAT3TP.js";import{b as X0,k as Z0,n as eC}from"./chunk-XDQMGUWL.js";import{B as vf,D as kc,a as uf,b as Ui,c as v0,h as b0,i as hr,k as gf,u as wf,v as lk,w as I0,x as S0,y as yf,z as P0}from"./chunk-FTEOCCPB.js";import{$a as wk,Aa as bf,Ab as Ha,Ba as kf,Bb as z0,C as u0,Ca as uk,Cb as W0,Da as pk,Db as _r,E as bc,Ea as _0,Fb as Q0,Ga as T0,Ha as E0,Ib as Da,J as p0,Ja as If,Ka as A0,L as m0,Ma as C0,N as f0,Oa as M0,P as h0,Q as g0,Ra as Sf,Ta as Pf,Ua as Rf,Va as Ic,Wa as mk,Xa as fk,Y as w0,Ya as xf,Za as hk,_a as gk,ab as yk,bb as vk,c as QA,ca as ja,cb as bk,da as zl,i as ZA,ja as ff,jb as j0,ka as y0,kb as O0,l as n0,la as Ze,lb as Sc,m as o0,mb as H0,n as a0,nb as D0,o as i0,ob as _f,p as s0,pb as Tf,q as mf,qb as Ef,r as dk,rb as L0,s as c0,sb as kk,t as d0,tb as B0,u as l0,ua as Oa,va as k0,vb as $0,wa as hf,wb as N0,xa as _n,xb as U0,ya as R0,yb as q0,za as x0,zb as F0}from"./chunk-25MBPJVY.js";import{e as ik,l as ao}from"./chunk-WN3V6KDN.js";import{A as Fl,C as t0,D as pf,G as r0,K as ck,L as Ma,b as sk,i as nr,j as ql,n as en,u as e0}from"./chunk-523TE4BI.js";import"./chunk-ZCHXGRRU.js";import"./chunk-FWIPHEVA.js";import{b as QE,c as eA}from"./chunk-QDC4OW3S.js";import"./chunk-ZZWAQBA2.js";import{g as XA}from"./chunk-YR5ID2SS.js";import{b as ZE,e as tA}from"./chunk-YBT2NB32.js";import{k as Lb}from"./chunk-74ZXXBGN.js";import"./chunk-APB2STJK.js";import{C as $A,D as NA,I as FA,K as rk,L as nk,M as zA,S as ok,U as WA,V as ak,Z as VA,_ as GA,ca as JA,da as KA,f as $l,fa as Ni,ga as YA,ha as lf,v as vc,x as Ul}from"./chunk-I7AQMAQI.js";import{M as yc,O as HA,Q as DA,R as LA,S as BA,a as $i,b as xA,c as Nl,d as xn,e as _A,f as of,g as TA,h as EA,i as af,j as sf,l as AA,m as CA,n as MA,o as jA,p as OA,z as tk}from"./chunk-Z4Z5UOZM.js";import{a as Gl}from"./chunk-6FA3GG5B.js";import{Ba as fA,Ua as hA,Wa as tf,ba as rA,bb as Xb,d as OE,db as gA,f as Qm,fb as wA,gb as rf,hb as yA,l as HE,lb as vA,m as DE,ob as bA,pa as nA,sb as Qb,ub as Zb,va as mA,wb as kA,x as LE,xb as IA,yb as SA,zb as ek}from"./chunk-Y4OWBBDD.js";import{A as iA,E as sA,F as cA,G as Li,H as dA,I as lA,J as uA,N as pA,h as oA,z as aA}from"./chunk-6ZFPQYHG.js";import"./chunk-JFXWI3EN.js";import{b as rE,d as Bm,e as Rn,f as rr}from"./chunk-FFRFSDBM.js";import{$ as zE,Ab as wc,Fb as JE,H as qE,Hb as KE,Mb as YE,N as We,O as xt,Q as FE,Ra as ef,Tb as XE,b as xE,ba as Zm,d as Zr,g as BE,j as $E,kb as WE,l as NE,lb as Ca,m as UE,mb as pt,nb as VE,qb as GE,yb as gc,zb as $o}from"./chunk-VYLGI3IH.js";import{$ as Gb,Aa as PE,Ab as AE,Bb as CE,Cb as ME,D as hE,Db as jE,E as Fm,Ea as RE,F as zm,G as Wm,H as Vm,Ja as Km,K as Gm,L as Ub,La as Ll,M as Hi,N as Di,P as gE,R as wE,S as yE,Va as Ym,W as qb,Wa as _E,X as Fb,Y as zb,Z as Wb,_ as Vb,_a as Yb,a as aE,aa as Jb,ba as Kb,db as TE,ea as vE,fb as EE,h as _e,ib as Xm,l as Aa,oa as bE,qa as kE,ta as IE,v as mE,wa as Jm,x as fE,za as SE}from"./chunk-ACYFMLWG.js";import{q as nE,r as Ea}from"./chunk-TVQAPBLZ.js";import{f as eE,g as Db,h as tE,k as ot,l as Re,m as A,n as Lm}from"./chunk-KGNCKIFP.js";import{a as Nt,b}from"./chunk-ES2ISFJC.js";import{a as PA,c as Bi,f as nf,h as Bl,i as RA,n as cf,o as UA,p as No,q as qA,r as Uo,s as df}from"./chunk-H7IWJN7L.js";import{a as i,b as He,c as Ce,e as Qr}from"./chunk-FTQLQJQV.js";var Ko=Ce((JSe,$B)=>{"use strict";var LB=["nodebuffer","arraybuffer","fragments"],BB=typeof Blob<"u";BB&&LB.push("blob");$B.exports={BINARY_TYPES:LB,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:BB,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:i(()=>{},"NOOP")}});var Ru=Ce((YSe,ag)=>{"use strict";var{EMPTY_BUFFER:ZY}=Ko(),OI=Buffer[Symbol.species];function eX(e,t){if(e.length===0)return ZY;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let a=e[o];r.set(a,n),n+=a.length}return n<t?new OI(r.buffer,r.byteOffset,n):r}i(eX,"concat");function NB(e,t,r,n,o){for(let a=0;a<o;a++)r[n+a]=e[a]^t[a&3]}i(NB,"_mask");function UB(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}i(UB,"_unmask");function tX(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}i(tX,"toArrayBuffer");function HI(e){if(HI.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new OI(e):ArrayBuffer.isView(e)?t=new OI(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),HI.readOnly=!1),t}i(HI,"toBuffer");ag.exports={concat:eX,mask:NB,toArrayBuffer:tX,toBuffer:HI,unmask:UB};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=He("bufferutil");ag.exports.mask=function(t,r,n,o,a){a<48?NB(t,r,n,o,a):e.mask(t,r,n,o,a)},ag.exports.unmask=function(t,r){t.length<32?UB(t,r):e.unmask(t,r)}}catch{}});var zB=Ce((QSe,FB)=>{"use strict";var qB=Symbol("kDone"),DI=Symbol("kRun"),LI=class{static{i(this,"Limiter")}constructor(t){this[qB]=()=>{this.pending--,this[DI]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[DI]()}[DI](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[qB])}}};FB.exports=LI});var nd=Ce((ePe,JB)=>{"use strict";var xu=He("zlib"),WB=Ru(),rX=zB(),{kStatusCode:VB}=Ko(),nX=Buffer[Symbol.species],oX=Buffer.from([0,0,255,255]),sg=Symbol("permessage-deflate"),Yo=Symbol("total-length"),td=Symbol("callback"),Qa=Symbol("buffers"),rd=Symbol("error"),ig,BI=class{static{i(this,"PerMessageDeflate")}constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ig){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ig=new rX(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[td];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,n=t.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let a=+o;if(!Number.isInteger(a)||a<8||a>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=a}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),t}decompress(t,r,n){ig.add(o=>{this._decompress(t,r,(a,s)=>{o(),n(a,s)})})}compress(t,r,n){ig.add(o=>{this._compress(t,r,(a,s)=>{o(),n(a,s)})})}_decompress(t,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?xu.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=xu.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[sg]=this,this._inflate[Yo]=0,this._inflate[Qa]=[],this._inflate.on("error",iX),this._inflate.on("data",GB)}this._inflate[td]=n,this._inflate.write(t),r&&this._inflate.write(oX),this._inflate.flush(()=>{let a=this._inflate[rd];if(a){this._inflate.close(),this._inflate=null,n(a);return}let s=WB.concat(this._inflate[Qa],this._inflate[Yo]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Yo]=0,this._inflate[Qa]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,s)})}_compress(t,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let a=`${o}_max_window_bits`,s=typeof this.params[a]!="number"?xu.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=xu.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Yo]=0,this._deflate[Qa]=[],this._deflate.on("data",aX)}this._deflate[td]=n,this._deflate.write(t),this._deflate.flush(xu.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=WB.concat(this._deflate[Qa],this._deflate[Yo]);r&&(a=new nX(a.buffer,a.byteOffset,a.length-4)),this._deflate[td]=null,this._deflate[Yo]=0,this._deflate[Qa]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,a)})}};JB.exports=BI;function aX(e){this[Qa].push(e),this[Yo]+=e.length}i(aX,"deflateOnData");function GB(e){if(this[Yo]+=e.length,this[sg]._maxPayload<1||this[Yo]<=this[sg]._maxPayload){this[Qa].push(e);return}this[rd]=new RangeError("Max payload size exceeded"),this[rd].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rd][VB]=1009,this.removeListener("data",GB),this.reset()}i(GB,"inflateOnData");function iX(e){if(this[sg]._inflate=null,this[rd]){this[td](this[rd]);return}e[VB]=1007,this[td](e)}i(iX,"inflateOnError")});var od=Ce((rPe,cg)=>{"use strict";var{isUtf8:KB}=He("buffer"),{hasBlob:sX}=Ko(),cX=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function dX(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}i(dX,"isValidStatusCode");function $I(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}i($I,"_isValidUTF8");function lX(e){return sX&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}i(lX,"isBlob");cg.exports={isBlob:lX,isValidStatusCode:dX,isValidUTF8:$I,tokenChars:cX};if(KB)cg.exports.isValidUTF8=function(e){return e.length<24?$I(e):KB(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=He("utf-8-validate");cg.exports.isValidUTF8=function(t){return t.length<32?$I(t):e(t)}}catch{}});var zI=Ce((oPe,r$)=>{"use strict";var{Writable:uX}=He("stream"),YB=nd(),{BINARY_TYPES:pX,EMPTY_BUFFER:XB,kStatusCode:mX,kWebSocket:fX}=Ko(),{concat:NI,toArrayBuffer:hX,unmask:gX}=Ru(),{isValidStatusCode:wX,isValidUTF8:QB}=od(),dg=Buffer[Symbol.species],an=0,ZB=1,e$=2,t$=3,UI=4,qI=5,lg=6,FI=class extends uX{static{i(this,"Receiver")}constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||pX[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[fX]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=an}_write(t,r,n){if(this._opcode===8&&this._state==an)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(n)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new dg(n.buffer,n.byteOffset+t,n.length-t),new dg(n.buffer,n.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let n=this._buffers[0],o=r.length-t;t>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,t),o),this._buffers[0]=new dg(n.buffer,n.byteOffset+t,n.length-t)),t-=n.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case an:this.getInfo(t);break;case ZB:this.getPayloadLength16(t);break;case e$:this.getPayloadLength64(t);break;case t$:this.getMask();break;case UI:this.getData(t);break;case qI:case lg:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[YB.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=ZB:this._payloadLength===127?this._state=e$:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=t$:this._state=UI}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=UI}getData(t){let r=XB;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&gX(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(n);return}if(this._compressed){this._state=qI,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[YB.extensionName].decompress(t,this._fin,(o,a)=>{if(o)return r(o);if(a.length){if(this._messageLength+=a.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(s);return}this._fragments.push(a)}this.dataMessage(r),this._state===an&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=an;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=NI(n,r):this._binaryType==="arraybuffer"?o=hX(NI(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=an):(this._state=lg,setImmediate(()=>{this.emit("message",o,!0),this._state=an,this.startLoop(t)}))}else{let o=NI(n,r);if(!this._skipUTF8Validation&&!QB(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(a);return}this._state===qI||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=an):(this._state=lg,setImmediate(()=>{this.emit("message",o,!1),this._state=an,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,XB),this.end();else{let n=t.readUInt16BE(0);if(!wX(n)){let a=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(a);return}let o=new dg(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!QB(o)){let a=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(a);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=an;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=an):(this._state=lg,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=an,this.startLoop(r)}))}createError(t,r,n,o,a){this._loop=!1,this._errored=!0;let s=new t(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(s,this.createError),s.code=a,s[mX]=o,s}};r$.exports=FI});var GI=Ce((sPe,a$)=>{"use strict";var{Duplex:iPe}=He("stream"),{randomFillSync:yX}=He("crypto"),{types:{isUint8Array:vX}}=He("util"),n$=nd(),{EMPTY_BUFFER:bX,kWebSocket:kX,NOOP:IX}=Ko(),{isBlob:ad,isValidStatusCode:SX}=od(),{mask:o$,toBuffer:os}=Ru(),sn=Symbol("kByteLength"),PX=Buffer.alloc(4),ug=8*1024,as,id=ug,Dn=0,RX=1,xX=2,WI=class e{static{i(this,"Sender")}constructor(t,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Dn,this.onerror=IX,this[kX]=void 0}static frame(t,r){let n,o=!1,a=2,s=!1;r.mask&&(n=r.maskBuffer||PX,r.generateMask?r.generateMask(n):(id===ug&&(as===void 0&&(as=Buffer.alloc(ug)),yX(as,0,ug),id=0),n[0]=as[id++],n[1]=as[id++],n[2]=as[id++],n[3]=as[id++]),s=(n[0]|n[1]|n[2]|n[3])===0,a=6);let c;typeof t=="string"?(!r.mask||s)&&r[sn]!==void 0?c=r[sn]:(t=Buffer.from(t),c=t.length):(c=t.length,o=r.mask&&r.readOnly&&!s);let d=c;c>=65536?(a+=8,d=127):c>125&&(a+=2,d=126);let l=Buffer.allocUnsafe(o?c+a:a);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=d,d===126?l.writeUInt16BE(c,2):d===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),r.mask?(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],s?[l,t]:o?(o$(t,n,l,a,c),[l]):(o$(t,n,t,0,c),[l,t])):[l,t]}close(t,r,n,o){let a;if(t===void 0)a=bX;else{if(typeof t!="number"||!SX(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(a=Buffer.allocUnsafe(2+c),a.writeUInt16BE(t,0),typeof r=="string")a.write(r,2);else if(vX(r))a.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[sn]:a.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Dn?this.enqueue([this.dispatch,a,!1,s,o]):this.sendFrame(e.frame(a,s),o)}ping(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):ad(t)?(o=t.size,a=!1):(t=os(t),o=t.length,a=os.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[sn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};ad(t)?this._state!==Dn?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==Dn?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}pong(t,r,n){let o,a;if(typeof t=="string"?(o=Buffer.byteLength(t),a=!1):ad(t)?(o=t.size,a=!1):(t=os(t),o=t.length,a=os.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[sn]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};ad(t)?this._state!==Dn?this.enqueue([this.getBlobData,t,!1,s,n]):this.getBlobData(t,!1,s,n):this._state!==Dn?this.enqueue([this.dispatch,t,!1,s,n]):this.sendFrame(e.frame(t,s),n)}send(t,r,n){let o=this._extensions[n$.extensionName],a=r.binary?2:1,s=r.compress,c,d;typeof t=="string"?(c=Buffer.byteLength(t),d=!1):ad(t)?(c=t.size,d=!1):(t=os(t),c=t.length,d=os.readOnly),this._firstFragment?(this._firstFragment=!1,s&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=c>=o._threshold),this._compress=s):(s=!1,a=0),r.fin&&(this._firstFragment=!0);let l={[sn]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:d,rsv1:s};ad(t)?this._state!==Dn?this.enqueue([this.getBlobData,t,this._compress,l,n]):this.getBlobData(t,this._compress,l,n):this._state!==Dn?this.enqueue([this.dispatch,t,this._compress,l,n]):this.dispatch(t,this._compress,l,n)}getBlobData(t,r,n,o){this._bufferedBytes+=n[sn],this._state=xX,t.arrayBuffer().then(a=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(VI,this,c,o);return}this._bufferedBytes-=n[sn];let s=os(a);r?this.dispatch(s,r,n,o):(this._state=Dn,this.sendFrame(e.frame(s,n),o),this.dequeue())}).catch(a=>{process.nextTick(_X,this,a,o)})}dispatch(t,r,n,o){if(!r){this.sendFrame(e.frame(t,n),o);return}let a=this._extensions[n$.extensionName];this._bufferedBytes+=n[sn],this._state=RX,a.compress(t,n.fin,(s,c)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");VI(this,d,o);return}this._bufferedBytes-=n[sn],this._state=Dn,n.readOnly=!1,this.sendFrame(e.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===Dn&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][sn],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][sn],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};a$.exports=WI;function VI(e,t,r){typeof r=="function"&&r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],a=o[o.length-1];typeof a=="function"&&a(t)}}i(VI,"callCallbacks");function _X(e,t,r){VI(e,t,r),e.onerror(t)}i(_X,"onError")});var f$=Ce((dPe,m$)=>{"use strict";var{kForOnEventAttribute:_u,kListener:JI}=Ko(),i$=Symbol("kCode"),s$=Symbol("kData"),c$=Symbol("kError"),d$=Symbol("kMessage"),l$=Symbol("kReason"),sd=Symbol("kTarget"),u$=Symbol("kType"),p$=Symbol("kWasClean"),Xo=class{static{i(this,"Event")}constructor(t){this[sd]=null,this[u$]=t}get target(){return this[sd]}get type(){return this[u$]}};Object.defineProperty(Xo.prototype,"target",{enumerable:!0});Object.defineProperty(Xo.prototype,"type",{enumerable:!0});var is=class extends Xo{static{i(this,"CloseEvent")}constructor(t,r={}){super(t),this[i$]=r.code===void 0?0:r.code,this[l$]=r.reason===void 0?"":r.reason,this[p$]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[i$]}get reason(){return this[l$]}get wasClean(){return this[p$]}};Object.defineProperty(is.prototype,"code",{enumerable:!0});Object.defineProperty(is.prototype,"reason",{enumerable:!0});Object.defineProperty(is.prototype,"wasClean",{enumerable:!0});var cd=class extends Xo{static{i(this,"ErrorEvent")}constructor(t,r={}){super(t),this[c$]=r.error===void 0?null:r.error,this[d$]=r.message===void 0?"":r.message}get error(){return this[c$]}get message(){return this[d$]}};Object.defineProperty(cd.prototype,"error",{enumerable:!0});Object.defineProperty(cd.prototype,"message",{enumerable:!0});var Tu=class extends Xo{static{i(this,"MessageEvent")}constructor(t,r={}){super(t),this[s$]=r.data===void 0?null:r.data}get data(){return this[s$]}};Object.defineProperty(Tu.prototype,"data",{enumerable:!0});var TX={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[_u]&&o[JI]===t&&!o[_u])return;let n;if(e==="message")n=i(function(a,s){let c=new Tu("message",{data:s?a:a.toString()});c[sd]=this,pg(t,this,c)},"onMessage");else if(e==="close")n=i(function(a,s){let c=new is("close",{code:a,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[sd]=this,pg(t,this,c)},"onClose");else if(e==="error")n=i(function(a){let s=new cd("error",{error:a,message:a.message});s[sd]=this,pg(t,this,s)},"onError");else if(e==="open")n=i(function(){let a=new Xo("open");a[sd]=this,pg(t,this,a)},"onOpen");else return;n[_u]=!!r[_u],n[JI]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[JI]===t&&!r[_u]){this.removeListener(e,r);break}}};m$.exports={CloseEvent:is,ErrorEvent:cd,Event:Xo,EventTarget:TX,MessageEvent:Tu};function pg(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}i(pg,"callListener")});var mg=Ce((uPe,h$)=>{"use strict";var{tokenChars:Eu}=od();function go(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}i(go,"push");function EX(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,a=!1,s,c,d=-1,l=-1,u=-1,p=0;for(;p<e.length;p++)if(l=e.charCodeAt(p),s===void 0)if(u===-1&&Eu[l]===1)d===-1&&(d=p);else if(p!==0&&(l===32||l===9))u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let w=e.slice(d,u);l===44?(go(t,w,r),r=Object.create(null)):s=w,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(c===void 0)if(u===-1&&Eu[l]===1)d===-1&&(d=p);else if(l===32||l===9)u===-1&&d!==-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),go(r,e.slice(d,u),!0),l===44&&(go(t,s,r),r=Object.create(null),s=void 0),d=u=-1}else if(l===61&&d!==-1&&u===-1)c=e.slice(d,p),d=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Eu[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1?d=p:n||(n=!0),o=!1}else if(a)if(Eu[l]===1)d===-1&&(d=p);else if(l===34&&d!==-1)a=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&e.charCodeAt(p-1)===61)a=!0;else if(u===-1&&Eu[l]===1)d===-1&&(d=p);else if(d!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let w=e.slice(d,u);n&&(w=w.replace(/\\/g,""),n=!1),go(r,c,w),l===44&&(go(t,s,r),r=Object.create(null),s=void 0),c=void 0,d=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(d===-1||a||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let m=e.slice(d,u);return s===void 0?go(t,m,r):(c===void 0?go(r,m,!0):n?go(r,c,m.replace(/\\/g,"")):go(r,c,m),go(t,s,r)),t}i(EX,"parse");function AX(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(n=>[t].concat(Object.keys(n).map(o=>{let a=n[o];return Array.isArray(a)||(a=[a]),a.map(s=>s===!0?o:`${o}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}i(AX,"format");h$.exports={format:AX,parse:EX}});var wg=Ce((hPe,_$)=>{"use strict";var CX=He("events"),MX=He("https"),jX=He("http"),y$=He("net"),OX=He("tls"),{randomBytes:HX,createHash:DX}=He("crypto"),{Duplex:mPe,Readable:fPe}=He("stream"),{URL:KI}=He("url"),Za=nd(),LX=zI(),BX=GI(),{isBlob:$X}=od(),{BINARY_TYPES:g$,CLOSE_TIMEOUT:NX,EMPTY_BUFFER:fg,GUID:UX,kForOnEventAttribute:YI,kListener:qX,kStatusCode:FX,kWebSocket:Tt,NOOP:v$}=Ko(),{EventTarget:{addEventListener:zX,removeEventListener:WX}}=f$(),{format:VX,parse:GX}=mg(),{toBuffer:JX}=Ru(),b$=Symbol("kAborted"),XI=[8,13],Qo=["CONNECTING","OPEN","CLOSING","CLOSED"],KX=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ct=class e extends CX{static{i(this,"WebSocket")}constructor(t,r,n){super(),this._binaryType=g$[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=fg,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),k$(this,t,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){g$.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){let o=new LX({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),a=new BX(t,this._extensions,n.generateMask);this._receiver=o,this._sender=a,this._socket=t,o[Tt]=this,a[Tt]=this,t[Tt]=this,o.on("conclude",QX),o.on("drain",ZX),o.on("error",eQ),o.on("message",tQ),o.on("ping",rQ),o.on("pong",nQ),a.onerror=oQ,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",P$),t.on("data",gg),t.on("end",R$),t.on("error",x$),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Za.extensionName]&&this._extensions[Za.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){$r(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),S$(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){QI(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||fg,r,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){QI(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||fg,r,n)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){QI(this,t,n);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Za.extensionName]||(o.compress=!1),this._sender.send(t||fg,o,n)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){$r(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(ct,"CONNECTING",{enumerable:!0,value:Qo.indexOf("CONNECTING")});Object.defineProperty(ct.prototype,"CONNECTING",{enumerable:!0,value:Qo.indexOf("CONNECTING")});Object.defineProperty(ct,"OPEN",{enumerable:!0,value:Qo.indexOf("OPEN")});Object.defineProperty(ct.prototype,"OPEN",{enumerable:!0,value:Qo.indexOf("OPEN")});Object.defineProperty(ct,"CLOSING",{enumerable:!0,value:Qo.indexOf("CLOSING")});Object.defineProperty(ct.prototype,"CLOSING",{enumerable:!0,value:Qo.indexOf("CLOSING")});Object.defineProperty(ct,"CLOSED",{enumerable:!0,value:Qo.indexOf("CLOSED")});Object.defineProperty(ct.prototype,"CLOSED",{enumerable:!0,value:Qo.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(ct.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(ct.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[YI])return t[qX];return null},set(t){for(let r of this.listeners(e))if(r[YI]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[YI]:!0})}})});ct.prototype.addEventListener=zX;ct.prototype.removeEventListener=WX;_$.exports=ct;function k$(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:NX,protocolVersion:XI[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!XI.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${XI.join(", ")})`);let a;if(t instanceof KI)a=t;else try{a=new KI(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}a.protocol==="http:"?a.protocol="ws:":a.protocol==="https:"&&(a.protocol="wss:"),e._url=a.href;let s=a.protocol==="wss:",c=a.protocol==="ws+unix:",d;if(a.protocol!=="ws:"&&!s&&!c?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!a.pathname?d="The URL's pathname is empty":a.hash&&(d="The URL contains a fragment identifier"),d){let f=new SyntaxError(d);if(e._redirects===0)throw f;hg(e,f);return}let l=s?443:80,u=HX(16).toString("base64"),p=s?MX.request:jX.request,m=new Set,w;if(o.createConnection=o.createConnection||(s?XX:YX),o.defaultPort=o.defaultPort||l,o.port=a.port||l,o.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=a.pathname+a.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(w=new Za({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=VX({[Za.extensionName]:w.offer()})),r.length){for(let f of r){if(typeof f!="string"||!KX.test(f)||m.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(f)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(a.username||a.password)&&(o.auth=`${a.username}:${a.password}`),c){let f=o.path.split(":");o.socketPath=f[0],o.path=f[1]}let g;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=s,e._originalHostOrSocketPath=c?o.socketPath:a.host;let f=n&&n.headers;if(n={...n,headers:{}},f)for(let[y,h]of Object.entries(f))n.headers[y.toLowerCase()]=h}else if(e.listenerCount("redirect")===0){let f=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:a.host===e._originalHostOrSocketPath;(!f||e._originalSecure&&!s)&&(delete o.headers.authorization,delete o.headers.cookie,f||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),g=e._req=p(o),e._redirects&&e.emit("redirect",e.url,g)}else g=e._req=p(o);o.timeout&&g.on("timeout",()=>{$r(e,g,"Opening handshake has timed out")}),g.on("error",f=>{g===null||g[b$]||(g=e._req=null,hg(e,f))}),g.on("response",f=>{let y=f.headers.location,h=f.statusCode;if(y&&o.followRedirects&&h>=300&&h<400){if(++e._redirects>o.maxRedirects){$r(e,g,"Maximum redirects exceeded");return}g.abort();let k;try{k=new KI(y,t)}catch{let I=new SyntaxError(`Invalid URL: ${y}`);hg(e,I);return}k$(e,k,r,n)}else e.emit("unexpected-response",g,f)||$r(e,g,`Unexpected server response: ${f.statusCode}`)}),g.on("upgrade",(f,y,h)=>{if(e.emit("upgrade",f),e.readyState!==ct.CONNECTING)return;g=e._req=null;let k=f.headers.upgrade;if(k===void 0||k.toLowerCase()!=="websocket"){$r(e,y,"Invalid Upgrade header");return}let S=DX("sha1").update(u+UX).digest("base64");if(f.headers["sec-websocket-accept"]!==S){$r(e,y,"Invalid Sec-WebSocket-Accept header");return}let I=f.headers["sec-websocket-protocol"],v;if(I!==void 0?m.size?m.has(I)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":m.size&&(v="Server sent no subprotocol"),v){$r(e,y,v);return}I&&(e._protocol=I);let R=f.headers["sec-websocket-extensions"];if(R!==void 0){if(!w){$r(e,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=GX(R)}catch{$r(e,y,"Invalid Sec-WebSocket-Extensions header");return}let P=Object.keys(T);if(P.length!==1||P[0]!==Za.extensionName){$r(e,y,"Server indicated an extension that was not requested");return}try{w.accept(T[Za.extensionName])}catch{$r(e,y,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[Za.extensionName]=w}e.setSocket(y,h,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(g,e):g.end()}i(k$,"initAsClient");function hg(e,t){e._readyState=ct.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}i(hg,"emitErrorAndClose");function YX(e){return e.path=e.socketPath,y$.connect(e)}i(YX,"netConnect");function XX(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=y$.isIP(e.host)?"":e.host),OX.connect(e)}i(XX,"tlsConnect");function $r(e,t,r){e._readyState=ct.CLOSING;let n=new Error(r);Error.captureStackTrace(n,$r),t.setHeader?(t[b$]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(hg,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}i($r,"abortHandshake");function QI(e,t,r){if(t){let n=$X(t)?t.size:JX(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${e.readyState} (${Qo[e.readyState]})`);process.nextTick(r,n)}}i(QI,"sendAfterClose");function QX(e,t){let r=this[Tt];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[Tt]!==void 0&&(r._socket.removeListener("data",gg),process.nextTick(I$,r._socket),e===1005?r.close():r.close(e,t))}i(QX,"receiverOnConclude");function ZX(){let e=this[Tt];e.isPaused||e._socket.resume()}i(ZX,"receiverOnDrain");function eQ(e){let t=this[Tt];t._socket[Tt]!==void 0&&(t._socket.removeListener("data",gg),process.nextTick(I$,t._socket),t.close(e[FX])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}i(eQ,"receiverOnError");function w$(){this[Tt].emitClose()}i(w$,"receiverOnFinish");function tQ(e,t){this[Tt].emit("message",e,t)}i(tQ,"receiverOnMessage");function rQ(e){let t=this[Tt];t._autoPong&&t.pong(e,!this._isServer,v$),t.emit("ping",e)}i(rQ,"receiverOnPing");function nQ(e){this[Tt].emit("pong",e)}i(nQ,"receiverOnPong");function I$(e){e.resume()}i(I$,"resume");function oQ(e){let t=this[Tt];t.readyState!==ct.CLOSED&&(t.readyState===ct.OPEN&&(t._readyState=ct.CLOSING,S$(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}i(oQ,"senderOnError");function S$(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}i(S$,"setCloseTimer");function P$(){let e=this[Tt];if(this.removeListener("close",P$),this.removeListener("data",gg),this.removeListener("end",R$),e._readyState=ct.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[Tt]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",w$),e._receiver.on("finish",w$))}i(P$,"socketOnClose");function gg(e){this[Tt]._receiver.write(e)||this.pause()}i(gg,"socketOnData");function R$(){let e=this[Tt];e._readyState=ct.CLOSING,e._receiver.end(),this.end()}i(R$,"socketOnEnd");function x$(){let e=this[Tt];this.removeListener("error",x$),this.on("error",v$),e&&(e._readyState=ct.CLOSING,this.destroy())}i(x$,"socketOnError")});var C$=Ce((yPe,A$)=>{"use strict";var wPe=wg(),{Duplex:aQ}=He("stream");function T$(e){e.emit("close")}i(T$,"emitClose");function iQ(){!this.destroyed&&this._writableState.finished&&this.destroy()}i(iQ,"duplexOnEnd");function E$(e){this.removeListener("error",E$),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}i(E$,"duplexOnError");function sQ(e,t){let r=!0,n=new aQ({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",i(function(a,s){let c=!s&&n._readableState.objectMode?a.toString():a;n.push(c)||e.pause()},"message")),e.once("error",i(function(a){n.destroyed||(r=!1,n.destroy(a))},"error")),e.once("close",i(function(){n.destroyed||n.push(null)},"close")),n._destroy=function(o,a){if(e.readyState===e.CLOSED){a(o),process.nextTick(T$,n);return}let s=!1;e.once("error",i(function(d){s=!0,a(d)},"error")),e.once("close",i(function(){s||a(o),process.nextTick(T$,n)},"close")),r&&e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._final(o)},"open"));return}e._socket!==null&&(e._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",i(function(){o()},"finish")),e.close()))},n._read=function(){e.isPaused&&e.resume()},n._write=function(o,a,s){if(e.readyState===e.CONNECTING){e.once("open",i(function(){n._write(o,a,s)},"open"));return}e.send(o,s)},n.on("end",iQ),n.on("error",E$),n}i(sQ,"createWebSocketStream");A$.exports=sQ});var ZI=Ce((bPe,M$)=>{"use strict";var{tokenChars:cQ}=od();function dQ(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let s=e.charCodeAt(o);if(n===-1&&cQ[s]===1)r===-1&&(r=o);else if(o!==0&&(s===32||s===9))n===-1&&r!==-1&&(n=o);else if(s===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=e.slice(r,n);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let a=e.slice(r,o);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);return t.add(a),t}i(dQ,"parse");M$.exports={parse:dQ}});var $$=Ce((SPe,B$)=>{"use strict";var lQ=He("events"),yg=He("http"),{Duplex:IPe}=He("stream"),{createHash:uQ}=He("crypto"),j$=mg(),ss=nd(),pQ=ZI(),mQ=wg(),{CLOSE_TIMEOUT:fQ,GUID:hQ,kWebSocket:gQ}=Ko(),wQ=/^[+/0-9A-Za-z]{22}==$/,O$=0,H$=1,L$=2,eS=class extends lQ{static{i(this,"WebSocketServer")}constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:fQ,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:mQ,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=yg.createServer((n,o)=>{let a=yg.STATUS_CODES[426];o.writeHead(426,{"Content-Length":a.length,"Content-Type":"text/plain"}),o.end(a)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=yQ(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:i((o,a,s)=>{this.handleUpgrade(o,a,s,n)},"upgrade")})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=O$}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===L$){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Au,this);return}if(t&&this.once("close",t),this._state!==H$)if(this._state=H$,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Au,this):process.nextTick(Au,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Au(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,n,o){r.on("error",D$);let a=t.headers["sec-websocket-key"],s=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){cs(this,t,r,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){cs(this,t,r,400,"Invalid Upgrade header");return}if(a===void 0||!wQ.test(a)){cs(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){cs(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Cu(r,400);return}let d=t.headers["sec-websocket-protocol"],l=new Set;if(d!==void 0)try{l=pQ.parse(d)}catch{cs(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=t.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let m=new ss({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=j$.parse(u);w[ss.extensionName]&&(m.accept(w[ss.extensionName]),p[ss.extensionName]=m)}catch{cs(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(w,g,f,y)=>{if(!w)return Cu(r,g||401,f,y);this.completeUpgrade(p,a,l,t,r,n,o)});return}if(!this.options.verifyClient(m))return Cu(r,401)}this.completeUpgrade(p,a,l,t,r,n,o)}completeUpgrade(t,r,n,o,a,s,c){if(!a.readable||!a.writable)return a.destroy();if(a[gQ])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>O$)return Cu(a,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${uQ("sha1").update(r+hQ).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(t[ss.extensionName]){let p=t[ss.extensionName].params,m=j$.format({[ss.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),u._extensions=t}this.emit("headers",l,o),a.write(l.concat(`\r
|
|
4
4
|
`).join(`\r
|
|
5
5
|
`)),a.removeListener("error",D$),u.setSocket(a,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Au,this)})),c(u,o)}};B$.exports=eS;function yQ(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return i(function(){for(let n of Object.keys(t))e.removeListener(n,t[n])},"removeListeners")}i(yQ,"addListeners");function Au(e){e._state=L$,e.emit("close")}i(Au,"emitClose");function D$(){this.destroy()}i(D$,"socketOnError");function Cu(e,t,r,n){r=r||yg.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${yg.STATUS_CODES[t]}\r
|
|
6
6
|
`+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
|
|
@@ -10,7 +10,7 @@ import{a as BL,b as $L,c as NL}from"./chunk-2D4Y3HNW.js";import{a as cL,b as dL,
|
|
|
10
10
|
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, call_key TEXT NOT NULL UNIQUE, payload TEXT NOT NULL);
|
|
11
11
|
CREATE INDEX IF NOT EXISTS html_visual_session ON html_visual_publications(session_id);`),r(n)))}return i(t,"db"),{get(r){return t(n=>{let o=n.prepare("SELECT payload FROM html_visual_publications WHERE id=?").get(r);return o?JSON.parse(o.payload):null})},byCall(r){return t(n=>{let o=n.prepare("SELECT payload FROM html_visual_publications WHERE call_key=?").get(r);return o?JSON.parse(o.payload):null})},list(r){return t(n=>(r?n.prepare("SELECT payload FROM html_visual_publications WHERE session_id=?").all(r):n.prepare("SELECT payload FROM html_visual_publications").all()).map(o=>JSON.parse(o.payload)))},save(r){t(n=>{n.prepare("INSERT INTO html_visual_publications VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload").run(r.reference.publicationId,r.reference.sessionId,r.callKey,JSON.stringify(r))})},delete(r){t(n=>{n.prepare("DELETE FROM html_visual_publications WHERE id=?").run(r)})}}}i(WL,"createVisualStore");var VL=i(e=>yY("sha256").update(e).digest("hex"),"digest"),vu=i((e,t="html")=>({domain:"chat_attachment",id:`html-visual:${e}:${t}`}),"owner");function GL(e){let t=WL(e.home),r=new Map,n=0,o=new Map;async function a(d,l){let u=(o.get(d)??Promise.resolve()).catch(()=>{}).then(l);o.set(d,u);try{return await u}finally{o.get(d)===u&&o.delete(d)}}i(a,"locked");async function s(d){if(d.ready)return d.reference;let l=d.reference;if(!await e.getSession(l.sessionId))throw new Error("Visual conversation is unavailable.");d.document!==null&&await ok(e.home,{owner:vu(l.publicationId),displayName:`${l.output.title}.html`,mediaType:"text/html",bytes:Buffer.from(d.document)}),d.screenshot!==null&&await ok(e.home,{owner:vu(l.publicationId,"png"),displayName:"Preview.png",mediaType:"image/png",bytes:Buffer.from(d.screenshot,"base64")});let u=l.publicationId;return(await e.events(l.sessionId)).some(p=>p.id===u)||await e.append({id:u,sessionId:l.sessionId,turnId:l.turnId,name:"visual.published",timestamp:l.output.createdAt,source:"server",data:{visual:l}}),t.save({...d,document:null,screenshot:null,ready:!0}),l}i(s,"finish");async function c(d){await ak(e.home,vu(d.reference.publicationId)),await ak(e.home,vu(d.reference.publicationId,"png")),t.delete(d.reference.publicationId)}return i(c,"release"),{available(){return!!e.executor.previewHtml&&e.executor.visualAvailable?.()===!0},async recover(){for(let d of t.list()){if(!await e.getSession(d.reference.sessionId)){await c(d);continue}d.ready||await a(d.reference.sessionId,()=>s(d))}},async preview(d,l){let u=pD.parse(l);if(!e.executor.previewHtml||!e.executor.visualAvailable?.())throw new Error("This desktop does not support HTML previews.");d.signal.throwIfAborted();for(let[p,m]of r)m.expires<Date.now()&&r.delete(p);if(r.size+n>=16)throw new Error("There are too many draft visuals. Finish an existing preview or retry after drafts expire.");n++;try{let p=await zL(u.html,u.assets,d.session.cwd),m=await e.executor.previewHtml({...d,sessionId:d.session.id,conversationId:d.session.id,html:p,width:u.width});if(!m.ok)throw new Error(m.output);let w=fD.parse(m.data);d.signal.throwIfAborted();let g=vY(),f=VL(p);return r.set(g,{sessionId:d.session.id,html:p,sha256:f,capture:w,expires:Date.now()+15*6e4}),{previewId:g,sha256:f,heights:w.heights,console:w.console,screenshots:w.screenshots}}finally{n--}},async render(d,l){let u=mD.parse(l);return a(d.session.id,async()=>{d.signal.throwIfAborted();let p=VL(JSON.stringify([d.session.id,d.turnId,d.callId])),m=t.byCall(p);if(m)return s(m);let w=r.get(u.previewId);if(!w||w.sessionId!==d.session.id||w.expires<Date.now())throw new Error("Preview expired or belongs to another conversation. Preview the document again.");if(w.capture.console.some(I=>I.level==="error"))throw new Error("The preview has script or resource errors. Correct them and preview again before publishing.");let g=t.list(d.session.id).filter(I=>I.reference.visualId===u.visualId).sort((I,v)=>v.reference.output.revision-I.reference.output.revision)[0];if(u.visualId&&!g)throw new Error("The visual to revise does not belong to this conversation.");let f=`visual_pub_${p.slice(0,32)}`,y=u.visualId??`visual_${p.slice(0,32)}`,k={reference:{visualId:y,publicationId:f,sessionId:d.session.id,turnId:d.turnId,heights:w.capture.heights,output:{kind:"file",id:y,title:u.title,sourceTaskId:d.session.id,sourceTurnId:d.turnId,revision:(g?.reference.output.revision??0)+1,createdAt:new Date().toISOString(),contentType:"text/html",sizeBytes:Buffer.byteLength(w.html),sha256:w.sha256,location:{kind:"managed",fileId:f,downloadPath:`/v1/sessions/${encodeURIComponent(d.session.id)}/visuals/${f}/source`},validation:[{kind:"visual",status:"passed",label:"Desktop HTML preview",detail:`Rendered at ${w.capture.heights.map(I=>I.width).join(" and ")}px; no script or resource errors.`}]}},callKey:p,document:w.html,screenshot:w.capture.screenshots[0],ready:!1};t.save(k);let S=await s(k);return r.delete(u.previewId),S})},async read(d,l,u="html"){let p=t.get(l);if(!p||p.reference.sessionId!==d||!p.ready||!await e.getSession(d))throw new Error("Visual is unavailable.");let m=await WA(e.home,vu(l,u),w=>bY.readFile(w));return{reference:p.reference,bytes:m}},async removeSession(d){await a(d,async()=>{for(let l of t.list(d))await c(l);for(let[l,u]of r)u.sessionId===d&&r.delete(l)})}}}i(GL,"createHtmlVisualService");async function JL(e){let t=qL(),r=GL({home:e.home,executor:t.executor,getSession:i(n=>e.store.getSession(n),"getSession"),events:i(n=>e.store.runtimeEventsForSession(n),"events"),append:e.appendRuntimeEvent});return await r.recover(),{browserControlQueue:t,htmlVisuals:r,http:{htmlVisuals:r,browserControlActive:t.isActive,browserControlRegister:t.registerDesktopExecutor,browserControlNext:t.claimNext,browserControlComplete:t.completeRequest,browserControlStatus:t.status}}}i(JL,"createDesktopVisualRuntime");async function bu(e,t){let r=await $L(e),n={...t,providers:{...t.providers},statuses:{...t.statuses},modelCaches:{...t.modelCaches}};if(r.length){let o=r,a="custom-openai-compatible",c=[...t.modelCaches[a]?.models??[],...o.map(d=>({id:d.id,providerId:a,displayName:d.name,source:"manual",raw:{connectionProvider:d.providerName},capabilities:{streaming:d.protocol==="openai",toolCalling:!1,reasoning:!1,reasoningEfforts:[],vision:!1,structuredOutput:!1}}))];n.providers[a]=of.parse({...t.providers[a],enabled:!0,defaultModel:o[0].id}),n.statuses[a]=af.parse({...t.statuses[a],id:a,displayName:"Models from URL",enabled:!0,available:!0,defaultModel:o[0].id,modelIds:c.map(d=>d.id),credentialModes:["custom"],credential:{connected:!0,source:"local_secret"},routing:{localRuntime:!0,localByok:!0},capabilities:{chatCompletions:!0,streaming:!0,modelDiscovery:"none",toolCalling:!1}}),n.modelCaches[a]=xn.parse({providerId:a,source:"manual",models:c})}return n}i(bu,"withUrlModels");import wI from"node:path";async function KL(e){let t=[{role:"system",content:e.runtime?.systemPrompt??e.systemPrompt},{role:"user",content:e.userPrompt}],r=[...e.tools,...e.runtime?.tools??[]],n=[],o=[],a=[],s=await oE({turnId:e.turnId,maxRounds:e.maxTurns,signal:e.signal,async runRound({index:c,signal:d}){let l=await e.policyRequest({turnIndex:c,messages:structuredClone(t),tools:structuredClone(r)},d);d.throwIfAborted(),n.push(l.result),t.push({role:"assistant",content:l.content,tool_calls:l.toolCalls.map(g=>({id:g.id,type:"function",function:{name:g.name,arguments:g.arguments}}))});let u=e.runtime?l.toolCalls.filter(g=>g.name===Bb):[],p=e.runtime?l.toolCalls.filter(g=>g.name!==Bb):l.toolCalls,m=u.map(g=>{let f;try{f=e.runtime.readFile(JSON.parse(g.arguments))}catch(y){f={error:y instanceof Error?y.message:"Harness source read failed."}}return t.push({role:"tool",tool_call_id:g.id,content:JSON.stringify(f)}),o.push(g.name),{id:g.id,name:g.name,output:f}});if(u.length&&!p.length)return a.push({turnIndex:c,content:l.content,toolCalls:u,toolResults:m,terminal:!1}),{type:"continue"};let w=await e.step({content:l.content,toolCalls:p},d);d.throwIfAborted();for(let g of w.toolResults)t.push({role:"tool",tool_call_id:g.id,content:JSON.stringify(g.output)}),o.push(g.name);return w.userMessage&&t.push({role:"user",content:w.userMessage}),a.push({turnIndex:c,content:l.content,toolCalls:l.toolCalls,toolResults:[...m,...w.toolResults],terminal:w.terminal}),w.terminal?{type:"complete",result:w}:{type:"continue"}},async onExhausted(){e.signal.throwIfAborted();let c=await e.terminate("max_turns",e.signal);if(!c.terminal)throw new Error("Harness environment did not terminate after exhausting its turn budget.");return a.push({turnIndex:e.maxTurns,content:null,toolCalls:[],toolResults:[],terminal:!0,terminationReason:"max_turns"}),c}});return{messages:t,toolSequence:o,trace:a,policyResults:n,finalStep:s,runtimeReceipt:e.runtime?.receipt??null}}i(KL,"executeHarnessRollout");function ku(e){return wI.dirname(wI.dirname(e.secretsFilePath))}i(ku,"homeFor");function Zh(e,t){return $l(wI.join(Bl(ku(e)).runtime,"providers"),t)}i(Zh,"locked");async function Ya(e){let t=ku(e),{document:r}=await vc(t),n={};for(let[o,a]of Object.entries(r.providers??{})){let s=a.credential;if(!s)continue;let c=No(t,"provider_connection_state",o)?.value;if(s.source==="env"){n[o]={source:"env",value:null,envVar:s.name,oauth:null,createdAt:c?.createdAt??"1970-01-01T00:00:00.000Z",updatedAt:c?.updatedAt??"1970-01-01T00:00:00.000Z",lastValidatedAt:c?.lastValidatedAt??null,lastError:c?.lastError??null,credentialId:`env:${s.name}`};continue}let d=await FA(t,s.id);if(!d)throw new Bi({code:"CREDENTIAL_RECOVERY_REQUIRED",path:s.id,message:`The credential for ${o} is missing.`,action:"Reconnect this provider in Settings or restore its credential backup."});let l={...d.value,...c?{lastValidatedAt:c.lastValidatedAt??null,lastError:c.lastError??null}:{},credentialId:s.id,revision:d.revision};(l.endpoint??null)!==(a.base_url??null)?n[o]={...l,value:null,oauth:null,lastError:"The provider endpoint changed. Reconnect the provider for this endpoint."}:n[o]=l}return{version:1,providers:n}}i(Ya,"readUnlocked");async function Yc(e){return Zh(e,()=>Ya(e))}i(Yc,"readProviderSecrets");function YL(e){return AA.parse(e)}i(YL,"parseProviderCredentialWriteRequest");function XL(e){return CA.parse(e)}i(XL,"parseProviderCredentialDeleteRequest");function QL(e,t){if(!e||e.credentialId!==t.credentialId||e.revision!==t.revision)throw new Bi({code:"CREDENTIAL_CONFLICT",path:e?.credentialId??"providers",message:"The provider connection changed or was revoked.",action:"Reconnect the provider before retrying."})}i(QL,"checkExpected");async function ZL(e,t,r,n){return Zh(e,async()=>{let o=ku(e),a=await Ya(e),s=a.providers[t];n&&QL(s,n);let c=await vc(o),d=c.document.providers?.[t]?.credential;if(n&&(d?.source!=="secret"||d.id!==s?.credentialId||(c.document.providers?.[t]?.base_url??null)!==(s?.endpoint??null)))throw new Bi({code:"CREDENTIAL_CONFLICT",path:t,message:"The provider connection changed during refresh.",action:"Reconnect the provider before retrying."});if(n&&s?.source==="chatgpt_subscription"&&r.source==="chatgpt_subscription"&&d?.source==="secret"){if(s.oauth?.accountId!==r.oauth?.accountId)throw new Bi({code:"CREDENTIAL_CONFLICT",path:d.id,message:"The refreshed credential belongs to another account.",action:"Reconnect the provider before retrying."});return await rk(o,d.id,{...r,endpoint:s.endpoint??null,createdAt:s.createdAt},s.revision),df(o,"provider_connection_state",t),Ya(e)}let l=zA(`provider:${t}`),u={...r,endpoint:c.document.providers?.[t]?.base_url??null,createdAt:s?.createdAt??r.createdAt};return u.source!=="env"&&await rk(o,l,u,null),await Ul(o,p=>({...p,providers:{...p.providers,[t]:{...p.providers?.[t],credential:u.source==="env"?{source:"env",name:u.envVar}:{source:"secret",id:l}}}}),c.rawRevision),u.source==="env"?Uo(o,"provider_connection_state",t,{createdAt:u.createdAt,updatedAt:u.updatedAt,lastValidatedAt:u.lastValidatedAt,lastError:u.lastError}):df(o,"provider_connection_state",t),d?.source==="secret"&&await nk(o,d.id),Ya(e)})}i(ZL,"save");async function eB(e){if(e.request.source!=="env"&&!e.request.value)throw new Error("Provider credential value is required.");return ZL(e.paths,e.providerId,{source:e.request.source,value:e.request.source==="env"?null:e.request.value,envVar:e.request.source==="env"?e.request.envVar:null,oauth:null,createdAt:e.timestamp,updatedAt:e.timestamp,lastValidatedAt:null,lastError:null})}i(eB,"writeProviderCredential");async function Xc(e){return ZL(e.paths,e.providerId,{source:"chatgpt_subscription",value:null,envVar:null,oauth:e.credential,createdAt:e.timestamp,updatedAt:e.timestamp,lastValidatedAt:e.timestamp,lastError:e.lastError??null},e.expected)}i(Xc,"writeProviderChatGptSubscriptionCredential");async function tB(e){return Zh(e.paths,async()=>{let t=ku(e.paths),r=await Ya(e.paths),n=r.providers[e.providerId];if(!n||e.request.source&&e.request.source!==n.source)return r;let o=await vc(t),a=o.document.providers?.[e.providerId]?.credential;return await Ul(t,s=>{let c=s.providers?.[e.providerId];return c&&delete c.credential,s},o.rawRevision),a?.source==="secret"&&await nk(t,a.id),df(t,"provider_connection_state",e.providerId),Ya(e.paths)})}i(tB,"deleteProviderCredential");async function yI(e){return Zh(e.paths,async()=>{let t=ku(e.paths),r=await Ya(e.paths),n=r.providers[e.providerId];return n?(e.expected&&QL(n,e.expected),Uo(t,"provider_connection_state",e.providerId,{createdAt:n.createdAt,updatedAt:n.updatedAt,lastValidatedAt:e.timestamp,lastError:e.lastError}),Ya(e.paths)):r})}i(yI,"updateProviderCredentialValidation");function rB({home:e,managedAdapterChatRuntime:t,localByokRuntimeState:r,providerSecretPaths:n,now:o}){return async function*(a){if(a.providerId==="openpond"&&await t.appliesTo(a.modelId)){yield*t.stream({modelId:a.modelId,messages:a.messages,tools:a.tools,toolChoice:a.toolChoice,requestId:a.requestId,signal:a.signal});return}let s=await r(),c=a.providerId==="custom-openai-compatible"&&a.modelId?.startsWith("url:")?await NL(e,a.modelId):null;if(c&&c.protocol!=="openai")throw new Error("The selected connection is not an OpenAI-compatible model.");for await(let d of Ga({...c?{resolvedProvider:{providerId:"custom-openai-compatible",baseUrl:c.endpoint,model:c.model,auth:{type:"api_key",apiKey:c.token}},allowAnonymous:!0}:{},providerId:a.providerId,settings:s.settings,secrets:s.secrets,modelId:a.modelId,messages:a.messages,tools:a.tools,toolChoice:a.toolChoice,maxOutputTokens:a.maxOutputTokens,requestId:a.requestId,promptCacheKey:a.promptCacheKey,signal:a.signal,saveChatGptSubscriptionCredential:i(async(l,u)=>{await Xc({paths:n,providerId:l,credential:u,expected:s.secrets.providers[l]??{},timestamp:o()})},"saveChatGptSubscriptionCredential")}))d.type==="text_delta"&&(yield{text:d.text,raw:d.raw}),d.type==="reasoning_delta"&&(yield{reasoningText:d.text,raw:d.raw}),d.type==="continuation"&&(yield{continuation:d.continuation,raw:d.raw}),d.type==="tool_call_delta"&&(yield{toolCalls:d.toolCalls,raw:d.raw}),d.type==="usage"&&(yield{raw:d.raw,usage:d.usage}),d.type==="finish"&&(yield{finishReason:d.finishReason,raw:d.raw})}}i(rB,"createLocalByokChatStream");function nB(e){return i(async function(r){try{await e.store.upsertModelUsageRecord(r)}catch(n){await e.appendRuntimeEvent(se({sessionId:r.sessionId??void 0,turnId:r.turnId??void 0,name:"diagnostic",source:"server",status:"failed",output:n instanceof Error?n.message:"Failed to persist model usage record.",data:{kind:"model_usage_record_failed",requestId:r.requestId,provider:r.provider,model:r.model}})).catch(()=>{})}},"safeUpsertModelUsageRecord")}i(nB,"createModelUsagePersistence");function oB(e){let t=Promise.resolve();return r=>{let n=t.then(async()=>{try{return await e.before(),await r()}finally{e.after()}});return t=n.catch(()=>{}),n}}i(oB,"createAccountAuthorityChange");import{createHash as GY}from"node:crypto";var Ne=class extends Error{static{i(this,"GithubExtensionError")}code;status;constructor(t,r){super(t),this.name="GithubExtensionError",this.code=r.code,this.status=r.status??400}};import{createHash as lB}from"node:crypto";import bI from"node:path";var aB="HEAD",iB=64,sB=512,uB=20*1024*1024,kI=5*1024*1024,pB=8,kY=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,cB=/^[A-Za-z0-9_.-]+$/,dB=new Set(["agents","assets","references","scripts"]);function mB(e={}){let t=e.fetch??fetch,r=e.githubToken?.trim()||process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()||null;return{async resolve(n){let o=await IY(n,t,r);return{preview:await SY(o,t,r),files:fB(o)}},async download(n,o){await _Y({resolution:n,fetchImpl:t,githubToken:r,writeFile:o})}}}i(mB,"createGithubSourceClient");function Xa(e){let t=e.trim(),r="",n="";if(/^(?:https?:\/\/)?github\.com\//i.test(t)){let s=new URL(t.startsWith("http")?t:`https://${t}`);if(s.hostname.toLowerCase()!=="github.com")throw eg(e);let c=s.pathname.replace(/^\/+|\/+$/g,"").split("/");if(c.length!==2)throw eg(e);[r="",n=""]=c}else{let c=t.replace(/^github:/i,"").replace(/^\/+|\/+$/g,"").split("/");if(c.length!==2)throw eg(e);[r="",n=""]=c}if(n=n.replace(/\.git$/i,""),!cB.test(r)||!cB.test(n))throw eg(e);let o=r.toLowerCase(),a=n.toLowerCase();return{id:`github:${o}/${a}`,owner:o,repo:a,repositoryUrl:`https://github.com/${o}/${a}`}}i(Xa,"parseGithubExtensionSource");async function IY(e,t,r){let n=Xa(e.source),o=e.ref?.trim()||aB,a=await vI(t,r,`/repos/${n.owner}/${n.repo}`),s=o===aB?a.default_branch?.trim()||"main":o,c=await vI(t,r,`/repos/${n.owner}/${n.repo}/commits/${encodeURIComponent(s)}`),d=c.sha?.trim(),l=c.commit?.tree?.sha?.trim();if(!d||!l)throw new Ne("GitHub returned an incomplete commit response.",{code:"github_invalid_commit",status:502});let u=await vI(t,r,`/repos/${n.owner}/${n.repo}/git/trees/${l}?recursive=1`);if(u.truncated)throw new Ne("The GitHub repository tree is too large to install safely.",{code:"github_tree_truncated"});let p=(u.tree??[]).filter(AY),m=RY(p);if(m.length===0)throw new Ne("No skills found. Add SKILL.md at the repository root or use a standard agent skills directory.",{code:"extension_no_skills"});if(m.length>iB)throw new Ne(`Extension contains more than ${iB} skills.`,{code:"extension_too_many_skills"});EY(m);let w=p.find(g=>g.type==="blob"&&/^readme(?:\.[^/]+)?$/i.test(g.path))??null;return{identity:n,requestedRef:o,resolvedCommit:d,tree:p,skillPackages:m,readme:w}}i(IY,"resolveSource");async function SY(e,t,r){let n=await wB(e.skillPackages,pB,async c=>{let d=await TY(e,c.entry,t,r);return PY(c,d)}),o=jY(n.map(c=>c.name));for(let c of n)o.has(c.name)&&(c.validationStatus="error",c.validationMessages=[...c.validationMessages,`Duplicate skill name: ${c.name}`]);let a=n.flatMap(c=>c.validationMessages.map(d=>`${c.relativePath}: ${d}`)),s=fB(e);return{...e.identity,source:"github",requestedRef:e.requestedRef,resolvedCommit:e.resolvedCommit,sourcePath:null,readmePath:e.readme?.path??null,packageHash:CY(s),skills:n.sort((c,d)=>c.name.localeCompare(d.name)),validationStatus:a.length===0?"valid":"error",validationMessages:a}}i(SY,"buildPreview");function PY(e,t){let r=xc(t),n=e.root==="."?null:bI.posix.basename(e.root),o=r.name??n??"invalid-skill",a=[...r.messages];kY.test(o)||a.push("Skill name must be lowercase kebab-case."),n&&o!==n&&a.push(`Skill name must match its directory name (${n}).`);let s=e.files.filter(c=>c.path!==e.entry.path).map(c=>MY(e.root,c.path)).sort();return{name:o,description:r.description??"",relativePath:e.root==="."?"SKILL.md":`${e.root}/SKILL.md`,sourcePath:"",charCount:t.length,sourceHash:lB("sha256").update(t).digest("hex"),resourceFiles:s,validationStatus:a.length===0?"valid":"error",validationMessages:[...new Set(a)]}}i(PY,"previewSkill");function RY(e){let t=[],r=e.find(c=>c.type==="blob"&&c.path==="SKILL.md");r&&t.push({root:".",entry:r});let n=e.filter(c=>c.type==="blob"&&c.path.endsWith("/SKILL.md")),o=n.filter(c=>xY(c.path)),a=o.length>0?o:n,s=new Set(a.map(c=>bI.posix.dirname(c.path)));for(let c of a){let d=bI.posix.dirname(c.path);[...s].some(l=>l!==d&&d.startsWith(`${l}/`))||t.push({root:d,entry:c})}return t.map(({root:c,entry:d})=>{let l=e.filter(m=>{if(m.type!=="blob")return!1;if(c!==".")return m.path.startsWith(`${c}/`);if(m.path==="SKILL.md")return!0;let w=m.path.split("/",1)[0]??"";return dB.has(w)}),u=e.find(m=>m.type!=="blob"&&m.type!=="tree"&&(c==="."?m.path==="SKILL.md"||dB.has(m.path.split("/",1)[0]??""):m.path.startsWith(`${c}/`))),p=l.find(m=>m.mode==="120000");if(u||p)throw new Ne(`Skill package ${c} contains a symlink or submodule.`,{code:"extension_unsafe_entry"});return{root:c,entry:d,files:l}})}i(RY,"discoverSkillPackages");function xY(e){let t=e.split("/");if(t.at(-1)!=="SKILL.md")return!1;let r=t.slice(0,-1);if(r.length<2)return!1;let n=r.lastIndexOf("skills");if(n<0||n>2)return!1;let o=r.slice(0,n),a=r.slice(n+1);if(a.length<1||a.length>2)return!1;if(n===0)return!0;let s=o[0]??"";return s.startsWith(".")||s==="agent"||s==="data"}i(xY,"isStandardAgentSkillsPath");function fB(e){let t=new Map;e.readme&&t.set(e.readme.path,e.readme);for(let r of e.skillPackages)for(let n of r.files)t.set(n.path,n);return[...t.values()].sort((r,n)=>r.path.localeCompare(n.path))}i(fB,"filesToDownload");async function _Y(e){let t=0;await wB(e.resolution.files,pB,async r=>{let n=await hB({owner:e.resolution.preview.owner,repo:e.resolution.preview.repo,commit:e.resolution.preview.resolvedCommit,file:r,fetchImpl:e.fetchImpl,githubToken:e.githubToken});if(t+=n.byteLength,t>uB)throw new Ne("Extension download exceeds the maximum allowed size.",{code:"extension_too_large"});await e.writeFile(r.path,n,r.mode==="100755")})}i(_Y,"downloadFiles");async function TY(e,t,r,n){let o=await hB({owner:e.identity.owner,repo:e.identity.repo,commit:e.resolvedCommit,file:t,fetchImpl:r,githubToken:n});return new TextDecoder("utf-8",{fatal:!0}).decode(o)}i(TY,"downloadText");async function hB(e){let t=e.file.path.split("/").map(encodeURIComponent).join("/"),r=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${t}`,n=await e.fetchImpl(r,{headers:gB(e.githubToken,"application/vnd.github.raw"),redirect:"follow"});if(!n.ok)throw new Ne(`GitHub file download failed (${n.status}): ${e.file.path}`,{code:"github_download_failed",status:n.status});let o=Number(n.headers.get("content-length"));if(Number.isFinite(o)&&o>kI)throw new Ne(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});let a=new Uint8Array(await n.arrayBuffer());if(a.byteLength>kI)throw new Ne(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});return a}i(hB,"downloadBytes");async function vI(e,t,r){let n=await e(`https://api.github.com${r}`,{headers:gB(t,"application/vnd.github+json")});if(!n.ok){let o=await n.json().catch(()=>null),a=typeof o?.message=="string"?`: ${o.message}`:"";throw new Ne(`GitHub request failed (${n.status})${a}`,{code:n.status===404?"github_repository_not_found":"github_request_failed",status:n.status})}return await n.json()}i(vI,"githubJson");function gB(e,t){let r=new Headers({Accept:t,"User-Agent":"openpond-extension-installer","X-GitHub-Api-Version":"2022-11-28"});return e&&r.set("Authorization",`Bearer ${e}`),r}i(gB,"githubHeaders");function EY(e){let t=new Map;for(let n of e)for(let o of n.files)t.set(o.path,o);if(t.size>sB)throw new Ne(`Extension contains more than ${sB} skill files.`,{code:"extension_too_many_files"});let r=0;for(let n of t.values()){if((n.size??0)>kI)throw new Ne(`Extension file is too large: ${n.path}`,{code:"extension_file_too_large"});r+=n.size??0}if(r>uB)throw new Ne("Extension exceeds the maximum allowed size.",{code:"extension_too_large"})}i(EY,"validateDownloadLimits");function AY(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.path=="string"&&!t.path.startsWith("/")&&!t.path.split("/").includes("..")&&typeof t.mode=="string"&&(t.type==="blob"||t.type==="tree"||t.type==="commit")&&typeof t.sha=="string"}i(AY,"validTreeEntry");function CY(e){let t=lB("sha256");for(let r of e)t.update(`${r.path}\0${r.sha}\0${r.size??""}
|
|
12
12
|
`);return t.digest("hex")}i(CY,"hashTree");function MY(e,t){return e==="."?t:t.slice(e.length+1)}i(MY,"relativeSkillPath");function jY(e){let t=new Set,r=new Set;for(let n of e)t.has(n)&&r.add(n),t.add(n);return r}i(jY,"duplicateValues");async function wB(e,t,r){let n=new Array(e.length),o=0;async function a(){for(;o<e.length;){let s=o;o+=1,n[s]=await r(e[s])}}return i(a,"worker"),await Promise.all(Array.from({length:Math.min(t,e.length)},a)),n}i(wB,"mapConcurrent");function eg(e){return new Ne(`Invalid GitHub extension source: ${e}. Use owner/repo or https://github.com/owner/repo.`,{code:"github_invalid_source"})}i(eg,"invalidSource");import{createHash as OY,randomUUID as SB}from"node:crypto";import{existsSync as ns}from"node:fs";import{mkdir as II,readFile as HY,rename as Zc,rm as ed,stat as DY,writeFile as yB}from"node:fs/promises";import lt from"node:path";var rg=1,LY=15e3;function PB(e={}){let t=lt.resolve(e.home??e.rootPath??nf()),r=lt.resolve(e.rootPath??lt.join(t,"library","extensions")),n=Bl(t).database,o=mB({fetch:e.fetch,githubToken:e.githubToken}),a=e.now??(()=>new Date);async function s(){try{let g=await rs(t),f=await Promise.all(g.extensions.map(y=>SI(r,y)));return UY(f,await Qc(e.reservedSkillNames)),{rootPath:r,registryPath:n,extensions:f.sort(_I),error:null}}catch(g){return{rootPath:r,registryPath:n,extensions:[],error:g instanceof Error?g.message:String(g)}}}i(s,"list");async function c(g){let f=await o.resolve(g),y=await rs(t),h=y.extensions.find(k=>k.id===f.preview.id)??null;return Iu(f.preview,y.extensions.filter(k=>k.id!==h?.id),await Qc(e.reservedSkillNames)),f.preview}i(c,"preview");async function d(g){let f=Xa(g.source);return RI(r,f.id,async()=>{let y=await rs(t);if(y.extensions.some(I=>I.id===f.id))throw new Ne(`${f.owner}/${f.repo} is already installed.`,{code:"extension_already_installed",status:409});let h=await o.resolve(g);IB(h.preview),Iu(h.preview,y.extensions,await Qc(e.reservedSkillNames));let k=a().toISOString(),S=await vB({rootPath:r,resolution:h,installedAt:k,updatedAt:k,github:o});try{let I=await Qc(e.reservedSkillNames);return await PI(t,a,v=>({...v,extensions:$Y(v,S,I)})),await bB(r,S.id),S}catch(I){throw await kB(r,S.id),I}})}i(d,"add");async function l(g){let f=Xa(g.source);return RI(r,f.id,async()=>{let y=await rs(t),h=tg(y,f.id),k=await o.resolve({source:h.repositoryUrl,ref:g.ref?.trim()||h.requestedRef});if(IB(k.preview),Iu(k.preview,y.extensions.filter(I=>I.id!==h.id),await Qc(e.reservedSkillNames)),h.resolvedCommit===k.preview.resolvedCommit&&h.packageHash===k.preview.packageHash&&h.requestedRef===k.preview.requestedRef)return SI(r,h);let S=await vB({rootPath:r,resolution:k,installedAt:h.installedAt,updatedAt:a().toISOString(),github:o});try{let I=await Qc(e.reservedSkillNames);return await PI(t,a,v=>({...v,extensions:NY(v,S,I)})),await bB(r,S.id),S}catch(I){throw await kB(r,S.id),I}})}i(l,"update");async function u(){let g=await s();if(g.error)throw new Ne(g.error,{code:"extension_registry_error"});let f={updated:[],unchanged:[],failed:[]};for(let y of g.extensions)try{let h=await l({source:y.repositoryUrl,ref:y.requestedRef});h.resolvedCommit===y.resolvedCommit&&h.packageHash===y.packageHash?f.unchanged.push(h):f.updated.push(h)}catch(h){f.failed.push({id:y.id,error:h instanceof Error?h.message:String(h)})}return f}i(u,"updateAll");async function p(g){let f=Xa(g),y=await rs(t);return SI(r,tg(y,f.id))}i(p,"inspect");async function m(g){let f=Xa(g);return RI(r,f.id,async()=>{let y=await rs(t),h=tg(y,f.id),k=Su(r,f.owner,f.repo),S=`${k}.${SB()}.remove`;ns(k)&&await Zc(k,S);try{return await PI(t,a,I=>({...I,extensions:I.extensions.filter(v=>v.id!==h.id)})),await ed(S,{recursive:!0,force:!0}),h}catch(I){throw ns(S)&&!ns(k)&&await Zc(S,k),I}})}i(m,"remove");async function w(g){let f=g.trim();if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(f))throw new Ne("Extension skill name must be lowercase kebab-case.",{code:"extension_skill_invalid_name"});let y=await s();if(y.error)throw new Ne(y.error,{code:"extension_registry_error"});let h=y.extensions.flatMap(T=>T.skills.filter(P=>P.name===f).map(P=>({extension:T,skill:P})));if(h.length===0)throw new Ne(`Extension skill not found: ${f}`,{code:"extension_skill_not_found",status:404});if(h.length>1)throw new Ne(`Extension skill name is ambiguous: ${f}`,{code:"extension_skill_conflict",status:409});let k=h[0];if(k.extension.validationStatus!=="valid"||k.skill.validationStatus!=="valid")throw new Ne(`Extension skill ${f} is not valid.`,{code:"extension_skill_invalid"});let S=xB(k.extension.sourcePath,k.skill.relativePath),I=await HY(S,"utf8"),v=OY("sha256").update(I).digest("hex");if(v!==k.skill.sourceHash)throw new Ne(`Extension skill ${f} changed on disk. Update or reinstall its extension before using it.`,{code:"extension_skill_modified"});let R=xc(I);if(R.messages.length>0||R.name!==f||!R.description)throw new Ne(`Extension skill ${f} is not valid. ${R.messages.join(" ")}`.trim(),{code:"extension_skill_invalid"});return{name:f,description:R.description,body:R.body,path:k.skill.relativePath,sourcePath:k.extension.sourcePath,sourceHash:v,charCount:I.length,packagePath:lt.dirname(S),resourceFiles:k.skill.resourceFiles}}return i(w,"readSkill"),{rootPath:r,registryPath:n,list:s,preview:c,add:d,update:l,updateAll:u,inspect:p,remove:m,readSkill:w}}i(PB,"createGithubExtensionManager");async function vB(e){let t=e.resolution.preview,r=Su(e.rootPath,t.owner,t.repo),n=`${r}.${SB()}.install`,o=xI(e.rootPath,t.id),a=lt.join(n,"current");await ed(n,{recursive:!0,force:!0}),await ed(o,{recursive:!0,force:!0}),await II(a,{recursive:!0,mode:448});try{await e.github.download(e.resolution,async(c,d,l)=>{let u=xB(a,c);await II(lt.dirname(u),{recursive:!0,mode:448}),await yB(u,d,{mode:l?448:384})});let s=BY(t,r,e.installedAt,e.updatedAt);return await yB(lt.join(n,"extension.json"),`${JSON.stringify(s,null,2)}
|
|
13
|
-
`,{mode:384}),await II(lt.dirname(r),{recursive:!0,mode:448}),ns(r)&&await Zc(r,o),await Zc(n,r),s}catch(s){throw await ed(n,{recursive:!0,force:!0}),ns(o)&&!ns(r)&&await Zc(o,r),s}}i(vB,"materializeExtension");function BY(e,t,r,n){let o=lt.join(t,"current");return{...e,sourcePath:o,readmePath:e.readmePath?lt.join(o,e.readmePath):null,installedAt:r,updatedAt:n,skills:e.skills.map(a=>({...a,sourcePath:lt.join(o,a.relativePath)}))}}i(BY,"installedExtension");async function bB(e,t){await ed(xI(e,t),{recursive:!0,force:!0})}i(bB,"finalizeMaterialization");async function kB(e,t){let r=Xa(t.replace(/^github:/,"")),n=Su(e,r.owner,r.repo),o=xI(e,t);await ed(n,{recursive:!0,force:!0}),ns(o)&&await Zc(o,n)}i(kB,"rollbackMaterialization");async function SI(e,t){let r=Su(e,t.owner,t.repo),n=lt.join(r,"current"),o=(await DY(lt.join(r,"extension.json")).catch(()=>null))?.isFile()??!1,a=t.validationMessages.filter(s=>s!=="Installed files are missing.");return o||a.push("Installed files are missing."),{...t,sourcePath:n,readmePath:t.readmePath?lt.join(n,lt.basename(t.readmePath)):null,skills:t.skills.map(s=>({...s,sourcePath:lt.join(n,s.relativePath)})),validationStatus:a.length===0?"valid":"error",validationMessages:a}}i(SI,"hydrateExtension");function IB(e){if(e.validationStatus!=="valid")throw new Ne(`Extension contains invalid skills: ${e.validationMessages.join(" ")}`,{code:"extension_invalid"})}i(IB,"assertInstallable");function Iu(e,t,r){let n=new Map;for(let a of r)n.set(a,"a shipped OpenPond skill");for(let a of t)for(let s of a.skills)n.set(s.name,a.id);let o=e.skills.map(a=>({name:a.name,owner:n.get(a.name)})).filter(a=>!!a.owner);if(o.length!==0)throw new Ne(`Skill name conflict: ${o.map(a=>`${a.name} (${a.owner})`).join(", ")}.`,{code:"extension_skill_conflict",status:409})}i(Iu,"assertSkillNamesAvailable");function $Y(e,t,r){if(e.extensions.some(n=>n.id===t.id))throw new Ne(`${t.owner}/${t.repo} is already installed.`,{code:"extension_already_installed",status:409});return Iu(t,e.extensions,r),[...e.extensions,t].sort(_I)}i($Y,"appendInstalledExtension");function NY(e,t,r){return tg(e,t.id),Iu(t,e.extensions.filter(n=>n.id!==t.id),r),e.extensions.map(n=>n.id===t.id?t:n).sort(_I)}i(NY,"replaceInstalledExtension");function UY(e,t){let r=new Map;for(let n of t)r.set(n,"built-in");for(let n of e)for(let o of n.skills){let a=r.get(o.name);if(!a){r.set(o.name,n.id);continue}let s=`Skill name conflicts with ${a}: ${o.name}`;o.validationStatus="error",o.validationMessages=[...new Set([...o.validationMessages,s])],n.validationStatus="error",n.validationMessages=[...new Set([...n.validationMessages,s])]}}i(UY,"markInstalledSkillConflicts");async function Qc(e){let t=typeof e=="function"?await e():e??[];return[...new Set(t.map(r=>r.trim()).filter(Boolean))]}i(Qc,"reservedSkillNames");function tg(e,t){let r=e.extensions.find(n=>n.id===t);if(r)return r;throw new Ne(`${t.replace(/^github:/,"")} is not installed.`,{code:"extension_not_installed",status:404})}i(tg,"requireInstalled");async function rs(e){let t=No(e,"extension_installations","registry")?.value;if(!t)return FY();if(t.schemaVersion!==rg||!Array.isArray(t.extensions)||!t.extensions.every(RB))throw new Error("Extension registry has an unsupported format.");return qY(t)}i(rs,"readRegistry");async function PI(e,t,r){await $l(lt.join(Bl(e).runtime,"extension-registry"),async()=>{let n=No(e,"extension_installations","registry"),o=r(await rs(e));Uo(e,"extension_installations","registry",{...o,schemaVersion:rg,updatedAt:t().toISOString()},n?.revision??null)})}i(PI,"writeRegistry");function qY(e){return{schemaVersion:rg,updatedAt:typeof e?.updatedAt=="string"?e.updatedAt:null,extensions:Array.isArray(e?.extensions)?e.extensions.filter(RB):[]}}i(qY,"normalizeRegistry");function FY(){return{schemaVersion:rg,updatedAt:null,extensions:[]}}i(FY,"emptyRegistry");function RB(e){if(!e||typeof e!="object")return!1;let t=e;return t.source==="github"&&typeof t.id=="string"&&typeof t.owner=="string"&&typeof t.repo=="string"&&typeof t.repositoryUrl=="string"&&typeof t.requestedRef=="string"&&typeof t.resolvedCommit=="string"&&Array.isArray(t.skills)}i(RB,"isStoredExtension");function xB(e,t){if(lt.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new Ne(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});let r=lt.resolve(e,...t.split("/")),n=`${lt.resolve(e)}${lt.sep}`;if(!r.startsWith(n))throw new Ne(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});return r}i(xB,"safeDestination");function Su(e,t,r){return lt.join(e,"github",t,r)}i(Su,"extensionDirectory");function xI(e,t){let r=Xa(t.replace(/^github:/,""));return`${Su(e,r.owner,r.repo)}.previous`}i(xI,"backupDirectory");async function RI(e,t,r){let n=t.replace(/[^a-z0-9.-]+/gi,"-");return $l(lt.join(e,".locks",n),r,LY)}i(RI,"withExtensionLock");function _I(e,t){return e.id.localeCompare(t.id)}i(_I,"extensionSort");import{createHash as zY,randomUUID as WY}from"node:crypto";function _B(e){let t=e.explicitKey?.trim();if(t)return t;let r=e.sourceHead?.trim()||"unknown-source",n=e.targetProjectId?.trim()||"no-target-project",o=VY(e.input).slice(0,16),a=`profile-push-run:${e.localHead}:${r}:${e.runtimeAgentId}:${n}:${o}`;return e.retry?`${a}:retry:${(e.randomId??WY)()}`:a}i(_B,"buildHostedRunIdempotencyKey");function VY(e){return zY("sha256").update(TI(e)).digest("hex")}i(VY,"hashStableJson");function TI(e){return e===void 0?"undefined":e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(t=>TI(t)).join(",")}]`:`{${Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${TI(r)}`).join(",")}}`}i(TI,"stableJsonStringify");function TB(e,t){return async()=>{let r=await Mn(),n=(await t()).defaultTeamId?.trim()||null;if(r.accountState.state!=="signed_in")return null;let o=ho(r,n??void 0),a=fo(r,e,n,o.audience);return a?{owner:a,credentialKey:GY("sha256").update(JSON.stringify([r.token,r.apiBaseUrl])).digest("hex"),request:o.request}:null}}i(TB,"remoteRelayAccount");async function EB(e){let r=(await Mn()).accountState,n=(await e()).defaultTeamId?.trim()||null,o=r.state==="signed_in"&&!!r.profile?.id,a=r.activeProfile?.baseUrl??r.baseUrl,s=null;if(a){let c=new URL(a);s={"https://openpond.ai":"https://openpond.ai","https://api.openpond.ai":"https://openpond.ai","https://staging.openpond.ai":"https://staging.openpond.ai","https://staging-api.openpond.ai":"https://staging.openpond.ai"}[c.origin]??null}return{state:o?"ready":"signed_out",account:o?{id:r.profile.id,label:r.label}:null,team:o&&n?{id:n}:null,webBaseUrl:s}}i(EB,"remoteRelayAccountStatus");import{createHash as JY}from"node:crypto";function AB(e){return async t=>{let r=await e.store.getRemoteDeviceReceipt(t.id);if(r&&(!["stop","approval"].includes(t.action)||r.state!=="admitted")){if(r.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");return r}if(t.action==="approval"){if(!e.resolveApproval||!t.payload.response)throw new Error("remote_approval_unavailable");let a=r??await e.store.admitRemoteDeviceApproval(t);if(a.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");(await e.store.getApproval(a.approvalId))?.status==="pending"&&await e.resolveApproval(a.approvalId,{decision:t.payload.response==="approve"?"accept":"decline"});let c={...a,state:"applied",revision:a.revision+1};return await e.store.saveRemoteDeviceReceipt(t,c),c}if(t.action==="stop"){let a=r??await e.store.admitRemoteDeviceStop(t);if(a.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");(a.turnId?await e.store.getTurn(a.turnId):null)?.status==="in_progress"&&await e.interrupt(a.localSessionId,"Stopped remotely at the user's request.",a.turnId);let c={...a,state:"applied",revision:a.revision+1};return await e.store.saveRemoteDeviceReceipt(t,c),c}let n={id:t.id,deviceId:t.deviceId,state:"admitted",revision:2,payloadHash:t.payloadHash,action:t.action,targetId:t.targetId,createdAt:new Date().toISOString(),expiresAt:t.deadline},o=await e.store.getTaskInput(`remote-input:${t.id}`);if(o){let a=o.payload.remoteDevice;if(a?.payloadHash!==t.payloadHash||a.deviceId!==t.deviceId)throw new Error("remote_command_identity_changed")}else{if(!["follow_up","steer","start"].includes(t.action))throw new Error("remote_action_unavailable");let a=t.localSessionId;if(t.action==="start"){if(!e.resolveStarter||!e.createReserved)throw new Error("remote_start_unavailable");let s=await e.resolveStarter(t);a=(await e.createReserved({...K1(s),title:t.payload.text?.slice(0,120)??"Remote task"},{sessionId:`remote-session-${JY("sha256").update(t.id).digest("hex")}`,operationId:t.id,payloadHash:t.payloadHash,owner:mo.parse(s.metadata?.ponderLocalOwner),remoteStarterSourceSessionId:s.id})).id}else{let s=await e.inspect(a);if(!s.canSendFollowup||t.action==="steer"&&!s.canSteer)throw new Error("remote_target_unavailable")}if(!t.payload.text?.trim())throw new Error("remote_message_required");o=await e.admit({id:`remote-input:${t.id}`,sessionId:a,senderSessionId:null,senderKind:"user",kind:t.action==="steer"?"steer":"queued",body:t.payload.text,idempotencyKey:`remote:${t.id}`,expectedTurnId:t.expectedTurnId??null,replyTo:null,payload:{remoteDevice:t}})}return n.localSessionId=o.sessionId,n.inputId=o.id,o.turnId&&(n.turnId=o.turnId),await e.store.saveRemoteDeviceReceipt(t,n),n}}i(AB,"createRemoteCommandExecutor");import{randomUUID as QY}from"node:crypto";import{createHash as YY,randomUUID as MB}from"node:crypto";var EI=MB(),CB=0;function ng(){return EI}i(ng,"remoteHistoryIncarnation");function og(e){let t=e<CB;return t&&(EI=MB()),CB=e,t}i(og,"observeRemoteHistorySequence");function XY(e,t){return Number.parseInt(za(t,e.latestTurnId).slice(0,13),16)}i(XY,"remoteTaskRevision");function Pu(e){return YY("sha256").update(JSON.stringify([EI,e.id,e.createdAt,67])).digest("hex")}i(Pu,"remoteHistoryGeneration");async function jB(e){let t=[];for(let r of e.sessions){if(!ar(r,e.owner)||r.systemKind||r.hiddenFromDefaultSidebar||["sandbox","sandbox_template","sandbox_app"].includes(r.workspaceKind??""))continue;let n=await e.inspect(r.id),o=await e.latestTurn?.(r.id),a=e.approvals?.find(s=>s.sessionId===r.id&&s.status==="pending"&&o?.status==="in_progress"&&o.id===n.activeTurnId&&!!s.turnId&&(s.turnId===o.id||s.turnId===o.providerTurnId)&&Q1(s));t.push({id:r.id,localSessionId:r.id,title:r.title,projectId:r.localProjectId??null,projectLabel:r.workspaceName??null,provider:r.provider,revision:XY(n,r),historyGeneration:Pu(r),createdAt:r.createdAt,updatedAt:r.updatedAt,lastEventSequence:0,activeTurnId:n.activeTurnId,approvalId:a?.id??null,archived:r.archived??!1,deleted:!1,state:a?"attention":n.activeTurnId?"running":o?.status==="failed"?"failed":o?.status==="completed"?"completed":"idle",capabilities:{followUp:n.canSendFollowup,steer:n.canSteer,stop:n.activeTurnId!==null&&n.managedSessionId!==null,approval:!!a,artifacts:!1}})}return t.sort((r,n)=>r.id.localeCompare(n.id))}i(jB,"captureRemoteTaskCatalog");function AI(e,t){let r=e.name==="turn.started"&&typeof e.args?.prompt=="string",n=r||e.name==="assistant.delta",o=["tool.started","tool.completed"].includes(e.name),a=["turn.started","turn.completed","turn.failed","turn.interrupted"].includes(e.name),s=["approval.requested","approval.resolved"].includes(e.name);if(!n&&!o&&!a&&!s)return null;let c=e.data&&typeof e.data=="object"?e.data:{},d=n?r?e.args.prompt:e.output??(typeof c.text=="string"?c.text:""):"",l=e.name==="approval.requested"?"pending":e.name==="approval.resolved"?typeof c.status=="string"?c.status:c.decision==="accept"?"accepted":c.decision==="acceptForSession"?"accepted_for_session":c.decision==="decline"?"declined":c.decision==="cancel"?"cancelled":e.status:e.status;return{id:e.id,sequence:t,type:n?"message":o?"tool":s?"approval":"state",...e.turnId?{turnId:e.turnId}:{},...n?{messageId:r?`user:${e.turnId??e.id}`:`assistant:${typeof c.nativeMessageId=="string"?c.nativeMessageId:typeof c.itemId=="string"?c.itemId:e.turnId??e.id}`,textMode:c.nativeMessageSnapshot===!0?"replace":"append"}:{},...n?{role:r?"user":"assistant"}:{},...d?{text:d}:{},...o&&e.action?{toolName:e.action.slice(0,200)}:{},...l?{status:l}:{},...s&&typeof(c.approvalId??c.id)=="string"?{approvalId:c.approvalId??c.id}:{}}}i(AI,"projectRemoteEvent");async function CI(e,t){if(!["approval.requested","approval.resolved"].includes(t.name)||!t.turnId)return t;let r=await e.turnByProviderTurnId(t.turnId);return r&&r.sessionId===t.sessionId?{...t,turnId:r.id}:t}i(CI,"normalizeRemoteEventTurn");function*MI(e,t,r=0){let n=AI(e,t);if(n){if(!n.text||n.type!=="message"){yield n;return}for(let o=r;o<n.text.length;o+=8e3)yield{...n,fragmentIndex:Math.floor(o/8e3),fragmentCount:Math.ceil(n.text.length/8e3),id:`${n.id}:${o}`,text:n.text.slice(o,o+8e3),textMode:o===0?n.textMode:"append"}}}i(MI,"projectRemoteEventChunks");async function OB(e){let t=await e.store.getSession(e.taskId);if(!t||!ar(t,e.owner))throw new Error("remote_task_not_owned");let r=await e.store.latestEventSequence();og(r);let n=Pu(t),o=e.outputs?await e.outputs(t):[],a=0,s=0,c=r,d=QY();if(e.cursor){let f=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"));if(f.generation!==n||f.taskId!==e.taskId||!Number.isSafeInteger(f.after)||f.after<0||!Number.isSafeInteger(f.watermark)||f.watermark<f.after||typeof f.snapshotId!="string"||!Number.isSafeInteger(f.fragment??0)||(f.fragment??0)<0)throw new Error("remote_history_resync_required");a=f.after,s=f.fragment??0,c=f.watermark,d=f.snapshotId}let l=await e.store.runtimeEventPageRows({sessionId:e.taskId,afterSequence:a,beforeSequence:null,limit:100}),u=[],p=0,m=a,w=s,g=l.entries.length<100;e:for(let f of l.entries){if(f.sequence>c){g=!0;break}let y=MI(await CI(e.store,f.event),f.sequence,w);for(let h of y){f.event.name==="turn.completed"&&(h.artifactIds=o.filter(S=>S.sourceTurnId===f.event.turnId).map(S=>S.id).slice(0,100));let k=Buffer.byteLength(JSON.stringify(h));if(p+k>2e5){g=!1;break e}u.push(h),p+=k,h.type==="message"&&(w+=h.text?.length??0)}if(m=f.sequence,w=0,m>=c){g=!0;break}}return{snapshotId:d,taskId:t.id,historyGeneration:n,watermark:c,items:u,nextCursor:g?null:Buffer.from(JSON.stringify({generation:n,taskId:t.id,after:m,watermark:c,snapshotId:d,fragment:w})).toString("base64url"),capturedAt:new Date().toISOString(),provenance:"live"}}i(OB,"readRemoteHistory");function HB(e){let{deps:t,current:r,subscriptions:n,scheduleCatalog:o,catalog:a,send:s,serial:c,disconnect:d,schedule:l}=e,u=0;return t.listen(p=>{let m=["session.started","session.updated","session.title.updated","session.closed","turn.started","turn.completed","turn.failed","turn.interrupted","approval.requested","approval.resolved"].includes(p.name);m&&o();let w=p.sessionId;if(!r().authority||!w||!n.has(w))return;let g=AI(p,p.sequence??0);if(!g)return;let f=Buffer.byteLength(JSON.stringify(g));if(u+f>so.socketQueueBytes){d({state:"reconnecting",reason:"relay_backpressure"}).then(l);return}u+=f,c(async()=>{let{selected:y,authority:h}=r();if(!y||!h||!n.has(w))return;let k=await t.store.getSession(w);if(!k||r().authority!==h||r().selected!==y)return;let{deviceOwnsLocalSession:S}=await import("./local-scope-HVF2GZ5W.js");if(S(k,y.owner)){m&&await a(),p.name==="turn.completed"&&(g.artifactIds=(await t.outputs(k)).filter(I=>I.sourceTurnId===p.turnId).map(I=>I.id).slice(0,100));for(let I of MI(await CI(t.store,p),p.sequence??0)){if(r().authority!==h||r().selected!==y)return;g.artifactIds&&(I.artifactIds=g.artifactIds),s({protocolVersion:1,type:"events",taskId:k.id,payload:{historyGeneration:Pu(k),items:[I]}})}}}).catch(()=>{d({state:"reconnecting",reason:"connection_failed"}).then(l)}).finally(()=>{u-=f})})}i(HB,"listenRemoteRelayEvents");var DB=b.object({deviceId:b.string(),epoch:b.string(),fence:b.number().int().positive(),grantRevision:b.number().int().positive(),leaseExpiresAt:b.string().datetime()}),jI=b.object({keys:b.array(b.object({keyId:b.string(),publicKey:b.string()})).max(10),artifactUploadOrigins:b.array(b.string().url()).max(10).default([])});import{randomUUID as tN}from"node:crypto";import OQ from"node:os";var vQ=Qr(C$(),1),bQ=Qr(mg(),1),kQ=Qr(nd(),1),IQ=Qr(zI(),1),SQ=Qr(GI(),1),PQ=Qr(ZI(),1),vg=Qr(wg(),1),tS=Qr($$(),1);var rS=vg.default;import{createHash as q$,randomUUID as RQ}from"node:crypto";import{mkdir as xQ,open as N$,readFile as _Q,rename as TQ,unlink as EQ}from"node:fs/promises";import nS from"node:path";var AQ=b.object({version:b.literal(1),disabled:b.array(b.string().regex(/^[a-f0-9]{64}$/)),devices:b.record(b.string(),b.string().uuid()).default({})}).strict();function Zo(e){return q$("sha256").update(JSON.stringify([e.installationId,e.profileId,e.ownerUserId,e.teamId,e.audience])).digest("hex")}i(Zo,"deviceOwnerKey");function U$(e){return q$("sha256").update(JSON.stringify([e.installationId,e.profileId,e.ownerUserId,e.audience])).digest("hex")}i(U$,"accountPreferenceKey");async function F$(e){let t=nS.join(e,"remote-relay"),r=nS.join(t,"preference.json");await xQ(t,{recursive:!0,mode:448});let n=new Set,o={};try{let s=AQ.parse(JSON.parse(await _Q(r,"utf8")));n=new Set(s.disabled),o=s.devices}catch(s){if(s.code!=="ENOENT")throw s}let a=Promise.resolve();return{enabled(s){return!n.has(U$(s))&&!n.has(Zo(s))},async capture(s){n.has(Zo(s))&&await this.set(s,!1)},deviceId(s){return o[Zo(s)]??null},setDeviceId(s,c){return this.set(s,this.enabled(s),c)},set(s,c,d){let l=a.then(async()=>{let u=new Set(n),p=U$(s),m=Zo(s);u.delete(m),c?u.delete(p):u.add(p);let w={...o,...d?{[m]:d}:{}},g=nS.join(t,`${RQ()}.tmp`);try{let f=await N$(g,"wx",384);try{await f.writeFile(JSON.stringify({version:1,disabled:[...u],devices:w})),await f.sync()}finally{await f.close()}await TQ(g,r);let y=await N$(t,"r");try{await y.sync()}finally{await y.close()}n=u,o=w}finally{await EQ(g).catch(f=>{if(f.code!=="ENOENT")throw f})}});return a=l.catch(()=>{}),l}}}i(F$,"loadRemoteAccessPreference");import{createHash as CQ,randomUUID as z$}from"node:crypto";function MQ(e){let t=z$();return{runtimeId:t,request:e.request,signed(r,n){let o={version:1,scope:e.scope,runtimeId:t,audience:e.audience,nonce:z$(),issuedAt:new Date().toISOString(),payloadHash:CQ("sha256").update(Zl({method:"POST",path:r,payload:n})).digest("hex")};return e.request({path:r.replace(/^\/v1/,""),method:"POST",body:{payload:n,proof:{...o,signature:e.installation.sign(YM(o))}}})}}}i(MQ,"createRemoteDeviceClient");function W$(e,t){return MQ({installation:e,scope:{installationId:t.owner.installationId,profileId:t.owner.profileId,ownerUserId:t.owner.ownerUserId,teamId:t.owner.teamId},audience:t.owner.audience,request:t.request})}i(W$,"createSelectedRemoteClient");async function V$(e){let t=b.object({taskId:b.string(),artifactId:b.string(),uploadUrl:b.string().url(),maxBytes:b.number().int().positive().max(26214400)}).strict().parse(e.payload),r=new URL(t.uploadUrl);if(r.protocol!=="https:"||r.username||r.password||!e.uploadOrigins.includes(r.origin))throw new Error("remote_artifact_upload_origin_denied");let n=await e.session(t.taskId);if(!n||!ar(n,e.owner))throw new Error("remote_artifact_not_owned");let o=(await e.outputs(n)).find(d=>d.id===t.artifactId);if(!o||o.sourceTaskId!==n.id||o.sizeBytes>t.maxBytes)throw new Error("remote_artifact_unavailable_or_too_large");let a=await e.read(n,o.id);if(a.outputRef.sha256!==o.sha256||a.outputRef.sizeBytes!==o.sizeBytes||!e.stillCurrent())throw new Error("remote_artifact_authority_changed");let s=Buffer.from(a.contentsBase64,"base64");if(s.byteLength>t.maxBytes||s.byteLength!==o.sizeBytes)throw new Error("remote_artifact_size_changed");if(!(await fetch(r,{method:"PUT",body:s,headers:{"Content-Type":o.contentType},redirect:"error",signal:AbortSignal.timeout(15e3)})).ok)throw new Error("remote_artifact_upload_failed");if(!e.stillCurrent())throw new Error("remote_artifact_authority_changed");return{artifactId:o.id}}i(V$,"uploadRemoteArtifact");async function G$(e){let t=[];for(let r of e.sessions){if(e.assertCurrent(),!Xi(r)||!(await e.qualify(r)).eligible)continue;let n=await e.latestTurn(r.id);t.push({id:r.id,title:r.title,revision:za(r,n?.id??null)})}return e.assertCurrent(),t}i(G$,"unresolvedLocalOwnership");async function J$(e){e.assertCurrent();let t=await e.store.getSession(e.sessionId);if(!t)throw new Error("remote_local_attachment_session_unavailable");if(!ar(t,e.owner)){if(!Xi(t))throw new Error("remote_local_attachment_not_eligible");let r=await e.qualify(t);if(!r.eligible)throw new Error(r.reason??"remote_local_attachment_not_eligible")}return e.assertCurrent(),e.store.attachLocalSessionOwner({sessionId:e.sessionId,expectedRevision:e.expectedRevision,owner:e.owner,assertCurrent:e.assertCurrent})}i(J$,"attachQualifiedLocalOwner");function K$(){let e=[],t=null,r=null,n=!1;function o(){if(n||t)return;let a=e.shift();a&&(r=a,t=Promise.resolve().then(async()=>{try{a.current()&&await a.run()}catch(s){try{a.failed(s)}catch{}}finally{a.release()}}).finally(()=>{t=null,r=null,o()}))}return i(o,"advance"),{contains(a,s){let c=[...r?[r]:[],...e].filter(d=>d.commandId===a);if(c.some(d=>d.payloadHash!==s))throw new Error("remote_command_identity_changed");return c.length>0},enqueue(a){if(n||!a.current()){a.release();return}e.push(a),o()},invalidate(){e=e.filter(a=>a.current()?!0:(a.release(),!1))},async close(){n=!0;for(let a of e)a.release();e=[],await t}}}i(K$,"createRemoteCommandExecution");async function Y$(e){let{command:t,deps:r,send:n}=e;try{let o=await r.execute(t);n({protocolVersion:1,type:"receipt",payload:o})}catch(o){let a=await r.store.getRemoteDeviceReceipt(t.id);if(a){n({protocolVersion:1,type:"receipt",payload:{...a,state:"reconciling"}});return}n({protocolVersion:1,type:"receipt",payload:{id:t.id,deviceId:t.deviceId,payloadHash:t.payloadHash,action:t.action,targetId:t.targetId,state:"rejected",revision:2,error:o instanceof b.ZodError?"remote_command_configuration_invalid":o instanceof Error&&/^remote_[a-z0-9_]+$/.test(o.message)?o.message:"remote_command_failed",createdAt:new Date().toISOString(),expiresAt:t.deadline}})}}i(Y$,"executeRemoteCommand");async function X$(e){let{request:t,requestId:r,store:n,pending:o,current:a}=e,s=o(t.commandId,t.payloadHash),c=await n.getRemoteDeviceReceipt(t.commandId);if(!a())return null;let d=await n.getTaskInput(`remote-input:${t.commandId}`);if(!a())return null;let l=d?.payload.remoteDevice,u=await n.getRemoteDeviceCancellation(t.commandId);if(!a())return null;if(u&&u.payload_hash!==t.payloadHash)throw new Error("remote_command_identity_changed");if(c&&c.payloadHash!==t.payloadHash||l&&l.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");return{protocolVersion:1,type:"receipt_query_result",requestId:r,payload:{commandId:t.commandId,payloadHash:t.payloadHash,receipt:c??(d&&l?{id:l.id,deviceId:l.deviceId,state:"admitted",revision:2,payloadHash:l.payloadHash,action:l.action,targetId:l.targetId,localSessionId:d.sessionId,inputId:d.id,turnId:d.turnId,createdAt:d.createdAt,expiresAt:l.deadline}:null),notAdmitted:!c&&!d&&!s,cancelled:!!u}}}i(X$,"readRemoteCommandReceiptQuery");import{randomUUID as jQ}from"node:crypto";function Q$(e){let t=null,r=0,n=null,o=!1,a=0,s=i(c=>{if(!n)return;let d=n;n=null,clearTimeout(d.timeout),d.reject(c)},"cancel");return{reset(c=0){a++,s(new Error("remote_catalog_connection_lost")),t=null,r=Math.max(r,c)},resync(c){a++,t=null,r=Math.max(r,c),s(new Error("remote_catalog_resync_required"))},acknowledge(c){let d=QM.parse(c);if(!n||d.snapshotId!==n.snapshotId||d.revision!==n.revision||d.mode!==n.mode||d.pageIndex!==n.pageIndex)return;if(d.committed!==n.final||n.final&&d.catalogRevision!==n.revision)throw new Error("remote_catalog_ack_invalid");let l=n;n=null,clearTimeout(l.timeout),l.resolve()},async publish(c,d){if(o)throw new Error("remote_catalog_publication_in_progress");let l={tasks:new Map(c.map(R=>[R.id,R])),starters:new Map(d.map(R=>[R.id,R]))},u=i((R,T)=>[...R.values()].filter(P=>{let x=P.id;return!T?.has(x)||Zl(T.get(x))!==Zl(P)}),"changed"),p=i((R,T)=>[...R?.keys()??[]].filter(P=>!T.has(P)),"removed"),m={tasks:u(l.tasks,t?.tasks),starters:u(l.starters,t?.starters),removedIds:p(t?.tasks,l.tasks),removedStarterIds:p(t?.starters,l.starters)};if(t&&Object.values(m).every(R=>R.length===0))return!1;let w=t?"patch":"snapshot",g=r,f=Math.max(Date.now(),r+1),y=jQ(),h={mode:w,revision:f,snapshotId:y,...w==="patch"?{baseRevision:g}:{}},k=[{tasks:[],starters:[],removedIds:[],removedStarterIds:[]}];for(let R of["tasks","starters","removedIds","removedStarterIds"])for(let T of m[R]){let P=k.at(-1),x={...P,[R]:[...P[R],T]};(P[R].length>=100||Buffer.byteLength(JSON.stringify(x))>so.frameBytes-4096)&&(P={tasks:[],starters:[],removedIds:[],removedStarterIds:[]},k.push(P)),P[R].push(T)}if(k.length>100||Buffer.byteLength(JSON.stringify(k))>8388608)throw new Error("remote_catalog_publication_limit");let S=k.map((R,T)=>XM.parse({...h,...R,pageIndex:T,pageCount:k.length,complete:T===k.length-1})),I=a;o=!0;let v=Date.now()+45e3;try{for(let R of S){if(I!==a)throw new Error("remote_catalog_connection_lost");let T=v-Date.now();if(T<=0)throw new Error("remote_catalog_publication_timeout");let P=new Promise((x,_)=>{let E=setTimeout(()=>s(new Error("remote_catalog_ack_timeout")),Math.min(5e3,T));E.unref(),n={mode:w,snapshotId:y,revision:f,pageIndex:R.pageIndex,final:R.complete,resolve:x,reject:_,timeout:E}});try{e(R),await P}catch(x){throw s(x instanceof Error?x:new Error("remote_catalog_failed")),await P.catch(()=>{}),x}}if(I!==a)throw new Error("remote_catalog_connection_lost");return r=f,t=l,!0}finally{o=!1}}}}i(Q$,"createCatalogPublication");function Z$(e,t){if(e===4006||t.startsWith("protocol_unsupported")){let r=/minimum=(\d+)/.exec(t);return{state:"update_required",reason:"protocol_unsupported",...r?{minimumSupportedProtocolVersion:Number(r[1])}:{}}}return["grant_revoked","remote_access_off","ticket_revoked"].includes(t)?{state:"off",reason:t}:["authentication_required","ticket_invalid"].includes(t)?{state:"reconnecting",reason:"authentication_expired"}:{state:"reconnecting",reason:e===1013?"relay_backpressure":"connection_lost"}}i(Z$,"remoteCloseFailure");function eN(e){let t=Math.min(5e3,250*2**Math.min(e,5));return Math.round(t*(.8+Math.random()*.4))}i(eN,"remoteReconnectDelay");function rN(e){let t,r=null,n=null,o=null,a=null,s=null,c=null,d=null,l=null,u=!1,p=0,m=0,w=!1,g=null,f=null,y=null,h=Promise.resolve(),k="offline",S={state:"signed_out",account:null,team:null,webBaseUrl:null},I=null,v=0,R=null,T=!0,P=ng(),x=0,_=K$(),E=new Map,C=null,O=null,D=null,B=new Map,F=i(X=>{let W=h.then(X);return h=W.catch(()=>{}),W},"serial"),J=i(X=>W$(e.installation,X),"clientFor"),z=i(X=>{if(!n||n.readyState!==rS.OPEN)throw new Error("remote_connection_unavailable");let W=JSON.stringify({...o?{deviceId:o.id}:{},...l?{epoch:l}:{},...s?{fence:s.fence}:{},...X});if(Buffer.byteLength(W)>so.frameBytes||n.bufferedAmount+Buffer.byteLength(W)>so.socketQueueBytes)throw new Error("remote_connection_backpressure");n.send(W)},"send"),te=Q$(X=>z({protocolVersion:1,type:"catalog",payload:X}));async function M(X){X&&(I?.state!=="update_required"||X.state==="update_required")&&(I=X),I?.state==="update_required"&&g&&(clearTimeout(g),g=null),R&&clearTimeout(R),R=null,f&&clearTimeout(f),f=null,p++,_.invalidate(),T=!0,te.reset(),a=null,l=null,d=null,B.clear(),s=null,D?.(new Error("remote_connection_lost")),C=null,O=null,D=null;for(let G of E.values())clearTimeout(G.timer),G.reject(new Error("remote_connection_lost"));E.clear();let W=n;n=null,W?.close(1e3,"authority_changed"),await e.store.setRemoteDeviceAuthority(null),k=r&&t&&!t.enabled(r.owner)?"off":I?.state??"offline"}i(M,"disconnect");async function L(){return e.store.sessionShells()}i(L,"sessions");async function H(){if(!r||!a||!t.enabled(r.owner))return;let X=r,W=a,G=p,re=i(()=>!u&&r===X&&a===W&&p===G,"catalogCurrent"),le=await e.store.latestEventSequence();if(!re()||(og(le)&&(T=!0),P!==ng()&&(T=!0),!T))return;T=!1;let oe=await L(),pe=await e.store.pendingApprovals();if(!re())return;let me=await jB({owner:X.owner,sessions:oe,inspect:e.inspect,approvals:pe,latestTurn:i(ye=>e.store.latestTurnForSession(ye),"latestTurn")});for(let ye of me){if(!re())return;let ie=oe.find(Oe=>Oe.id===ye.localSessionId);ye.capabilities.artifacts=ie.experience==="work";let be=await e.store.runtimeEventPageRows({sessionId:ie.id,afterSequence:0,beforeSequence:await e.store.latestEventSequence()+1,limit:1});ye.lastEventSequence=be.entries[0]?.sequence??0}let Fe=[...Y1(oe,X.owner).values()].map(ye=>ye.target);if(re()){try{await te.publish(me,Fe)}catch(ye){if(ye instanceof Error&&ye.message==="remote_catalog_resync_required")T=!0,await te.publish(me,Fe);else throw ye}re()&&(P=ng())}}i(H,"catalog");async function N(X=!1){if(u||w||I?.state==="update_required")return;let W=p,G=await e.current(),re=await e.accountStatus();if(G&&await t.capture(G.owner),w||W!==p||u)return;if(S=re,r&&(!G||Zo(G.owner)!==Zo(r.owner)||G.credentialKey!==r.credentialKey)){m++;let De=p+1;if(await M(),p!==De||u||w)return;o=null}r=G;let le=!!G&&!t.enabled(G.owner);if(!G||le&&!e.caller?.needsConnection()){await M();return}for(let[De,Le]of B){for(let[it,ge]of Le)ge<=Date.now()&&Le.delete(it);Le.size===0&&B.delete(De)}if(n){if(s&&d&&o){let De=n,Le=d,it=o,ge=p,ce=i(()=>!u&&!w&&n===De&&p===ge,"renewalCurrent"),Ee=jI.parse(await Le.request({path:"/remote-devices/service-keys"}));if(!ce())return;c=Ee;let ut=b.object({ticket:b.string()}).parse(await Le.signed("/v1/remote-devices/connection-tickets",{role:"device",deviceId:it.id,client:"desktop",mode:le?"request":"remote",...e.caller?.requestAuthority(it.id,Le.runtimeId)?{requestAuthority:e.caller.requestAuthority(it.id,Le.runtimeId)}:{}}));if(!ce())return;z({protocolVersion:1,type:"renew",payload:{ticket:ut.ticket}}),z({protocolVersion:1,type:"heartbeat"}),await H()}return}k="connecting";let oe=p,pe=J(G),me;try{me=await pe.signed("/v1/remote-devices/enroll",{publicKey:e.installation.publicKey,name:OQ.hostname(),platform:process.platform,enabled:!le,...le?{requestOnly:!0}:{},...X?{reenable:!0}:{}})}catch(De){if(oe!==p||u||w)return;if(String(De).includes("deliberate_local_reenable_required")){if(await t.set(G.owner,!1),oe!==p||u||w)return;k="off";return}throw De}let Fe=jI.parse(await pe.request({path:"/remote-devices/service-keys"}));if(oe!==p||u||w)return;c=Fe;let ye=b.object({ticket:b.string(),connectUrl:b.string().url()}).parse(await pe.signed("/v1/remote-devices/connection-tickets",{role:"device",deviceId:me.device.id,client:"desktop",mode:le?"request":"remote",...e.caller?.requestAuthority(me.device.id,pe.runtimeId)?{requestAuthority:e.caller.requestAuthority(me.device.id,pe.runtimeId)}:{}}));if(oe!==p||u||(o=me.device,await t.setDeviceId(G.owner,o.id),oe!==p||u||w))return;d=pe;let ie=new rS(ye.connectUrl,{maxPayload:so.frameBytes});C=new Promise((De,Le)=>{O=De,D=Le}),C.catch(()=>{}),n=ie,R=setTimeout(()=>{n===ie&&!s&&M({state:"reconnecting",reason:"authentication_timeout"}).then($)},6e3),R.unref(),ie.on("open",()=>{n===ie&&z({protocolVersion:1,type:"hello",payload:{ticket:ye.ticket}})});let be=i(()=>!u&&n===ie&&oe===p,"connectionCurrent"),Oe=i(De=>{be()&&z(De)},"sendCurrent");ie.on("message",De=>{if(!be())return;try{let ge=JSON.parse(De.toString()),ce=ge.type==="error"&&ge.payload?.error==="catalog_resync_required";if(ge.type==="catalog_ack"||ce){if(n!==ie||oe!==p||!s)return;if(ge.protocolVersion!==Ac||ge.deviceId!==o?.id||ge.epoch!==s.epoch||ge.fence!==s.fence)throw new Error("remote_catalog_ack_authority_changed");if(ce){let Ee=b.object({catalogRevision:b.number().int().nonnegative()}).parse(ge.payload);te.resync(Ee.catalogRevision),T=!0}else te.acknowledge(ge.payload);return}}catch(ge){if(!be())return;e.warn(`Remote relay acknowledgement: ${ge instanceof Error?ge.name:"invalid_frame"}`),M({state:"reconnecting",reason:"connection_failed"}).then($);return}let Le=Buffer.byteLength(De.toString());if(x+Le>so.socketQueueBytes){M({state:"reconnecting",reason:"relay_backpressure"}).then($);return}x+=Le;let it=!1;F(async()=>{if(n!==ie||oe!==p)return;let ge=JSON.parse(De.toString());if(ge.protocolVersion!==Ac){await M({state:"update_required",reason:"protocol_unsupported"});return}if(ge.type==="hello"||ge.type==="heartbeat"||ge.type==="renew"){let ce=DB.parse(ge.payload);if(ge.type==="hello"){let Ee=b.object({catalogRevision:b.number().int().nonnegative(),minimumSupportedProtocolVersion:b.number().int().positive(),supportedProtocolVersion:b.number().int().positive()}).parse(ge.payload);if(Ee.minimumSupportedProtocolVersion>Ac||Ee.supportedProtocolVersion!==Ac){await M({state:"update_required",reason:"protocol_unsupported",minimumSupportedProtocolVersion:Ee.minimumSupportedProtocolVersion});return}te.reset(Ee.catalogRevision)}if(ce.deviceId!==o?.id)throw new Error("remote_device_identity_changed");if(l=ce.epoch,s=ce,a=le?null:{...ce,owner:G.owner,publicKeys:c?.keys??[]},await e.store.setRemoteDeviceAuthority(a),!be()||(R&&clearTimeout(R),R=null,I=null,v=0,O?.(),O=null,ge.type==="hello"&&await H(),!be()))return;k=le?"off":"connected"}else if(ge.type==="error"){let ce=b.object({error:b.string(),minimumSupportedProtocolVersion:b.number().int().positive().optional()}).parse(ge.payload);if(ce.error==="protocol_unsupported")await M({state:"update_required",reason:ce.error,minimumSupportedProtocolVersion:ce.minimumSupportedProtocolVersion});else throw new Error("remote_relay_rejected_frame")}else if(ge.type==="revoked"){if(await t.set(G.owner,!1),!be())return;await M()}else if(ge.type==="drain")await M({state:"reconnecting",reason:"connection_lost"}),$();else if(ge.type==="subscribe"||ge.type==="history_request"){if(!a)throw new Error("remote_authority_unavailable");let ce=b.object({taskId:b.string(),viewerId:b.string().optional(),cursor:b.unknown().optional()}).parse(ge.payload);if(ge.type==="subscribe"){if(!ce.viewerId)throw new Error("remote_viewer_identity_required");if(!B.has(ce.taskId)&&B.size>=so.deviceSubscriptions)throw new Error("remote_subscription_limit");let Rr=B.get(ce.taskId)??new Map,sc=Rr.has(ce.viewerId);if(Rr.size>=100&&!sc)throw new Error("remote_viewer_limit");if(Rr.set(ce.viewerId,Date.now()+75e3),B.set(ce.taskId,Rr),!ge.requestId&&ce.cursor===void 0)return}let Ee=typeof ce.cursor=="string"?ce.cursor:null;if(ce.cursor&&typeof ce.cursor=="object"){let Rr=b.object({historyGeneration:b.string(),sequence:b.number().int().nonnegative()}).parse(ce.cursor);Ee=Buffer.from(JSON.stringify({generation:Rr.historyGeneration,taskId:ce.taskId,after:Rr.sequence,watermark:await e.store.latestEventSequence(),snapshotId:tN()})).toString("base64url")}if(!be())return;let ut=await OB({store:e.store,owner:G.owner,taskId:ce.taskId,cursor:Ee,outputs:e.outputs});Oe({protocolVersion:1,type:"snapshot",taskId:ce.taskId,requestId:ge.requestId,payload:ut})}else if(ge.type==="unsubscribe"){let ce=b.object({taskId:b.string(),viewerId:b.string()}).parse(ge.payload),Ee=B.get(ce.taskId);Ee?.delete(ce.viewerId),Ee?.size===0&&B.delete(ce.taskId)}else if(ge.type==="receipt_query"){let ce=b.object({commandId:b.string(),payloadHash:b.string()}).parse(ge.payload),Ee=await X$({request:ce,requestId:ge.requestId,store:e.store,pending:_.contains,current:be});Ee&&Oe(Ee)}else if(ge.type==="command_cancel"){let ce=b.object({commandId:b.string(),payloadHash:b.string()}).parse(ge.payload),Ee=await e.store.cancelRemoteDeviceCommand(ce.commandId,ce.payloadHash);Oe({protocolVersion:1,type:"command_cancel_result",requestId:ge.requestId,payload:{...ce,...Ee}})}else if(ge.type==="caller_offers")e.caller?.receiveOffers(ge.payload);else if(ge.type==="caller_result"){let ce=ge.requestId?E.get(ge.requestId):null;if(!ce)return;let Ee=b.object({result:b.unknown().optional(),error:b.string().optional()}).parse(ge.payload);E.delete(ge.requestId),clearTimeout(ce.timer),Ee.error?ce.reject(new Error(Ee.error)):ce.resolve(Ee.result)}else if(ge.type==="artifact_request")try{let ce=await V$({payload:ge.payload,owner:G.owner,uploadOrigins:c?.artifactUploadOrigins??[],session:i(Ee=>e.store.getSession(Ee),"session"),outputs:e.outputs,read:e.readOutput,stillCurrent:i(()=>n===ie&&p===oe&&!!a,"stillCurrent")});Oe({protocolVersion:1,type:"artifact_result",requestId:ge.requestId,payload:ce})}catch(ce){Oe({protocolVersion:1,type:"artifact_result",requestId:ge.requestId,payload:{artifactId:ge.payload.artifactId,error:ce instanceof Error?ce.message:"remote_artifact_failed"}})}else if(ge.type==="command"){let ce=ge.payload,Ee=i(()=>!u&&!w&&!!a&&n===ie&&p===oe,"current");it=!0,_.enqueue({commandId:ce.id,payloadHash:ce.payloadHash,current:Ee,run:i(()=>Y$({command:ce,deps:e,send:i(ut=>{Ee()&&z(ut)},"send")}),"run"),failed:i(ut=>{Ee()&&(e.warn(`Remote relay command: ${ut instanceof Error?ut.name:"command_failed"}`),M({state:"reconnecting",reason:"connection_failed"}).then($))},"failed"),release:i(()=>{x-=Le},"release")})}}).catch(ge=>{n!==ie||oe!==p||u||(e.warn(`Remote relay frame: ${ge instanceof Error?ge.name:"invalid_frame"}`),M({state:"reconnecting",reason:"connection_failed"}).then($))}).finally(()=>{it||(x-=Le)})}),ie.on("close",(De,Le)=>{if(n!==ie)return;let it=Z$(De,Le.toString());it.state==="off"&&t.set(G.owner,!1),M(it).then($)}),ie.on("error",De=>e.warn(`Remote relay connection: ${De.name}`))}i(N,"connect");function $(){if(g&&clearTimeout(g),g=null,u||I?.state==="update_required")return;let W=!!r&&(t.enabled(r.owner)||!!e.caller?.needsConnection())&&!n?eN(v++):15e3;g=setTimeout(()=>{g=null,F(N).catch(G=>{k="reconnecting",I={state:k,reason:"connection_failed"},e.warn(`Remote relay: ${G instanceof Error?G.name:"connection_failed"}`)}).finally($)},W),g.unref()}i($,"schedule");function Z(){T=!0,!(u||f||!a)&&(f=setTimeout(()=>{f=null,F(H).catch(()=>{T=!0,M({state:"reconnecting",reason:"connection_failed"}).then($)})},100),f.unref())}return i(Z,"scheduleCatalog"),{async start(){t=await F$(e.storeDir),await e.store.initializeRemoteDeviceStore(),y=HB({deps:e,current:i(()=>({selected:r,authority:a}),"current"),subscriptions:B,scheduleCatalog:Z,catalog:H,send:z,serial:F,disconnect:M,schedule:$}),await F(N).catch(X=>e.warn(`Remote relay startup: ${X instanceof Error?X.name:"connection_failed"}`)),$()},async close(){u=!0,g&&clearTimeout(g),y?.(),await M(),await h,await _.close()},async beforeAuthorityChange(){w=!0,m++,I=null,await M(),r&&await t.capture(r.owner),r=null,o=null,k="offline"},afterAuthorityChange(){w=!1,this.wake()},wake(){F(N).catch(X=>e.warn(`Remote relay wake: ${X instanceof Error?X.name:"connection_failed"}`)).finally($)},async callerRequest(X){if(E.size>=32)throw new Error("ponder_relay_request_limit");if(await F(N),await C,!s)throw new Error("ponder_relay_connection_unavailable");let W=tN();return new Promise((G,re)=>{let le=setTimeout(()=>{E.delete(W),re(new Error("ponder_relay_request_timeout"))},3e4);le.unref(),E.set(W,{resolve:G,reject:re,timer:le});try{z({protocolVersion:1,type:"caller_request",requestId:W,payload:X})}catch(oe){clearTimeout(le),E.delete(W),re(oe)}})},status(){return{state:r?k:"signed_out",enabled:r?t.enabled(r.owner):!1,device:o,owner:r?.owner??null,account:S.account,team:S.team,webBaseUrl:S.webBaseUrl,reason:I?.reason??null,minimumSupportedProtocolVersion:I?.minimumSupportedProtocolVersion??null,supportedProtocolVersion:Ac}},async settings(X,W){if(w)throw new Error("remote_account_changing");let G=m,re=i(()=>{if(u||w||G!==m)throw new Error("remote_account_changing")},"assertCurrentAccount"),le=await e.accountStatus(),oe=await e.current();if(oe&&await t.capture(oe.owner),w||G!==m)throw new Error("remote_account_changing");if(S=le,!oe)return await M(),r=null,o=null,{...this.status(),devices:[],unresolvedTasks:[]};if(r&&Zo(r.owner)!==Zo(oe.owner)&&(await M(),r=oe,o=null),(X==="enable"||X==="disable")&&await this.setEnabled(X==="enable"),X==="retry"){if(!t.enabled(oe.owner))throw new Error("remote_access_off");I=null,v=0,await M(),r=oe,await F(N),$()}if(X==="attach"){let ie=b.object({sessionId:b.string(),expectedRevision:b.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(W),be=await e.prepareOwnerAttachment(oe.owner);await J$({...ie,store:e.store,owner:oe.owner,qualify:be,assertCurrent:re}),T=!0,a&&await H()}if(X==="rename"||X==="remove"||X==="disable-device"){let ie=b.object({deviceId:b.string().uuid(),revision:b.number().int().positive(),name:b.string().min(1).max(200).optional()}).strict().parse(W),be=t.deviceId(oe.owner);if(!be)throw new Error("remote_device_not_enrolled");let Oe=await J(oe).signed("/v1/remote-devices/device-management",{deviceId:be,action:X==="disable-device"?"disable":X,targetDeviceId:ie.deviceId,revision:ie.revision,...ie.name?{name:ie.name}:{}});ie.deviceId===o?.id&&(o=Oe.device),["remove","disable-device"].includes(X)&&ie.deviceId===o?.id&&(await t.set(oe.owner,!1),await M())}let pe=t.deviceId(oe.owner),me=pe?await J(oe).signed("/v1/remote-devices/device-management",{deviceId:pe,action:"list"}):{devices:[]};o=me.devices.find(ie=>ie.id===pe)??o;let Fe=await e.prepareOwnerAttachment(oe.owner),ye=await G$({sessions:await L(),qualify:Fe,latestTurn:i(ie=>e.store.latestTurnForSession(ie),"latestTurn"),assertCurrent:re});return{...this.status(),devices:me.devices,unresolvedTasks:ye}},async setEnabled(X){if(w)throw new Error("remote_account_changing");I=null,v=0;let W=m,G=await e.current();if(w||W!==m)throw new Error("remote_account_changing");if(!G)throw new Error("Sign in to your OpenPond account first.");if(await t.set(G.owner,X),w||W!==m)throw new Error("remote_account_changing");if(await M(),w||W!==m)throw new Error("remote_account_changing");return r=G,!X&&o&&await J(G).signed("/v1/remote-devices/device-management",{deviceId:o.id,targetDeviceId:o.id,action:"disable",revision:o.revision}),X&&await F(()=>N(!0)),$(),this.status()}}}i(rN,"createRemoteRelayManager");function oS(e){let t=new Map,r=0;return async n=>{if(n.experience!=="work")return[];let o=await e.latestEventSequence(),a=t.get(n.id);if(a?.watermark===o)return t.delete(n.id),t.set(n.id,a),a.outputs;let s=RH(5e3),c=0;for(;c<o;){let p=(await e.runtimeEventPageRows({sessionId:n.id,afterSequence:c,beforeSequence:null,limit:100})).entries.filter(m=>m.sequence<=o);for(let m of p)s.accept(m.event);if(p.length<100)break;c=p.at(-1).sequence}let d=s.values().filter(u=>u.sourceTaskId===n.id&&u.location.kind==="local").sort((u,p)=>p.revision-u.revision),l=Buffer.byteLength(JSON.stringify(d));if(l>10485760)throw new Error("remote_output_reference_limit");for(a&&(r-=a.bytes,t.delete(n.id));t.size>=20||r+l>33554432;){let u=t.entries().next().value;if(!u)break;t.delete(u[0]),r-=u[1].bytes}return t.set(n.id,{watermark:o,outputs:d,bytes:l}),r+=l,d}}i(oS,"createRemoteOutputReader");function nN(e,t){let r=oS(e);return async(n,o)=>{let a=(await r(n)).find(s=>s.id===o);if(!a)throw new Error("remote_artifact_unavailable");return t(n,a)}}i(nN,"createRemoteQualifiedOutputReader");function oN(e){let{loadAppPreferences:t,commands:r,readQualifiedOutput:n,...o}=e,a=TB(o.installation.installationId,t);return rN({...o,current:a,accountStatus:i(()=>EB(t),"accountStatus"),execute:AB({...r,store:o.store,inspect:o.inspect,resolveStarter:X1({store:o.store,current:a})}),outputs:oS(o.store),readOutput:nN(o.store,n)})}i(oN,"createAccountRemoteRelayManager");import{createHash as HQ}from"node:crypto";import{readFile as DQ,writeFile as LQ,rename as BQ,mkdir as $Q}from"node:fs/promises";import aN from"node:path";function iN(e){let t=!1,r=Promise.resolve(),n=i(p=>{t||(r=r.then(p).catch(()=>e.warn("Ponder Pal activity sync will retry.")))},"queue");async function o(){let p=await Mn(),m=p?.accountState;if(!m?.activeProfile||m.state!=="signed_in")return null;let w=fo(p,e.deviceId,await e.teamId(),new URL(p.apiBaseUrl).origin);if(!w?.teamId)return null;let g=HQ("sha256").update(JSON.stringify([m.baseUrl,m.activeProfile,w.teamId,e.deviceId,w.ownerUserId])).digest("hex");return{key:g,owner:w,context:p,file:aN.join(e.storeDir,"ponder-activity",`${g}.json`)}}i(o,"scope");async function a(p,m){let w=await e.sessionOwner(p);return w?.installationId===m.installationId&&w.profileId===m.profileId&&w.ownerUserId===m.ownerUserId&&w.teamId===m.teamId&&w.audience===m.audience}i(a,"owns");async function s(p){try{return JSON.parse(await DQ(p,"utf8"))}catch(m){if(m.code==="ENOENT")return{pending:[],observed:{}};throw m}}i(s,"read");async function c(p,m){await $Q(aN.dirname(p),{recursive:!0}),await LQ(p+".tmp",JSON.stringify(m),{mode:384}),await BQ(p+".tmp",p)}i(c,"save");let d=e.subscribe(p=>{if(t||!p.sessionId||!["session.started","turn.completed","turn.failed","turn.interrupted","turn.started"].includes(p.name))return;let m=o().then(w=>({owner:w}),w=>({error:w}));n(async()=>{let w=await m;if("error"in w)throw w.error;let g=w.owner;if(!g||t||!await a(p.sessionId,g.owner))return;let f=await e.sessionTitle(p.sessionId),y=await s(g.file),h={id:`local:${e.deviceId}:${p.id}`,source:"local",kind:p.name==="session.started"?"thread.started":"run.updated",resourceId:p.sessionId,title:f.slice(0,300),status:p.name==="session.started"?"started":p.name.slice(5),occurredAt:p.timestamp};y.pending.some(k=>k.id===h.id)||y.pending.push(h),await c(g.file,y)})});async function l(){let p=await o();if(!p||t)return;let m=await e.request({path:"/ponder/settings"},p.context,p.owner.teamId);if((await o())?.key!==p.key)return;let w=m.settings,g=m.bindingId;if(typeof g!="string")throw new Error("Ponder Pal binding missing.");let f=await s(p.file);if(!w.watchLocalThreads){f.pending=[],await c(p.file,f);return}if(w.watchWorkflows){let{workflows:S,runs:I}=await e.workflows(),v=new Map(S.map(R=>[R.id,R.name]));for(let R of[...S.map(T=>({...T,status:"available",resourceId:T.id,title:T.name})),...I.map(T=>({...T,resourceId:T.sessionId,title:v.get(T.workflowId)??"Workflow run"}))]){if(!await a(R.resourceId,p.owner))continue;let T=`workflow:${R.id}`,P=`${R.updatedAt}:${R.status}`;f.observed[T]!==P&&(f.pending.push({id:`local:${e.deviceId}:${T}:${P}`,source:"local",kind:"workflow.updated",resourceId:R.resourceId,title:R.title.slice(0,300),status:R.status,occurredAt:R.updatedAt}),f.observed[T]=P)}await c(p.file,f)}if((await o())?.key!==p.key||!f.pending.length)return;let y=f.pending.slice(0,100),h=await e.request({path:"/ponder/activity",method:"POST",body:{bindingId:g,items:y}},p.context,p.owner.teamId);if((await o())?.key!==p.key)return;let k=new Set([...h.delivered,...h.ignored]);f.pending=f.pending.filter(S=>!k.has(S.id)),await c(p.file,f)}i(l,"flush");let u=setInterval(()=>n(l),1e4);return u.unref(),n(l),{close(){return t||(t=!0,clearInterval(u),d()),r},flush:i(()=>(n(l),r),"flush")}}i(iN,"createPonderActivityBridge");async function sN(e){let{teamId:t,...r}=e,n=await wr();return ho(n,t).request(r)}i(sN,"requestHostedPonder");var NQ=b.object({teamId:b.string().trim().min(1).max(240),resource:b.enum(["options","policies","definitions","serving-targets"]),method:b.enum(["GET","POST"]),body:b.record(b.string(),b.unknown()).optional()}).strict();async function cN(e){let t=NQ.parse(e);if(t.method==="POST"&&t.resource==="options")throw new Error("Learning options are read-only.");let r=sI({teamId:t.teamId,path:`/connected-evidence/learning/${t.resource}`,method:t.method,...t.method==="POST"?{body:t.body??{}}:{}});if(t.method==="GET"&&t.resource==="options"){let[n,o]=await Promise.all([r,sI({teamId:t.teamId,path:"/ponder/settings",method:"GET"})]);return{...n,ponderBindingId:o.bindingId}}return r}i(cN,"requestConversationLearning");import{randomUUID as UQ}from"node:crypto";import{isDeepStrictEqual as qQ}from"node:util";function dN(e){async function t(n){let o=await e.getSession(n);if(!o)throw new Wo("This task no longer exists. Choose an available task before sending.",404);let[a,s,c,d]=await Promise.all([e.store.taskInboxSnapshot(n),e.latestTurn(n),e.readiness(o),e.approvalBlocked(n)]),l=Ch(o),u=Mh(o.provider),p=o.metadata?.nativeResumeAvailable===!0&&!o.metadata?.nativeBranch&&o.nativeAgent?.provider===o.provider&&o.nativeAgent.cwd===o.cwd,m=o.archived||o.status==="closed"?"This task is closed or archived.":o.workspaceKind==="sandbox"||o.workspaceKind==="sandbox_template"||o.workspaceKind==="sandbox_app"?"This target is hosted; use its hosted message action.":o.metadata?.nativeHistoryProjection===!0&&!p||lu(o.id)?"This imported conversation has not been qualified for original-session continuation. Open it in the desktop and check its connection before sending a task follow-up.":!u||!l?"This conversation has no managed local session. Imported history alone cannot receive messages.":c.available?null:c.reason??"The original managed agent is unavailable.",w=L1(o,s?.id??null);return{sessionId:n,provider:o.provider,title:o.title,managedSessionId:l,targetRevision:w,latestTurnId:s?.id??null,activeTurnId:a.activeTurnId,paused:a.paused,approvalBlocked:d,canSendFollowup:m===null,canSteer:m===null&&c.canSteer&&a.acceptingInput&&!d,unavailableReason:m,inbox:a}}i(t,"inspect");async function r(n,o){let a=gO.parse(o),s={localManagedMessage:{targetRevision:a.expectedTargetRevision,recommendationId:a.recommendationId??null,authority:a.authority}},c=a.mode==="steer"?"steer":"queued",d,l=0;for(;!d;){let p=await e.store.taskInputsForSession(n,{afterSequence:l,limit:500});if(d=p.find(m=>m.senderKind==="user"&&m.senderSessionId===null&&m.idempotencyKey===a.idempotencyKey),p.length<500)break;l=p.at(-1).sequence}if(d){let p=d.payload.localManagedMessage;if(d.kind!==c||d.body!==a.prompt||d.expectedTurnId!==(a.expectedTurnId??null)||!qQ(p,s.localManagedMessage))throw new Wo("This message identity was already used with different content or target. Refresh before sending a changed message.");return d}let u=await t(n);if(!u.canSendFollowup)throw new Wo(u.unavailableReason,422);if(u.targetRevision!==a.expectedTargetRevision)throw new Wo("The managed target changed. Refresh and review the message before sending.");if(a.mode==="steer"&&(!u.canSteer||u.activeTurnId!==a.expectedTurnId))throw new Wo("The observed turn is no longer accepting corrections. Your text was not sent to another turn; refresh or queue a follow-up.");return e.admit({id:UQ(),sessionId:n,senderSessionId:null,senderKind:"user",kind:c,body:a.prompt,payload:s,idempotencyKey:a.idempotencyKey,expectedTurnId:a.expectedTurnId??null,replyTo:null})}return i(r,"send"),{inspect:t,send:r}}i(dN,"createLocalManagedMessaging");function lN(e){return async t=>{let r=mo.safeParse(t.metadata?.ponderLocalOwner);if(!r.success)return{available:!1,reason:"This OpenPond task has no captured local account owner."};try{let n=await Mn(),o=(await e()).defaultTeamId,a=fo(n,r.data.installationId,o,new URL(n.apiBaseUrl).origin);return!a||!ar(t,a)?{available:!1,reason:"Sign in to this task's original OpenPond account and workspace before sending."}:{available:!0,reason:null}}catch{return{available:!1,reason:"The captured OpenPond account could not be authenticated."}}}}i(lN,"createOpenPondManagedReadiness");import{access as FQ,constants as uN}from"node:fs/promises";import{delimiter as zQ,extname as WQ,isAbsolute as VQ,join as GQ}from"node:path";async function JQ(e){let t=process.platform==="win32"&&!WQ(e)?[e,...(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(n=>e+n)]:[e],r=VQ(e)?t:(process.env.PATH??"").split(zQ).filter(Boolean).flatMap(n=>t.map(o=>GQ(n,o)));for(let n of r)try{return await FQ(n,process.platform==="win32"?uN.F_OK:uN.X_OK),!0}catch{}return!1}i(JQ,"executableAvailable");function bg(e){return async t=>{let r=i(a=>({available:!1,canSteer:!1,reason:a}),"unavailable");if(t.provider==="openpond"){if(!(await e.configProvider("openpond"))?.enabled)return r("Enable OpenPond in Providers before sending.");let s=await e.openPondStatus(t);return s.available?{available:!0,canSteer:!0,reason:null}:r(s.reason??"The captured OpenPond account is unavailable.")}if(t.provider==="codex"){if(!t.codexThreadId||!t.cwd)return r("This conversation has no original managed Codex thread and working directory.");let a=await e.codexStatus();return!a.enabled||!a.available?r(a.reason??"The local Codex installation is unavailable or disabled."):{available:!0,canSteer:!0,reason:null}}if(!Zi(t.provider)||!t.nativeAgent)return r("Imported history has no qualified managed session.");let n=await e.configProvider(t.provider);if(!n?.enabled)return r("Enable the original local agent in Providers before sending.");let o;try{o=Br(t.provider,n)}catch(a){return r(a instanceof Error?a.message:"The local agent configuration is invalid.")}if(t.nativeAgent.provider!==t.provider||t.nativeAgent.instanceId!==o.instanceId||!t.cwd||t.nativeAgent.cwd!==t.cwd)return r("The original agent installation, account configuration or working directory changed. Restore it before sending.");if(!await JQ(o.command))return r("The original local agent executable is unavailable. Restore it before sending.");if(e.nativeStatus){let a=await e.nativeStatus(t);if(!a.available)return r(a.reason??"The original local agent is unavailable.")}return{available:!0,canSteer:!1,reason:null}}}i(bg,"createLocalManagedReadiness");function pN(e){let t=mo.parse(e.owner),r,n=new Map,o=i(c=>({eligible:!1,reason:c}),"unavailable"),a=bg({configProvider:i(async c=>e.providers.providers[c]??null,"configProvider"),codexStatus:i(async()=>{let c=await(r??=e.codexStatus());return{enabled:e.providers.providers.codex?.enabled??!1,available:c.available&&c.authHealth==="signed_in",reason:c.authHealth==="signed_in"?null:"Sign in to the original local Codex installation before adding this task."}},"codexStatus"),openPondStatus:i(async c=>ar(c,t)?{available:!0,reason:null}:{available:!1,reason:"The selected local account changed."},"openPondStatus")});async function s(c){if(!c.currentProfile&&!c.profileWorkflowBinding&&!c.profileComponentBinding)return{eligible:!0,reason:null};let d=JSON.stringify([c.currentProfile??null,c.profileWorkflowBinding??null,c.profileComponentBinding??null]),l=n.get(d);return l||(l=(async()=>{try{if(c.profileWorkflowBinding||c.profileComponentBinding){let u=await e.loadHarness(c);if(!u||c.profileWorkflowBinding&&!u.workflow)return o("The task's original released Profile workflow or component is unavailable.")}else if(c.currentProfile){let u=await e.loadProfile(c.currentProfile);if(u.mode!=="local"||u.activeProfile!==c.currentProfile.profileId||u.error||u.setupGate.status!=="ready")return o("Restore this task's original Profile and complete its setup before adding it.")}return{eligible:!0,reason:null}}catch{return o("The task's original Profile or released workflow could not be loaded.")}})(),n.set(d,l)),l}return i(s,"profileAvailable"),async c=>{if(!Xi(c))return o("Only an eligible local task without an existing account owner can be added.");if(!Mh(c.provider)||!Ch(c))return o("This conversation has no qualified original managed session.");let d={...c,metadata:{...c.metadata,ponderLocalOwner:t}},l;try{l=await a(d)}catch{return o("The original managed provider is unavailable.")}return l.available?s(c):o(l.reason??"The original managed provider is unavailable.")}}i(pN,"createLocalOwnerAttachmentInspection");function mN(e){return{localManagedMessaging:dN({store:e.store,getSession:i(async r=>await e.store.getSession(r)?e.getSession(r):null,"getSession"),latestTurn:i(r=>e.store.latestTurnForSession(r),"latestTurn"),approvalBlocked:i(async r=>{let n=await e.store.latestTurnForSession(r);return n?.status==="in_progress"&&(await e.store.pendingApprovals()).some(o=>o.sessionId===r&&!!o.turnId&&(o.turnId===n.id||o.turnId===n.providerTurnId))},"approvalBlocked"),readiness:bg({openPondStatus:lN(e.loadAppPreferences),configProvider:i(async r=>(await e.localByokRuntimeState()).settings.providers[r]??null,"configProvider"),codexStatus:i(async()=>{let r=await e.refreshCodexStatus();return{enabled:(await e.localByokRuntimeState()).settings.providers.codex?.enabled??!1,available:r.available&&r.authHealth==="signed_in",reason:r.authHealth==="signed_in"?null:"Sign in to the original local Codex installation before sending."}},"codexStatus")}),admit:i(r=>e.turnRunner.admitUserLocalMessage(r),"admit")}),prepareOwnerAttachment:i(async r=>pN({owner:r,providers:structuredClone((await e.localByokRuntimeState()).settings),codexStatus:e.refreshCodexStatus,loadProfile:e.loadProfile,loadHarness:e.loadHarness}),"prepareOwnerAttachment"),conversationLearningRequestPayload:cN,ponderRequestPayload:i(async r=>sN({...r,teamId:(await e.loadAppPreferences()).defaultTeamId??void 0}),"ponderRequestPayload")}}i(mN,"createDesktopManagedAgentRoutes");function fN(e){let{loadAppPreferences:t,...r}=e;return iN({...r,teamId:i(async()=>(await t()).defaultTeamId,"teamId"),request:i(async(n,o,a)=>ho(o,a).request(n),"request")})}i(fN,"createDesktopPonderActivityBridge");function hN(e){return fN({storeDir:e.storeDir,deviceId:e.installation.installationId,subscribe:e.subscribe,loadAppPreferences:e.loadAppPreferences,sessionTitle:i(async t=>(await e.store.getSession(t))?.title??"Local chat","sessionTitle"),sessionOwner:i(async t=>{let r=mo.safeParse((await e.store.getSession(t))?.metadata?.ponderLocalOwner);return r.success?r.data:null},"sessionOwner"),workflows:i(async()=>({workflows:await e.store.listChatWorkflows(),runs:await e.store.listChatWorkflowRuns(null,500)}),"workflows"),warn:e.warn})}i(hN,"createServerPonderActivity");import eZ from"node:path";import{rm as KQ}from"node:fs/promises";import gN from"node:path";var YQ=b.object({source:b.literal("openpond_git"),repositoryId:b.string().min(1),profileId:b.string().min(1)}).strict(),wN=b.object({schemaVersion:b.literal("openpond.profileExperimentOrigin.v1"),apiBaseUrl:b.string().url(),actorId:b.string().min(1),teamId:b.string().min(1),projectId:b.string().min(1),ref:YQ,sourceRevision:b.string().regex(/^[a-f0-9]{40}$/),sourcePath:b.string(),sourceFilesHash:b.string().regex(/^[a-f0-9]{64}$/)}).strict(),yN=b.object({id:b.string(),teamId:b.string(),name:b.string(),metadata:b.record(b.string(),b.unknown())});function ei(e){let t=i(async(u,p,m)=>{let w=xe(u.token);w.set("x-openpond-team-id",u.teamId),m!==void 0&&w.set("content-type","application/json");let g=await(e.fetch??fetch)(new URL(p,u.apiBaseUrl),{method:m===void 0?"GET":"POST",headers:w,...m===void 0?{}:{body:JSON.stringify(m)}});if(!g.ok)throw new ee("local_profile_origin_access_denied","This Profile origin is unavailable to the current account.",g.status===401?401:403);let f=await g.text();if(Buffer.byteLength(f)>4e7)throw new Error("Profile origin response exceeds its size limit.");return JSON.parse(f)},"request");function r(u){let p=b.object({sourceUpload:b.object({sourceCommitSha:b.string().regex(/^[a-f0-9]{40}$/)}),manifest:b.object({profiles:b.record(b.string(),b.unknown())})}).parse(u.metadata.hostedProfileRepo);return{revision:p.sourceUpload.sourceCommitSha,profiles:Object.keys(p.manifest.profiles)}}i(r,"source");async function n(u,p,m={}){let w=await e.resolveAccess();if(w.actorId!==u.actorId||w.teamId!==u.teamId||w.apiBaseUrl.replace(/\/$/,"")!==u.apiBaseUrl.replace(/\/$/,"")||u.projectId!==u.ref.repositoryId||p&&(p.ownerScope.kind!=="team"||p.ownerScope.id!==u.teamId||p.location!=="local"||p.metadata.selectionEligible!==!1))throw new ee("local_profile_origin_access_denied","The cached Profile belongs to another actor or origin.",403);let g=b.object({project:yN}).parse(await t(w,`/v1/projects/${encodeURIComponent(u.projectId)}?teamId=${encodeURIComponent(w.teamId)}`)),f=r(g.project);if(g.project.id!==u.projectId||g.project.teamId!==u.teamId||m.requireCurrentRevision!==!1&&f.revision!==u.sourceRevision||!f.profiles.includes(u.ref.profileId))throw new ee("local_profile_origin_changed","The original committed Profile origin has changed or is no longer accessible.",409);return w}i(n,"authorize");async function o(u,p){for(let m of await e.store.listHarnessWorkspaces()){let w=wN.safeParse(m.metadata.profileExperimentOrigin);if(!w.success||A(w.data.ref)!==A(u))continue;let g=p?await e.store.getHarnessReleaseRecord(p.contentHash):m.currentChannel.release&&await e.store.getHarnessReleaseRecord(m.currentChannel.release.contentHash);if(!(!g||g.workspaceId!==m.id||p&&g.harnessRelease.id!==p.id))return{workspace:m,release:g,origin:w.data}}throw new ee("local_profile_origin_access_denied","The exact Profile has no trusted installed origin on this device.",403)}i(o,"cached");let a=i(async(u,p,m,w)=>{let g=wN.parse(u.metadata.profileExperimentOrigin);if(A(g.ref)!==A(m))throw new Error("Profile origin reference was substituted.");await n(g,u,w);let f=`profile-origin-${A([g.apiBaseUrl,g.actorId,g.teamId,g.ref,g.sourceRevision]).slice(0,40)}`;if(u.id!==f||g.sourcePath!==gN.join(e.storeDir,"library","profile-experiment-origins",f))throw new Error("Profile origin provenance was substituted.");if(await gH(g.sourcePath)!==g.sourceFilesHash)throw new Error("Installed Profile tree differs from its complete committed source.");let y=await Yl(g.sourcePath,m.profileId);if(y.error||!y.sourcePath)throw new Error("The installed Profile source is incomplete.");let h=await GC({storeDir:e.storeDir,workspaceId:u.id,name:m.profileId,profile:y,repositoryId:m.repositoryId,sourceRevision:g.sourceRevision});if(h.harnessRelease.id!==p.id||h.harnessRelease.contentHash!==p.contentHash)throw new Error("Installed Profile source differs from its original compiler identity.");await n(g,u,w)},"authority");async function s(u,p){let m=await o(u,p?.harnessRelease);if(await a(m.workspace,{id:m.release.harnessRelease.id,contentHash:m.release.harnessRelease.contentHash},u),p&&p.sourceRevision!==m.origin.sourceRevision)throw new Error("Selected Profile source revision changed.");return Wc({store:e.store,ref:u,release:m.release,sourceRevision:m.origin.sourceRevision})}i(s,"workflows");let c=new Map;async function d(u,p,m,w){let g=p.profileId,f=A([w.apiBaseUrl,w.actorId,w.teamId,p,m]),y=c.get(f);if(y)return y;let h=(async()=>{let k=`profile-origin-${A([w.apiBaseUrl,w.actorId,w.teamId,p,m]).slice(0,40)}`,S=await e.store.getHarnessWorkspace(k);if(!S){let I=gN.join(e.storeDir,"library","profile-experiment-origins",k),v={schemaVersion:"openpond.profileExperimentOrigin.v1",apiBaseUrl:w.apiBaseUrl,actorId:w.actorId,teamId:w.teamId,projectId:u.id,ref:p,sourceRevision:m,sourcePath:I,sourceFilesHash:"0".repeat(64)};await n(v),await KQ(I,{recursive:!0,force:!0});let R=await hH({root:I,revision:m,read:i(_=>t(w,`/v1/projects/${encodeURIComponent(u.id)}/files`,{teamId:w.teamId,..._}),"read")}),T={...v,sourceFilesHash:A(R)};await n(T);let P=await Yl(I,g);if(P.error||!P.sourcePath)throw new Error("Profile source is invalid.");S=(await VC({store:e.store,storeDir:e.storeDir,id:k,ownerId:w.actorId,name:g,profile:P,sourceRevision:m,repositoryId:u.id,selectionEligible:!1,originOwnerScope:{kind:"team",id:w.teamId},originMetadata:{profileExperimentOrigin:T}})).workspace}return S})();c.set(f,h);try{return await h}finally{c.delete(f)}}i(d,"install");async function l(){let u=await e.resolveAccess(),{projects:p}=b.object({projects:b.array(yN).max(1e3)}).parse(await t(u,`/v1/projects?teamId=${encodeURIComponent(u.teamId)}&role=profile`)),m=[],w=0;for(let g of p.slice(0,100))try{if(g.teamId!==u.teamId)continue;let f=r(g);for(let y of f.profiles.slice(0,20)){if(++w>100)return m;let h={source:"openpond_git",repositoryId:g.id,profileId:y};await d(g,h,f.revision,u),await s(h),m.push({ref:h,name:`${g.name} / ${y} (installed origin)`})}}catch{}return m}return i(l,"discover"),{authority:a,workflows:s,discover:l,resolveRef:i(async(u,p,m)=>{let w={source:"openpond_git",repositoryId:u,profileId:p},g=await o(w,m);return await a(g.workspace,m,w),w},"resolveRef")}}i(ei,"createLocalProfileOriginAdapter");function yr(e){let t=ff(e),r=e.modelResources?.rewards??(e.learningResources?Zm(e.taskset).rewards:[]);if(t&&A(Ll(t,r))!==A(e.taskset.graders))throw new ee("local_grader_closure_conflict","The retained Reward closure differs from the released Dataset graders.",422);return e.taskset.graders.map(n=>{let o=t?.sources.find(s=>s.graderId===n.id),a=o&&r.find(s=>s.id===o.reward.id&&s.revision===o.reward.revision&&s.contentHash===o.reward.contentHash);return{id:n.id,version:n.version,contentHash:A(n),name:a?.name??("config"in n&&n.config.operator==="final_answer_equals_expected"?"Answer accuracy":`${n.kind.replaceAll("_"," ")} grader`),feedbackKey:a?Jm(a):`grader_${A(n.id).slice(0,24)}`,release:a?{id:a.id,revision:a.revision,contentHash:a.contentHash}:null}})}i(yr,"localPackageGraders");function kg(e,t){let r=yr(e),n=t?t.map(o=>{let a=r.find(s=>s.id===o.id&&s.version===o.version&&s.contentHash===o.contentHash);if(!a)throw new ee("local_grader_pin_unavailable","Select an exact grader from the retained Dataset package.",422);return{...a,mappings:o.mappings}}):r;try{return IC(n)}catch(o){throw new ee("experiment_grader_feedback_conflict",o instanceof Error?o.message:"Grader selection conflicts.",422)}}i(kg,"selectLocalPackageGraders");function vN(e,t,r,n=!1,o=!1,a=!1){let s=Ze(t),c=e.configuration.request;if(s.contentHash!==e.packageHash||A(c.taskset)!==A({id:s.taskset.id,revision:s.taskset.revision,contentHash:s.taskset.contentHash}))throw new ee("local_dataset_pin_conflict","Local execution requires the exact retained Dataset package.",422);if(c.policy.kind!=="hosted_chat"&&!(c.policy.kind==="hosted_harness"&&a))throw new ee("local_target_not_qualified","This local execution path requires a qualified exact target owner.",422);if(e.model.providerId==="claude-code"&&(XQ(s)||s.taskset.environment.kind!=="text"||s.taskset.tools.length))throw new ee("claude_environment_not_admitted","The Claude process adapter requires a text Dataset with no environment tools. Additional tool owners require explicit admission.",422);let d=c.policy.kind==="hosted_chat"?c.policy.harness:void 0;if(d&&!n)throw new ee("local_harness_not_qualified","A released Harness must execute through its native turn owner.",422);let l=zl(s);if(s.taskset.policy.connectedAppScopes.length)throw new ee("local_connected_scope_not_qualified","This Dataset requires connected scopes that have not been admitted for local execution.",422);for(let u of s.taskset.capabilities.filter(p=>p.required)){if(u.id==="tools"&&a&&u.scopes.every(m=>["work_exec","work_save_output"].includes(m)&&s.taskset.tools.some(w=>w.name===m)))continue;if(u.id!=="private-verifier")throw new ee("local_capability_not_qualified","This Dataset requires capabilities not supplied by the local execution owner.",422);if((u.scopes.length?u.scopes:s.taskset.policy.hiddenGraderRefs).some(m=>!s.taskset.policy.hiddenGraderRefs.includes(m)||!s.taskset.graders.some(w=>w.id===m&&w.privileged&&w.kind!=="human")))throw new ee("local_capability_not_qualified","The required private grader scope has no supported exact local grader owner.",422)}if(!l&&s.taskset.tools.length&&!a)throw new ee("local_tool_target_not_qualified","This Dataset's tools require a released native target executor.",422);if(l?.execution.javascript.executionServices?.length&&!o)throw new ee("local_prepared_environment_not_qualified","This Dataset requires prepared compute services that are not yet bound to the local execution owner.",422);if(s.taskset.environment.kind!=="text"&&!l)throw new ee("local_environment_unavailable","The released Dataset has no supported local environment executor.",422);if(d&&(l||s.taskset.environment.kind!=="text"))throw new ee("local_harness_environment_not_qualified","This native Harness requires a compatible text Dataset.",422);return c.population.map(u=>{let p=s.taskset.tasks.find(y=>y.id===u.taskId);if(!p)throw new ee("local_population_unavailable","The selected task is absent from this immutable Dataset release.",422);let m=IE(p);if((m.artifactRefs.length||p.requiredOutputs?.length)&&!(a&&c.policy.kind==="hosted_harness"))throw new ee("local_work_target_not_qualified","This Dataset requires document input or Work output capabilities not supplied by this local model target.",422);let w=l?.assets.find(y=>y.id===l.execution.javascript.module.id),g=l?.assets.find(y=>y.id===p.privilegedContextRef);if(l&&(!w||!g))throw new ee("local_environment_assets_missing","Private environment resources are missing from the retained package.",422);let f={kind:"model",id:`local-case-${A([r,u.receiptId]).slice(0,48)}`,taskId:p.id,model:e.model,...d?{harness:d}:{},instructions:y0(s),input:m.input,policyVisibleContext:m.policyVisibleContext,timeoutMs:s.taskset.environment.defaultTimeoutMs,environment:l?{kind:"javascript",definition:l.execution.javascript,asset:w,initialState:JSON.parse(Zr(g,g.asset)),seed:Number(u.seed)}:{kind:"text"}};return{receiptId:u.receiptId,taskId:u.taskId,seed:u.seed,request:e1.parse({...f,admissionHash:A(f)})}})}i(vN,"localExperimentAdmissions");function XQ(e){return!!zl(e)}i(XQ,"executionForClaude");import{readFile as QQ}from"node:fs/promises";import ZQ from"node:path";async function Tr(e,t,r,n){let o=await e.getHarnessReleaseRecord(t.contentHash),a=o&&await e.getHarnessWorkspace(o.workspaceId);if(!o||!a||o.harnessRelease.id!==t.id||a.location!=="local"||a.metadata.sourceLayout!=="openpond.harnessSourceManifest.v1")throw new ee("local_profile_source_unavailable","The exact Profile Harness is unavailable.",403);let s=a.metadata.profileExperimentOrigin!==void 0||a.metadata.experimentCandidateOrigin!==void 0;if(s){if(!n||!r)throw new ee("local_profile_origin_access_denied","This source requires its authenticated origin.",403);await n(a,t,r)}else{if(a.ownerScope.kind!=="personal"||a.ownerScope.id!=="desktop-personal"||typeof o.harnessRelease.metadata.profileRepositoryId=="string"||typeof o.agentSnapshot.metadata.profileRepositoryId=="string")throw new ee("local_profile_origin_access_denied","The Profile is not device-owned.",403);let m=o.harnessRelease.metadata.profile;if(r&&(r.source!=="local"||m?.id!==r.profileId||m.repositoryId&&m.repositoryId!==r.repositoryId))throw new ee("local_profile_origin_access_denied","The retained Harness differs from this exact Profile reference.",403);if(a.metadata.selectionEligible===!1&&(!r||!m?.repositoryId||m.repositoryId!==r.repositoryId||a.id!==`${qH}${A({ref:r,sourceRevision:m.sourceRevision}).slice(0,24)}`))throw new ee("local_profile_origin_access_denied","This explicit Profile release requires its canonical accepted reference.",403)}let c=await rM({workspace:a,release:o}),d=new Map;for(let m of o.harnessRelease.files)d.set(m.path,await QQ(ZQ.join(o.bundlePath,"source",...m.path.split("/"))));let l=Ea({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,files:d}),u=Xm(o);$m({sourcePackage:l,expectedRelease:t,baseSystemPrompt:"",runtimeId:"openpond.native-profile-experiment.v1",maxContextCharacters:262144,tools:u.map(m=>({name:m.name,inputSchema:m.inputSchema,definition:{type:"function",function:{name:m.name,description:m.description,parameters:m.inputSchema}}}))});let p=await e.getHarnessWorkspace(a.id);if(!p||A(p.ownerScope)!==A(a.ownerScope)||A(p.metadata)!==A(a.metadata))throw new ee("local_profile_origin_access_denied","Profile source ownership changed during admission.",403);return s&&await n(a,t,r),c}i(Tr,"resolveLocalProfileExperimentSource");var Mu=b.string().min(1).max(240),bN=b.string().regex(/^[a-f0-9]{64}$/),aS=b.object({schemaVersion:b.literal("openpond.experimentCandidateOrigin.v1"),candidateId:Mu,actorId:Mu,teamId:Mu,baseWorkspaceId:Mu,baseProfileRef:qo,baseProfileSourceRevision:b.string().min(1).max(500),baseRelease:b.object({id:Mu,contentHash:bN}).strict(),frozenRevision:b.number().int().positive(),frozenHash:bN}).strict();function kN(e){async function t(n,o,a){let s=aS.parse(n.metadata.experimentCandidateOrigin),c=await e.actorId(),d=await e.teamId();if(s.actorId!==c||s.teamId!==d||n.metadata.selectionEligible!==!1||n.location!=="local"||n.ownerScope.kind!=="personal"||n.ownerScope.id!==c)throw new Error("Candidate origin is unavailable to this account or placement.");let l=await e.improvements.read({actorId:c,teamId:d},s.candidateId);if(!l.frozen||["draft","authoring","failed","cancelled","declined"].includes(l.status)||l.ownerWorkspaceId!==s.baseWorkspaceId||A(l.profileRef)!==A(s.baseProfileRef)||l.baseProfileSourceRevision!==s.baseProfileSourceRevision||A(l.baseRelease)!==A(s.baseRelease)||l.frozen.candidateRevision!==s.frozenRevision||A(l.frozen)!==s.frozenHash||A(o)!==A(l.frozen.release)||A(n.currentChannel.release)!==A(o)||a&&A(a)!==A(l.profileRef))throw new Error("Candidate origin differs from its durable owner and exact frozen revision.");if(await Tr(e.store,l.baseRelease,l.profileRef,e.authorizeBaseOrigin),await e.actorId()!==c||await e.teamId()!==d)throw new Error("Candidate account changed during admission.");return l}i(t,"require");async function r(n){let o=await e.store.getHarnessReleaseRecord(n.contentHash);if(!o||o.harnessRelease.id!==n.id)return null;let a=await e.store.getHarnessWorkspace(o.workspaceId);return a?.metadata.experimentCandidateOrigin!==void 0?{workspace:a,release:o}:null}return i(r,"workspace"),{hasOrigin:i(async n=>!!await r(n),"hasOrigin"),authority:i((async(n,o,a)=>{await t(n,o,a)}),"authority"),async resolveRef(n,o,a){let s=await r(a);if(!s)throw new Error("Candidate source is unavailable.");let c=await t(s.workspace,a);if(c.profileRef.repositoryId!==n||c.profileRef.profileId!==o)throw new Error("Candidate Profile reference changed.");return c.profileRef},async workflows(n,o){if(!o)throw new Error("Candidate discovery requires its frozen source reference.");let a=await r(o.harnessRelease);if(!a)throw new Error("Candidate source is unavailable.");let s=await t(a.workspace,o.harnessRelease,n);if(o.sourceRevision!==s.frozen.profileSourceRevision)throw new Error("Candidate Profile source revision changed.");let c=await Wc({store:e.store,release:a.release,ref:n,sourceRevision:o.sourceRevision});return await t(a.workspace,o.harnessRelease,n),c}}}i(kN,"createLocalExperimentCandidateOriginAdapter");function dd(e){return async(t,r)=>{let n=await e.identity(),o=await e.resolveAccess(),a={baseUrl:o.apiBaseUrl,apiKey:o.token,teamId:n.teamId},s=new hr(a),c=new Qi(a),d=new rn(a),l=ei({...e,resolveAccess:i(async()=>({...await e.resolveAccess(),...await e.identity()}),"resolveAccess")});async function u(){if(A(await e.identity())!==A(n))throw new Error("The external Dataset account or workspace changed.");let w=await e.resolveAccess();if(w.apiBaseUrl.replace(/\/$/,"")!==o.apiBaseUrl.replace(/\/$/,"")||w.token!==o.token)throw new Error("The external Dataset connection changed.")}i(u,"current");async function p(){if(await u(),t.profileId!==r.profileRef.profileId)throw new Error("The external Dataset recipe names another Profile.");let w=await e.store.getHarnessReleaseRecord(r.harnessRelease.contentHash);if(!w||w.harnessRelease.id!==r.harnessRelease.id)throw new Error("The exact released Profile is unavailable.");let g=await e.store.getHarnessWorkspace(w.workspaceId);if(!g)throw new Error("The released Profile owner is unavailable.");let f=g.metadata.experimentCandidateOrigin===void 0?null:aS.parse(g.metadata.experimentCandidateOrigin);if(f&&(f.actorId!==n.actorId||f.teamId!==n.teamId||g.ownerScope.kind!=="personal"||g.ownerScope.id!==n.actorId||g.metadata.selectionEligible!==!1||A(f.baseProfileRef)!==A(r.profileRef)))throw new Error("The candidate source belongs to another owner or Profile.");if(r.profileRef.source==="local"){let I=await et(),v=await ft(r.profileRef);if(!I.profiles.some(R=>A(R.ref)===A(r.profileRef))||v.error||!v.sourcePath||v.activeProfile!==r.profileRef.profileId)throw new Error("The original Profile is no longer installed for this owner.")}else if(f){let I=await e.store.getHarnessWorkspace(f.baseWorkspaceId);if(!I)throw new Error("The candidate's original Profile is unavailable.");await l.authority(I,f.baseRelease,r.profileRef)}else await l.authority(g,r.harnessRelease,r.profileRef);let y=await _c({workspaceId:typeof w.agentSnapshot.metadata.workspaceId=="string"?w.agentSnapshot.metadata.workspaceId:w.workspaceId,sourceDir:eZ.join(w.bundlePath,"source")});if(y.harnessRelease.contentHash!==r.harnessRelease.contentHash||En(y).protectedClosureHash!==t.protectedProfileClosureHash)throw new Error("The original Profile's protected evaluator closure changed.");await u();let h=await s.getByRelease(t.dataset,{expectedPackageHash:t.packageHash});if(await u(),t.recordedOrigin){let I=t.recordedOrigin,v=await c.recordedExecution(I.execution.id),R=await d.scoringPass(I.originalEvidence.id),T=await d.scoringResult(I.originalEvidence.id);if(await u(),v.contentHash!==I.execution.contentHash||A(v.request.dataset)!==A(t.dataset)||T.manifest.population.length!==I.members.length||R.request.executionKind!=="recorded_evidence"||R.request.execution.id!==v.id||T.result.contentHash!==I.originalEvidence.contentHash||A(T.manifest.evaluators)!==A(t.evaluators))throw new Error("The original recorded grading evidence differs from this rerun recipe.");for(let[P,x]of I.members.entries()){let _=v.sources.filter(D=>D.boundaryId===x.caseId);if(_.length!==1)throw new Error("The original recorded case has no unique retained source cutoff.");let E=_[0],C=h.taskset.tasks.find(D=>D.id===x.caseId),O=C&&oI.parse(C.input.connectedEvidenceRef);if(!O||E.boundaryId!==x.caseId||E.id!==x.sourceId||E.snapshotHash!==x.snapshotHash||E.boundaryRevisionHash!==x.boundaryRevisionHash||A(O)!==A({id:E.id,snapshotHash:E.snapshotHash,boundaryId:E.boundaryId,boundaryRevisionHash:E.boundaryRevisionHash})||A(T.manifest.population[P])!==A({caseId:x.caseId,seed:x.seed,fixtureId:x.fixtureId}))throw new Error("The rerun changed an original ordered source cutoff.")}}let k=t.gradingSource?{pass:await d.scoringPass(t.gradingSource.pass.id),evidence:await d.scoringResult(t.gradingSource.evidence.id)}:void 0;await u();let S=Df({binding:t,packageValue:h,graders:yr(h),actualGrading:k});return await u(),S}i(p,"read");let m=await p();return{binding:t,packageValue:m,authorize:i(async()=>{if(A(await p())!==A(m))throw new Error("The external Dataset authority changed during preparation.")},"authorize")}}}i(dd,"createLocalExternalDatasetPreparation");function IN(e){let t=dd(e);async function r(o){let a=Rc(o),s=await e.identity();if(s.actorId!==a.actorId||s.teamId!==a.teamId)throw new Error("The advanced evaluation owner changed.");let c=await e.loadEvidence(s,a.evidence);if(c.result.status!=="completed"||c.manifest.dataset.id!==a.externalDatasetBinding.dataset.id||c.manifest.dataset.contentHash!==a.externalDatasetBinding.dataset.contentHash)throw new Error("Advanced Refiner evaluation requires exact completed source evidence from the selected Dataset.");if(!(await mh(e.storeDir)).releases.some(y=>y.id===a.refinerRelease.id&&y.contentHash===a.refinerRelease.contentHash))throw new Error("The exact admitted Refiner release is unavailable.");let l={profileRef:a.profileRef,sourceRevision:a.sourceRevision,harnessRelease:a.baselineRelease,workflows:[]},u=await t(a.adaptationDatasetBinding,l);await u.authorize();let p=await t(a.externalDatasetBinding,l),m=p.packageValue;if(m.environment.contentHash!==a.environmentPolicy.environmentHash)throw new Error("The advanced environment release changed.");if(a.mode==="downstream_adaptation"&&m.environment.contract.kind!=="work")throw new Error("This native Refiner adapter requires a released Work environment.");if(m.taskset.tools.some(y=>y.name==="web_search"||y.name==="web_fetch"))throw new Error("Advanced live web tools require a separately admitted budget and frozen-observation owner.");if(m.environment.contract.networkPolicy!=="none")throw new Error("This advanced adapter cannot bound live external tool charges. Select a resettable environment with network disabled; live-tool evaluation needs its own qualified admission owner.");if(u.packageValue.contentHash!==m.contentHash)throw new Error("This native adapter requires the same exact released package for adaptation and independent holdout.");let w=a.adaptationTaskIds.map(y=>u.packageValue.taskset.tasks.find(h=>h.id===y)),g=a.holdoutTaskIds.map(y=>m.taskset.tasks.find(h=>h.id===y));if(w.some(y=>!y||y.split!==a.adaptationSplit)||g.some(y=>!y||y.split!==a.holdoutSplit))throw new Error("The advanced population changed its ordered split membership.");let f=new Set(w.map(y=>y.clusterKey));if(g.some(y=>f.has(y.clusterKey)))throw new Error("Private holdout families overlap adaptation evidence.");if(m.verifierSet.graders.some(y=>y.kind==="human"||y.kind==="model_judge"&&y.calibrationStatus!=="passed"))throw new Error("Advanced evaluation needs executable deterministic or separately calibrated graders; human preference labels cannot become online reward.");if(await p.authorize(),a.mode==="review_quality"){let y=m.taskset.metadata.advancedRefinerReview;if(y?.outputConvention!=="openpond.refinerReviewOutput.v1"||A(y.contextEvidence)!==A(a.evidence))throw new Error("Review quality needs grounded independent labels bound to the exact retained context evidence.")}if(A(await e.identity())!==A(s))throw new Error("The advanced evaluation account changed during source admission.");return p}i(r,"read");async function n(o,a){if(await r(o),!e.localExperiments||!o.evidence.id.startsWith("local-"))throw new Error("This native review adapter requires actual retained local execution context. Hosted trace import requires a separately qualified current-owner context transport.");let s=RO.parse(await e.localExperiments().result({teamId:o.teamId,id:o.evidence.id}));if(s.execution.ownerActorId!==o.actorId)throw new Error("The review context belongs to another actor.");let c=s.cases.filter(f=>f.taskId===a&&f.status==="completed");if(c.length!==1)throw new Error("Choose one exact completed retained context per independent review case.");let d=c[0],l=d.profileNative??d.native;if(!l)throw new Error("The selected context has no actual native session/turn provenance.");if(l.outputHash!==A(d.output))throw new Error("The retained review output differs from its native execution.");let u=await e.store.getSession(l.sessionId),p=await e.store.getTurn(l.turnId);if(!u||!p||p.sessionId!==u.id||p.status==="in_progress")throw new Error("The actual retained review context is unavailable.");let m=await e.store.runtimeEventsForTurn(p.id),w=new Set(l.runtimeEventRefs),g=m.filter(f=>w.has(f.id));if(g.length!==w.size)throw new Error("The exact native review trace is incomplete.");return await r(o),{session:u,turn:p,events:g,case:d,traceHash:l.traceHash}}return i(n,"reviewContext"),{read:r,reviewContext:n,evidence:i(async o=>(await r(o),e.loadEvidence({actorId:o.actorId,teamId:o.teamId},o.evidence)),"evidence"),authorize:i(async o=>{await(await r(o)).authorize()},"authorize")}}i(IN,"createAdvancedRefinerEvaluationSource");import{randomUUID as RN}from"node:crypto";var wo=b.string().min(1).max(240),iS=b.object({id:wo,targetId:wo,jobId:wo,hostedModelId:wo,artifactHash:b.string().length(64),registryArtifactId:wo,registryArtifactHash:b.string().length(64),deploymentId:wo,servingPoolId:wo,authorizationHash:b.string().length(64),priorBindingId:wo,leaseId:wo.nullable(),bindingId:wo.nullable(),activatedAt:b.string().datetime().nullable(),canarySeconds:b.number().int().min(30).max(600),status:b.enum(["queued","claimed","canary","active","rolled_back","failed"])}).passthrough(),SN=b.object({request:iS,authorized:b.boolean()});function PN(e){let t=null,r=null,n=!1;async function o(g,f){return e.store.saveConversationServingExecution({...g,...f,revision:g.revision+1,updatedAt:new Date().toISOString()},g.revision)}i(o,"save");async function a(g,f){return SN.parse(await e.request(g.teamId,`serving-requests/${encodeURIComponent(f)}?ownerInstanceId=${encodeURIComponent(g.ownerInstanceId)}`))}i(a,"inspect");async function s(g,f,y){return iS.parse(await e.request(g.teamId,"serving-requests",{action:y,requestId:f.id,targetId:g.id,ownerInstanceId:g.ownerInstanceId,leaseId:f.leaseId,bindingId:f.bindingId,restoredBindingId:f.restoredBindingId,failure:f.failure}))}i(s,"command");async function c(g,f){let y=(await e.store.listConversationServingGrants()).find(h=>h.id===g.id);if(!y)throw new Error("The native serving grant disappeared.");y.expectedBindingId!==f&&await e.store.saveConversationServingGrant({...y,expectedBindingId:f,revision:y.revision+1,updatedAt:new Date().toISOString()},y.revision)}i(c,"updateExpectedBinding");async function d(g,f,y){let h=f.bindingId?await e.store.getModelBinding(f.bindingId):(await e.store.listModelBindings()).find(S=>S.promotedBy===`conversation:${f.id}`);if(!h){f=await o(f,{status:"failed",failure:y}),await s(g,f,"fail");return}let k=await e.store.getActiveModelBinding({profileId:g.profileId,role:g.role,roleTargetId:g.roleTargetId});if(f=await o(f,{status:"rolling_back",bindingId:h.id,failure:y}),k?.id===h.id){let S=await e.training.rollbackModelBinding({bindingId:h.id,rolledBackBy:`conversation:${f.id}:rollback`});if(!S.activeBinding)throw new Error("The authorized prior Model binding was not restored.");f=await o(f,{restoredBindingId:S.activeBinding.id})}else{let S=(await e.store.listModelBindings()).find(I=>I.status==="active"&&I.promotedBy===`conversation:${f.id}:rollback`&&I.priorBindingId===h.id);if(!S)throw new Error("The serving target changed outside this operation; automatic rollback cannot replace another owner's choice.");f=await o(f,{restoredBindingId:S.id})}await e.synchronization.reconcile(),await s(g,f,"rollback"),f=await o(f,{status:"rolled_back"}),await c(g,f.restoredBindingId)}i(d,"rollback");async function l(g,f){let y=f.request,h=(await e.store.listConversationServingExecutions(g.id)).find(T=>T.id===y.id);if(!h){if(!g.enabled||!f.authorized||g.authorizedConfigurationHash!==y.authorizationHash||y.hostedModelId!==g.hostedModelId||y.priorBindingId!==g.expectedBindingId)throw new Error("The requested serving change differs from the exact native grant.");let T=iS.parse(await e.request(g.teamId,"serving-requests",{action:"claim",requestId:y.id,targetId:g.id,ownerInstanceId:g.ownerInstanceId,leaseId:null,bindingId:null,restoredBindingId:null,failure:null}));if(!T.leaseId)throw new Error("The serving owner did not receive a retained lease.");h=await e.store.saveConversationServingExecution(tH.parse({id:y.id,grantId:g.id,revision:1,jobId:y.jobId,artifactHash:y.artifactHash,priorBindingId:y.priorBindingId,bindingId:null,restoredBindingId:null,status:"prepared",leaseId:T.leaseId,canarySeconds:y.canarySeconds,activatedAt:null,failure:null,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),0)}if(["superseded","rolled_back","failed"].includes(h.status))return;if(h.status==="active"){if(!g.enabled)return;let T=h.bindingId?await e.store.getModelBinding(h.bindingId):null;if(!T||T.status!=="active"){await o(h,{status:"superseded"});return}let P=await e.store.getModelArtifactLineage(T.modelArtifactLineageId),_=(await e.registry.listRegistry(g.teamId)).deployments.find(E=>E.id===P?.managedServing?.canonicalDeploymentId);(!_||["degraded","failed","deleted","deleting"].includes(_.state))&&await d(g,h,"The current candidate deployment failed runtime health after activation.");return}if(y.status==="active"){await o(h,{status:"active"}),await c(g,y.bindingId);return}if(!g.enabled||!f.authorized||h.status==="rolling_back")return d(g,h,"Serving authority was revoked or the retained rollout requires rollback.");if(Date.now()-Date.parse(h.createdAt)>=12e5)return d(g,h,"The serving rollout exceeded its authorized reconciliation deadline.");if(await s(g,h,"renew"),h.status==="prepared"||h.status==="binding"){await e.hosting.pullProject({hostedProjectId:g.hostedModelId,profileId:g.profileId}),await e.training.refreshManagedRunEvidence(h.jobId),await e.synchronization.reconcile();let T=(await e.store.listModelBindings()).find(P=>P.promotedBy===`conversation:${h.id}`);if(T){if(T.status!=="active"||T.profileId!==g.profileId||T.role!==g.role||T.roleTargetId!==g.roleTargetId)throw new Error("The retained serving promotion changed outside its owner.");h=await o(h,{status:"canary",bindingId:T.id,activatedAt:T.promotedAt})}else{let P=(await e.store.listModelArtifactLineage()).filter(O=>O.jobId===h.jobId&&O.status==="imported");if(P.length!==1)throw new Error("The exact hosted candidate is not imported into the serving owner.");if(P[0].managedServing?.canonicalArtifactId!==y.registryArtifactId||P[0].managedServing?.canonicalDeploymentId!==y.deploymentId)throw new Error("The candidate differs from the exact authorized serving deployment.");let x=await e.store.getTrainingArtifact(P[0].artifactId);if(!x||x.sha256!==h.artifactHash)throw new Error("The serving candidate's immutable artifact changed.");let _=(await e.store.listConversationServingGrants()).find(O=>O.id===g.id),E=await a(g,h.id);if(!_?.enabled||_.authorizedConfigurationHash!==y.authorizationHash||!E.authorized)return d(g,h,"Serving authority changed immediately before native activation.");h=await o(h,{status:"binding"});let C=await e.training.bindModel({profileId:g.profileId,modelId:P[0].id,role:g.role,roleTargetId:g.roleTargetId,promotedBy:`conversation:${h.id}`,expectedActiveBindingId:h.priorBindingId,servingGrant:{id:_.id,expectedRevision:_.revision,authorizationHash:y.authorizationHash}});h=await o(h,{status:"canary",bindingId:C.id,activatedAt:C.promotedAt})}}await e.synchronization.reconcile();let k=await e.store.getModelBinding(h.bindingId),S=k?await e.store.getModelArtifactLineage(k.modelArtifactLineageId):null;if(!k||k.status!=="active"||!S?.managedServing)return d(g,h,"The active binding lost its verified serving projection.");let v=(await e.registry.listRegistry(g.teamId)).deployments.find(T=>T.id===S.managedServing.canonicalDeploymentId);if(!v||["degraded","failed","deleted","deleting"].includes(v.state))return d(g,h,"The candidate deployment failed the runtime canary.");if(v.state!=="ready")return;let R=await s(g,h,"canary");Date.now()-Date.parse(R.activatedAt)>=h.canarySeconds*1e3&&(await s(g,h,"complete"),await o(h,{status:"active"}),await c(g,h.bindingId))}i(l,"advance");async function u(){for(let g of await e.store.listConversationServingGrants())try{g.enabled&&await e.request(g.teamId,"serving-targets",{action:"heartbeat",targetId:g.id,ownerInstanceId:g.ownerInstanceId});let f=(await e.store.listConversationServingExecutions(g.id)).filter(h=>!["superseded","rolled_back","failed"].includes(h.status));for(let h of f)await l(g,await a(g,h.id));if(!g.enabled||!g.authorizedConfigurationHash)continue;let y=b.object({requests:b.array(SN)}).parse(await e.request(g.teamId,`serving-requests?targetId=${encodeURIComponent(g.id)}&ownerInstanceId=${encodeURIComponent(g.ownerInstanceId)}`));for(let h of y.requests)f.some(k=>k.id===h.request.id)||await l(g,h)}catch(f){let y=(await e.store.listConversationServingExecutions(g.id)).filter(h=>!["active","superseded","rolled_back","failed"].includes(h.status));for(let h of y)await o(h,{failure:f instanceof Error?f.message.slice(0,2e3):"Serving reconciliation failed."})}}i(u,"once");function p(){return n?Promise.resolve():(t||(t=u().finally(()=>{t=null})),t)}i(p,"reconcile");function m(){if(n||r||t)return;let g=i(()=>{r=null,p().finally(()=>{n||(r=setTimeout(g,1e4),r.unref?.())})},"tick");g()}i(m,"start");async function w(){n=!0,r&&clearTimeout(r),r=null,await t}return i(w,"close"),{start:m,close:w,reconcile:p}}i(PN,"createConversationServingWorker");var ds=b.string().trim().min(1).max(240),Ig=b.object({profileId:ds,modelId:ds});function xN(e){async function t(o,a,s){let c=await e.resolveAccess();if(c.teamId!==o)throw new Error("Select the serving grant's authorized workspace.");let d=xe(c.token);d.set("X-OpenPond-Team-Id",o),d.set("content-type","application/json");let l=await fetch(`${c.apiBaseUrl}/v1/connected-evidence/learning/${a}`,{headers:d,redirect:"error",signal:AbortSignal.timeout(2e4),method:s===void 0?"GET":"POST",...s===void 0?{}:{body:JSON.stringify(s)}}),u=await l.json();if(!l.ok)throw new Error(`Serving owner request failed (${l.status}): ${u.code??"request_failed"}`);return u}i(t,"request");async function r(o){let a=Ig.parse(o),s=await e.store.getModelProject(a.modelId);if(!s||s.profileId!==a.profileId||!s.hosted)throw new Error("Select a hosted Model in the serving Profile.");let c=await e.resolveAccess();if(s.hosted.teamId!==c.teamId||s.hosted.apiOrigin!==new URL(c.apiBaseUrl).origin)throw new Error("The serving Model belongs to a different workspace.");return{model:s,access:c}}i(r,"scoped");let n=PN({...e,request:t});return{start:n.start,close:n.close,reconcile:n.reconcile,async state(o){let{model:a,access:s}=await r(o),c=(await e.store.listConversationServingGrants()).filter(u=>u.profileId===a.profileId&&u.hostedModelId===a.hosted.projectId&&u.teamId===s.teamId),d=(await e.store.listModelBindings()).filter(u=>u.profileId===a.profileId&&u.status==="active"),l=await t(s.teamId,"policies");return{grants:c,bindings:d,policies:l.filter(u=>u.configuration.configuration?.id===a.hosted.projectId).map(u=>({...u,servingAuthorized:c.some(p=>p.enabled&&p.authorizedConfigurationHash===A(u.configuration)&&p.id===u.configuration.serving?.targetId)})),executions:(await Promise.all(c.map(u=>e.store.listConversationServingExecutions(u.id)))).flat()}},async register(o){let a=Ig.extend({projectId:ds,bindingId:ds}).strict().parse(o),{model:s,access:c}=await r(a),d=await e.store.getModelBinding(a.bindingId);if(!d||d.status!=="active"||d.profileId!==s.profileId)throw new Error("Select an active OpenPond binding in this Profile with a retained rollback target.");let u=(await e.store.listConversationServingGrants()).find(m=>m.teamId===c.teamId&&m.profileId===s.profileId&&m.role===d.role&&m.roleTargetId===d.roleTargetId&&m.projectId===a.projectId&&m.hostedModelId===s.hosted.projectId&&m.enabled);if(u)return await t(c.teamId,"serving-targets",{action:"register",targetId:u.id,projectId:u.projectId,ownerInstanceId:u.ownerInstanceId,profileId:u.profileId,role:u.role,roleTargetId:u.roleTargetId,expectedBindingId:u.expectedBindingId}),u;let p=eH.parse({id:`conversation-serving-${RN()}`,revision:1,ownerInstanceId:`serving-owner-${RN()}`,teamId:c.teamId,profileId:s.profileId,projectId:a.projectId,hostedModelId:s.hosted.projectId,role:d.role,roleTargetId:d.roleTargetId,expectedBindingId:d.id,policyId:null,authorizedConfigurationHash:null,enabled:!0,updatedAt:new Date().toISOString()});return await e.store.saveConversationServingGrant(p,0),await t(c.teamId,"serving-targets",{action:"register",targetId:p.id,projectId:p.projectId,ownerInstanceId:p.ownerInstanceId,profileId:p.profileId,role:p.role,roleTargetId:p.roleTargetId,expectedBindingId:p.expectedBindingId}),p},async authorize(o){let a=Ig.extend({grantId:ds,policyId:ds,expectedRevision:b.number().int().positive()}).strict().parse(o),{model:s,access:c}=await r(a),d=(await e.store.listConversationServingGrants()).find(p=>p.id===a.grantId&&p.enabled&&p.profileId===s.profileId&&p.hostedModelId===s.hosted.projectId&&p.teamId===c.teamId);if(!d)throw new Error("The native serving grant is unavailable.");let l=await t(c.teamId,"serving-targets",{action:"authorize",targetId:d.id,ownerInstanceId:d.ownerInstanceId,policyId:a.policyId,expectedRevision:a.expectedRevision}),u=await e.store.saveConversationServingGrant({...d,revision:d.revision+1,policyId:a.policyId,authorizedConfigurationHash:b.string().length(64).parse(l.authorizedConfigurationHash),updatedAt:new Date().toISOString()},d.revision);return await n.reconcile(),u},async revoke(o){let a=Ig.extend({grantId:ds}).strict().parse(o),{model:s,access:c}=await r(a),d=(await e.store.listConversationServingGrants()).find(u=>u.id===a.grantId&&u.profileId===s.profileId&&u.hostedModelId===s.hosted.projectId&&u.teamId===c.teamId);if(!d)throw new Error("The native serving grant is unavailable.");let l=await e.store.saveConversationServingGrant({...d,enabled:!1,authorizedConfigurationHash:null,revision:d.revision+1,updatedAt:new Date().toISOString()},d.revision);return await t(c.teamId,"serving-targets",{action:"revoke",targetId:l.id,ownerInstanceId:l.ownerInstanceId}),await n.reconcile(),l}}}i(xN,"createConversationServingOwner");var Ft=b.string().trim().min(1).max(240),_N=b.number().int().positive(),tZ=b.enum(["dataset","evaluator","model","training_configuration","training_run","harness","environment","experiment","learning_policy","deployment"]),rZ=b.object({kind:tZ,resourceId:Ft,release:ik.nullable(),role:b.enum(["training","validation","holdout","target","reward","evaluation","serving","source"])}).strict(),nZ=b.discriminatedUnion("kind",[b.object({kind:b.literal("model"),providerId:Ft,modelId:Ft,artifact:ik.nullable(),messages:b.array(b.object({role:b.enum(["system","user","assistant"]),content:b.string().max(1e5)}).strict()).max(100)}).strict(),b.object({kind:b.literal("harness"),profileRepositoryId:Ft,source:Yb}).strict(),b.object({kind:b.literal("agent"),source:TE}).strict(),b.object({kind:b.literal("suite"),profileRepositoryId:Ft,suiteId:Ft,sources:b.array(Yb).min(1).max(1e3)}).strict().superRefine((e,t)=>{let r=e.sources[0],n=new Set;for(let[o,a]of e.sources.entries())n.has(a.definitionId)&&t.addIssue({code:"custom",path:["sources",o],message:"Suite definitions must be unique."}),n.add(a.definitionId),(a.profileId!==r.profileId||a.sourceRevision!==r.sourceRevision||a.catalogHash!==r.catalogHash||ao(a.harnessRelease)!==ao(r.harnessRelease))&&t.addIssue({code:"custom",path:["sources",o],message:"Suite checks must belong to the same pinned Profile source and Harness release."})})]),TN=b.object({name:b.string().trim().min(1).max(200),description:b.string().max(1e4),targets:b.array(b.object({id:Ft,name:b.string().trim().min(1).max(200),target:nZ}).strict()).max(100),defaultTargetId:Ft.nullable(),resources:b.array(rZ).max(1e3)}).strict().superRefine((e,t)=>{new Set(e.targets.map(r=>r.id)).size!==e.targets.length&&t.addIssue({code:"custom",path:["targets"],message:"Target identities must be unique."}),e.defaultTargetId&&!e.targets.some(r=>r.id===e.defaultTargetId)&&t.addIssue({code:"custom",path:["defaultTargetId"],message:"Default target must belong to this Project."}),new Set(e.resources.map(r=>ao(r))).size!==e.resources.length&&t.addIssue({code:"custom",path:["resources"],message:"Resource links must be unique."})}),EN=b.object({schemaVersion:b.literal("openpond.trainingProject.v1"),id:Ft,teamId:Ft,creatorUserId:Ft,ownerScope:b.enum(["workspace","personal"]).optional(),revision:_N,content:TN,archived:b.boolean(),createdAt:b.string().datetime(),updatedAt:b.string().datetime()}).strict(),oZ=b.object({operationId:Ft,id:Ft,expectedRevision:b.number().int().nonnegative(),content:TN,ownerScope:b.enum(["workspace","personal"]).optional()}).strict(),aZ=b.object({operationId:Ft,expectedRevision:_N,archived:b.boolean()}).strict(),iZ=b.object({teamId:Ft,projects:b.array(EN).max(100),nextCursor:Ft.nullable()}).strict(),ETe=b.object({operation:b.enum(["evaluate","train","enable_learning","accept_candidate","serve"]),support:b.enum(["supported","unsupported"]),state:b.enum(["ready","needs_setup","blocked"]),reasons:b.array(b.object({code:Ft,message:b.string().min(1).max(2e3),field:b.string().nullable(),action:b.enum(["choose_target","choose_data","choose_evaluator","configure_runtime","request_access","configure_budget","wait","review_evidence"]).nullable()}).strict()).max(100)}).strict().superRefine((e,t)=>{e.state==="ready"&&(e.support!=="supported"||e.reasons.length)&&t.addIssue({code:"custom",message:"Ready operations must be supported with no blockers."}),e.state!=="ready"&&!e.reasons.length&&t.addIssue({code:"custom",message:"Unavailable operations must explain the next step."})}),zt=class{static{i(this,"OpenPondTrainingProjectClient")}constructor(e){this.options=e;let t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash||!e.apiKey.trim()||!e.teamId.trim())throw new Error("A clean API origin and workspace credentials are required.");this.baseUrl=t.toString().replace(/\/+$/,"")}options;baseUrl;async list(e={}){let t=iZ.parse(await this.request(`?${new URLSearchParams(e.cursor?{cursor:e.cursor}:{})}`,"GET",void 0,e.signal));if(t.teamId!==this.options.teamId||t.projects.some(r=>r.teamId!==this.options.teamId))throw new Error("Project list workspace mismatch.");return t}async get(e,t){return this.readback(await this.request(`/${encodeURIComponent(e)}`,"GET",void 0,t),e)}async save(e,t){let r=oZ.parse(e),n=this.readback(await this.request(`/${encodeURIComponent(r.id)}`,"PUT",r,t),r.id);if(n.revision!==r.expectedRevision+1||ao(n.content)!==ao(r.content))throw new Error("Project write revision mismatch.");if(r.ownerScope&&n.ownerScope!==r.ownerScope)throw new Error("Project owner scope mismatch.");return n}async archive(e,t,r){let n=aZ.parse(t),o=this.readback(await this.request(`/${encodeURIComponent(e)}/archive`,"POST",n,r),e);if(o.revision!==n.expectedRevision+1||o.archived!==n.archived)throw new Error("Project archive receipt mismatch.");return o}readback(e,t){let r=EN.parse(e);if(r.id!==t||r.teamId!==this.options.teamId)throw new Error("Project identity mismatch.");return r}async request(e,t,r,n){let o=await(this.options.fetch??fetch)(`${this.baseUrl}/v1/training-projects${e}`,{method:t,signal:n,redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"X-OpenPond-Team-Id":this.options.teamId,"Content-Type":"application/json"},...r===void 0?{}:{body:JSON.stringify(r)}});if(!o.ok)throw new Error(`Project request failed (${o.status}).`);return o.json()}};function AN(e){return async t=>{let r=await e.identity(),n=await e.access(),o=new zt({baseUrl:n.apiBaseUrl,apiKey:n.token,teamId:r.teamId}),a=new Set,s,c=new Set;for(let l=0;;l++){if(l>=100)throw new Error("Project associations exceeded the supported launch bound.");let u=await o.list(s?{cursor:s}:{});for(let p of u.projects)!p.archived&&p.content.resources.some(m=>m.kind==="training_configuration"&&m.resourceId===t)&&a.add(p.id);if(!u.nextCursor)break;if(c.has(u.nextCursor))throw new Error("Project association pagination did not advance.");c.add(u.nextCursor),s=u.nextCursor}if(a.size>1)throw new Error("This training configuration belongs to several Projects. Retain one explicit Project association before starting.");let d=await e.identity();if(d.actorId!==r.actorId||d.teamId!==r.teamId)throw new Error("The active account changed before training admission.");return Vo.parse({schemaVersion:"openpond.trainingActivityAuthority.v1",...r,projectId:[...a][0]??null})}}i(AN,"createTrainingActivityAuthorityResolver");import{randomUUID as SZ}from"node:crypto";import{mkdir as PZ,readFile as RZ,rename as xZ,rm as _Z,writeFile as TZ}from"node:fs/promises";import KN from"node:path";import{readFile as GN}from"node:fs/promises";import _g from"node:path";import{createHash as sZ}from"node:crypto";import{createReadStream as cZ}from"node:fs";import{copyFile as dZ,mkdir as sS,readFile as CN,stat as lZ,writeFile as cS}from"node:fs/promises";import ls from"node:path";async function MN(e){if(!e.plan.compatibility.compatible)throw new Error("Training Plan is incompatible and cannot be bundled.");if(!e.plan.dataPolicy.exportApproved)throw new Error("Training export approval is required before bundle creation.");if(e.taskset.contentHash!==e.plan.tasksetHash)throw new Error("Training Plan references a different Taskset hash.");let t=new Set(e.plan.dataPolicy.approvedSourceIds),r=e.projectedTrainingData?{...e.projectedTrainingData,sourcePath:e.projectedTrainingData.path}:uZ(e.taskset,e.plan,t);if(r.exampleCount===0)throw new Error("Training Bundle has no approved training examples.");await sS(e.directory,{recursive:!0});let n=[{path:"recipe.json",role:"recipe",content:ot(e.plan.recipe)},{path:"policy.json",role:"policy",content:ot({tasksetId:e.taskset.id,tasksetHash:e.taskset.contentHash,sourceIds:e.plan.dataPolicy.approvedSourceIds,retentionDays:e.plan.dataPolicy.retentionDays,region:e.plan.dataPolicy.region,trainingData:{exampleCount:r.exampleCount,eligibleRows:r.eligibleRows,selectionSeed:r.selectionSeed,selectionStrategy:r.selectionStrategy,taskIdsHash:r.taskIdsHash}})},{path:"provenance.json",role:"provenance",content:ot(e.taskset.authoringProvenance)}],o=[{path:"data/train.jsonl",sha256:r.contentHash,sizeBytes:r.sizeBytes,role:"task_data"}],a=ls.join(e.directory,"data/train.jsonl");await sS(ls.dirname(a),{recursive:!0}),"sourcePath"in r?await dZ(r.sourcePath,a):await cS(a,r.content,{encoding:"utf8",mode:384});let s=await pZ(a);if(s.contentHash!==r.contentHash||s.sizeBytes!==r.sizeBytes)throw new Error("Projected training data changed while the Bundle was created.");for(let m of n){let w=ls.join(e.directory,m.path);await sS(ls.dirname(w),{recursive:!0}),await cS(w,m.content,"utf8"),o.push({path:m.path,sha256:Re(m.content),sizeBytes:Buffer.byteLength(m.content),role:m.role})}let c=new Date().toISOString(),d={schemaVersion:"openpond.trainingBundle.v1",id:`training_bundle_${A([e.plan.contentHash,o]).slice(0,24)}`,planId:e.plan.id,tasksetId:e.taskset.id,tasksetHash:e.taskset.contentHash,recipeHash:A(e.plan.recipe),files:[{path:"manifest.json",sha256:"00000000",sizeBytes:0,role:"manifest"},...o],totalSizeBytes:o.reduce((m,w)=>m+w.sizeBytes,0),sourceIds:e.plan.dataPolicy.approvedSourceIds,excludedSourceIds:e.taskset.sourceRefs.map(m=>m.id).filter(m=>!t.has(m)),containsRawChats:!1,containsSecrets:!1,containsHiddenGraderAssets:!1,createdAt:c,contentHash:"00000000"},l=ah.parse(d),u=A({...l,contentHash:"",files:l.files.map(m=>m.path==="manifest.json"?{...m,sha256:"",sizeBytes:0}:m)}),p=ah.parse({...l,contentHash:u,files:l.files.map(m=>m.path==="manifest.json"?{...m,sha256:u,sizeBytes:0}:m)});return await cS(ls.join(e.directory,"manifest.json"),ot(p),"utf8"),p}i(MN,"buildTrainingBundle");function uZ(e,t,r){if(t.recipe.method!=="sft"&&t.recipe.method!=="dpo"&&t.recipe.method!=="grpo"&&t.recipe.method!=="ppo")throw new Error(`Training method ${t.recipe.method} cannot produce task data.`);let n=new Set(e.learningSignals.demonstrations.flatMap(p=>p.approved&&p.taskId?[p.taskId]:[])),o=e.metadata.learning===void 0?null:zE.parse(e.metadata.learning),a=i(p=>o?o.admissions.find(m=>m.taskId===p.id)?.supervisedTarget??null:p.expectedOutput,"supervisedTarget"),s=t.recipe.method==="grpo"?t.recipe.rollout.seed:t.recipe.method==="ppo"?t.recipe.policyOptimization.seed:t.recipe.optimizer.seed;if(t.recipe.method==="dpo"){let p=e.learningSignals.preferences.filter(g=>g.approved&&g.sourceRefs.every(f=>r.has(f))).map(g=>({priority:A([e.contentHash,s,"preference",g.id]),record:{id:g.id,prompt:g.prompt,chosen:g.chosen,rejected:g.rejected,sourceRefs:g.sourceRefs}})).sort((g,f)=>g.priority.localeCompare(f.priority)||g.record.id.localeCompare(f.record.id)).slice(0,t.recipe.dataset.maxPairs),m=p.length?`${p.map(g=>JSON.stringify(g.record)).join(`
|
|
13
|
+
`,{mode:384}),await II(lt.dirname(r),{recursive:!0,mode:448}),ns(r)&&await Zc(r,o),await Zc(n,r),s}catch(s){throw await ed(n,{recursive:!0,force:!0}),ns(o)&&!ns(r)&&await Zc(o,r),s}}i(vB,"materializeExtension");function BY(e,t,r,n){let o=lt.join(t,"current");return{...e,sourcePath:o,readmePath:e.readmePath?lt.join(o,e.readmePath):null,installedAt:r,updatedAt:n,skills:e.skills.map(a=>({...a,sourcePath:lt.join(o,a.relativePath)}))}}i(BY,"installedExtension");async function bB(e,t){await ed(xI(e,t),{recursive:!0,force:!0})}i(bB,"finalizeMaterialization");async function kB(e,t){let r=Xa(t.replace(/^github:/,"")),n=Su(e,r.owner,r.repo),o=xI(e,t);await ed(n,{recursive:!0,force:!0}),ns(o)&&await Zc(o,n)}i(kB,"rollbackMaterialization");async function SI(e,t){let r=Su(e,t.owner,t.repo),n=lt.join(r,"current"),o=(await DY(lt.join(r,"extension.json")).catch(()=>null))?.isFile()??!1,a=t.validationMessages.filter(s=>s!=="Installed files are missing.");return o||a.push("Installed files are missing."),{...t,sourcePath:n,readmePath:t.readmePath?lt.join(n,lt.basename(t.readmePath)):null,skills:t.skills.map(s=>({...s,sourcePath:lt.join(n,s.relativePath)})),validationStatus:a.length===0?"valid":"error",validationMessages:a}}i(SI,"hydrateExtension");function IB(e){if(e.validationStatus!=="valid")throw new Ne(`Extension contains invalid skills: ${e.validationMessages.join(" ")}`,{code:"extension_invalid"})}i(IB,"assertInstallable");function Iu(e,t,r){let n=new Map;for(let a of r)n.set(a,"a shipped OpenPond skill");for(let a of t)for(let s of a.skills)n.set(s.name,a.id);let o=e.skills.map(a=>({name:a.name,owner:n.get(a.name)})).filter(a=>!!a.owner);if(o.length!==0)throw new Ne(`Skill name conflict: ${o.map(a=>`${a.name} (${a.owner})`).join(", ")}.`,{code:"extension_skill_conflict",status:409})}i(Iu,"assertSkillNamesAvailable");function $Y(e,t,r){if(e.extensions.some(n=>n.id===t.id))throw new Ne(`${t.owner}/${t.repo} is already installed.`,{code:"extension_already_installed",status:409});return Iu(t,e.extensions,r),[...e.extensions,t].sort(_I)}i($Y,"appendInstalledExtension");function NY(e,t,r){return tg(e,t.id),Iu(t,e.extensions.filter(n=>n.id!==t.id),r),e.extensions.map(n=>n.id===t.id?t:n).sort(_I)}i(NY,"replaceInstalledExtension");function UY(e,t){let r=new Map;for(let n of t)r.set(n,"built-in");for(let n of e)for(let o of n.skills){let a=r.get(o.name);if(!a){r.set(o.name,n.id);continue}let s=`Skill name conflicts with ${a}: ${o.name}`;o.validationStatus="error",o.validationMessages=[...new Set([...o.validationMessages,s])],n.validationStatus="error",n.validationMessages=[...new Set([...n.validationMessages,s])]}}i(UY,"markInstalledSkillConflicts");async function Qc(e){let t=typeof e=="function"?await e():e??[];return[...new Set(t.map(r=>r.trim()).filter(Boolean))]}i(Qc,"reservedSkillNames");function tg(e,t){let r=e.extensions.find(n=>n.id===t);if(r)return r;throw new Ne(`${t.replace(/^github:/,"")} is not installed.`,{code:"extension_not_installed",status:404})}i(tg,"requireInstalled");async function rs(e){let t=No(e,"extension_installations","registry")?.value;if(!t)return FY();if(t.schemaVersion!==rg||!Array.isArray(t.extensions)||!t.extensions.every(RB))throw new Error("Extension registry has an unsupported format.");return qY(t)}i(rs,"readRegistry");async function PI(e,t,r){await $l(lt.join(Bl(e).runtime,"extension-registry"),async()=>{let n=No(e,"extension_installations","registry"),o=r(await rs(e));Uo(e,"extension_installations","registry",{...o,schemaVersion:rg,updatedAt:t().toISOString()},n?.revision??null)})}i(PI,"writeRegistry");function qY(e){return{schemaVersion:rg,updatedAt:typeof e?.updatedAt=="string"?e.updatedAt:null,extensions:Array.isArray(e?.extensions)?e.extensions.filter(RB):[]}}i(qY,"normalizeRegistry");function FY(){return{schemaVersion:rg,updatedAt:null,extensions:[]}}i(FY,"emptyRegistry");function RB(e){if(!e||typeof e!="object")return!1;let t=e;return t.source==="github"&&typeof t.id=="string"&&typeof t.owner=="string"&&typeof t.repo=="string"&&typeof t.repositoryUrl=="string"&&typeof t.requestedRef=="string"&&typeof t.resolvedCommit=="string"&&Array.isArray(t.skills)}i(RB,"isStoredExtension");function xB(e,t){if(lt.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new Ne(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});let r=lt.resolve(e,...t.split("/")),n=`${lt.resolve(e)}${lt.sep}`;if(!r.startsWith(n))throw new Ne(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});return r}i(xB,"safeDestination");function Su(e,t,r){return lt.join(e,"github",t,r)}i(Su,"extensionDirectory");function xI(e,t){let r=Xa(t.replace(/^github:/,""));return`${Su(e,r.owner,r.repo)}.previous`}i(xI,"backupDirectory");async function RI(e,t,r){let n=t.replace(/[^a-z0-9.-]+/gi,"-");return $l(lt.join(e,".locks",n),r,LY)}i(RI,"withExtensionLock");function _I(e,t){return e.id.localeCompare(t.id)}i(_I,"extensionSort");import{createHash as zY,randomUUID as WY}from"node:crypto";function _B(e){let t=e.explicitKey?.trim();if(t)return t;let r=e.sourceHead?.trim()||"unknown-source",n=e.targetProjectId?.trim()||"no-target-project",o=VY(e.input).slice(0,16),a=`profile-push-run:${e.localHead}:${r}:${e.runtimeAgentId}:${n}:${o}`;return e.retry?`${a}:retry:${(e.randomId??WY)()}`:a}i(_B,"buildHostedRunIdempotencyKey");function VY(e){return zY("sha256").update(TI(e)).digest("hex")}i(VY,"hashStableJson");function TI(e){return e===void 0?"undefined":e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(t=>TI(t)).join(",")}]`:`{${Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${TI(r)}`).join(",")}}`}i(TI,"stableJsonStringify");function TB(e,t){return async()=>{let r=await Mn(),n=(await t()).defaultTeamId?.trim()||null;if(r.accountState.state!=="signed_in")return null;let o=ho(r,n??void 0),a=fo(r,e,n,o.audience);return a?{owner:a,credentialKey:GY("sha256").update(JSON.stringify([r.token,r.apiBaseUrl])).digest("hex"),request:o.request}:null}}i(TB,"remoteRelayAccount");async function EB(e){let r=(await Mn()).accountState,n=(await e()).defaultTeamId?.trim()||null,o=r.state==="signed_in"&&!!r.profile?.id,a=r.activeProfile?.baseUrl??r.baseUrl,s=null;if(a){let c=new URL(a);s={"https://openpond.ai":"https://openpond.ai","https://api.openpond.ai":"https://openpond.ai","https://staging.openpond.ai":"https://staging.openpond.ai","https://staging-api.openpond.ai":"https://staging.openpond.ai"}[c.origin]??null}return{state:o?"ready":"signed_out",account:o?{id:r.profile.id,label:r.label}:null,team:o&&n?{id:n}:null,webBaseUrl:s}}i(EB,"remoteRelayAccountStatus");import{createHash as JY}from"node:crypto";function AB(e){return async t=>{let r=await e.store.getRemoteDeviceReceipt(t.id);if(r&&(!["stop","approval"].includes(t.action)||r.state!=="admitted")){if(r.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");return r}if(t.action==="approval"){if(!e.resolveApproval||!t.payload.response)throw new Error("remote_approval_unavailable");let a=r??await e.store.admitRemoteDeviceApproval(t);if(a.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");(await e.store.getApproval(a.approvalId))?.status==="pending"&&await e.resolveApproval(a.approvalId,{decision:t.payload.response==="approve"?"accept":"decline"});let c={...a,state:"applied",revision:a.revision+1};return await e.store.saveRemoteDeviceReceipt(t,c),c}if(t.action==="stop"){let a=r??await e.store.admitRemoteDeviceStop(t);if(a.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");(a.turnId?await e.store.getTurn(a.turnId):null)?.status==="in_progress"&&await e.interrupt(a.localSessionId,"Stopped remotely at the user's request.",a.turnId);let c={...a,state:"applied",revision:a.revision+1};return await e.store.saveRemoteDeviceReceipt(t,c),c}let n={id:t.id,deviceId:t.deviceId,state:"admitted",revision:2,payloadHash:t.payloadHash,action:t.action,targetId:t.targetId,createdAt:new Date().toISOString(),expiresAt:t.deadline},o=await e.store.getTaskInput(`remote-input:${t.id}`);if(o){let a=o.payload.remoteDevice;if(a?.payloadHash!==t.payloadHash||a.deviceId!==t.deviceId)throw new Error("remote_command_identity_changed")}else{if(!["follow_up","steer","start"].includes(t.action))throw new Error("remote_action_unavailable");let a=t.localSessionId;if(t.action==="start"){if(!e.resolveStarter||!e.createReserved)throw new Error("remote_start_unavailable");let s=await e.resolveStarter(t);a=(await e.createReserved({...K1(s),title:t.payload.text?.slice(0,120)??"Remote task"},{sessionId:`remote-session-${JY("sha256").update(t.id).digest("hex")}`,operationId:t.id,payloadHash:t.payloadHash,owner:mo.parse(s.metadata?.ponderLocalOwner),remoteStarterSourceSessionId:s.id})).id}else{let s=await e.inspect(a);if(!s.canSendFollowup||t.action==="steer"&&!s.canSteer)throw new Error("remote_target_unavailable")}if(!t.payload.text?.trim())throw new Error("remote_message_required");o=await e.admit({id:`remote-input:${t.id}`,sessionId:a,senderSessionId:null,senderKind:"user",kind:t.action==="steer"?"steer":"queued",body:t.payload.text,idempotencyKey:`remote:${t.id}`,expectedTurnId:t.expectedTurnId??null,replyTo:null,payload:{remoteDevice:t}})}return n.localSessionId=o.sessionId,n.inputId=o.id,o.turnId&&(n.turnId=o.turnId),await e.store.saveRemoteDeviceReceipt(t,n),n}}i(AB,"createRemoteCommandExecutor");import{randomUUID as QY}from"node:crypto";import{createHash as YY,randomUUID as MB}from"node:crypto";var EI=MB(),CB=0;function ng(){return EI}i(ng,"remoteHistoryIncarnation");function og(e){let t=e<CB;return t&&(EI=MB()),CB=e,t}i(og,"observeRemoteHistorySequence");function XY(e,t){return Number.parseInt(za(t,e.latestTurnId).slice(0,13),16)}i(XY,"remoteTaskRevision");function Pu(e){return YY("sha256").update(JSON.stringify([EI,e.id,e.createdAt,67])).digest("hex")}i(Pu,"remoteHistoryGeneration");async function jB(e){let t=[];for(let r of e.sessions){if(!ar(r,e.owner)||r.systemKind||r.hiddenFromDefaultSidebar||["sandbox","sandbox_template","sandbox_app"].includes(r.workspaceKind??""))continue;let n=await e.inspect(r.id),o=await e.latestTurn?.(r.id),a=e.approvals?.find(s=>s.sessionId===r.id&&s.status==="pending"&&o?.status==="in_progress"&&o.id===n.activeTurnId&&!!s.turnId&&(s.turnId===o.id||s.turnId===o.providerTurnId)&&Q1(s));t.push({id:r.id,localSessionId:r.id,title:r.title,projectId:r.localProjectId??null,projectLabel:r.workspaceName??null,provider:r.provider,revision:XY(n,r),historyGeneration:Pu(r),createdAt:r.createdAt,updatedAt:r.updatedAt,lastEventSequence:0,activeTurnId:n.activeTurnId,approvalId:a?.id??null,archived:r.archived??!1,deleted:!1,state:a?"attention":n.activeTurnId?"running":o?.status==="failed"?"failed":o?.status==="completed"?"completed":"idle",capabilities:{followUp:n.canSendFollowup,steer:n.canSteer,stop:n.activeTurnId!==null&&n.managedSessionId!==null,approval:!!a,artifacts:!1}})}return t.sort((r,n)=>r.id.localeCompare(n.id))}i(jB,"captureRemoteTaskCatalog");function AI(e,t){let r=e.name==="turn.started"&&typeof e.args?.prompt=="string",n=r||e.name==="assistant.delta",o=["tool.started","tool.completed"].includes(e.name),a=["turn.started","turn.completed","turn.failed","turn.interrupted"].includes(e.name),s=["approval.requested","approval.resolved"].includes(e.name);if(!n&&!o&&!a&&!s)return null;let c=e.data&&typeof e.data=="object"?e.data:{},d=n?r?e.args.prompt:e.output??(typeof c.text=="string"?c.text:""):"",u=(e.name==="turn.started"?"in_progress":e.name==="turn.completed"?"completed":e.name==="turn.failed"?"failed":e.name==="turn.interrupted"?"interrupted":void 0)??(e.name==="approval.requested"?"pending":e.name==="approval.resolved"?typeof c.status=="string"?c.status:c.decision==="accept"?"accepted":c.decision==="acceptForSession"?"accepted_for_session":c.decision==="decline"?"declined":c.decision==="cancel"?"cancelled":e.status:e.status);return{id:e.id,sequence:t,type:n?"message":o?"tool":s?"approval":"state",...e.turnId?{turnId:e.turnId}:{},...n?{messageId:r?`user:${e.turnId??e.id}`:`assistant:${typeof c.nativeMessageId=="string"?c.nativeMessageId:typeof c.itemId=="string"?c.itemId:e.turnId??e.id}`,textMode:c.nativeMessageSnapshot===!0?"replace":"append"}:{},...n?{role:r?"user":"assistant"}:{},...d?{text:d}:{},...o&&e.action?{toolName:e.action.slice(0,200)}:{},...u?{status:u}:{},...s&&typeof(c.approvalId??c.id)=="string"?{approvalId:c.approvalId??c.id}:{}}}i(AI,"projectRemoteEvent");async function CI(e,t){if(!["approval.requested","approval.resolved"].includes(t.name)||!t.turnId)return t;let r=await e.turnByProviderTurnId(t.turnId);return r&&r.sessionId===t.sessionId?{...t,turnId:r.id}:t}i(CI,"normalizeRemoteEventTurn");function*MI(e,t,r=0){let n=AI(e,t);if(n){if(!n.text||n.type!=="message"){yield n;return}for(let o=r;o<n.text.length;o+=8e3)yield{...n,fragmentIndex:Math.floor(o/8e3),fragmentCount:Math.ceil(n.text.length/8e3),id:`${n.id}:${o}`,text:n.text.slice(o,o+8e3),textMode:o===0?n.textMode:"append"}}}i(MI,"projectRemoteEventChunks");async function OB(e){let t=await e.store.getSession(e.taskId);if(!t||!ar(t,e.owner))throw new Error("remote_task_not_owned");let r=await e.store.latestEventSequence();og(r);let n=Pu(t),o=e.outputs?await e.outputs(t):[],a=0,s=0,c=r,d=QY();if(e.cursor){let f=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"));if(f.generation!==n||f.taskId!==e.taskId||!Number.isSafeInteger(f.after)||f.after<0||!Number.isSafeInteger(f.watermark)||f.watermark<f.after||typeof f.snapshotId!="string"||!Number.isSafeInteger(f.fragment??0)||(f.fragment??0)<0)throw new Error("remote_history_resync_required");a=f.after,s=f.fragment??0,c=f.watermark,d=f.snapshotId}let l=await e.store.runtimeEventPageRows({sessionId:e.taskId,afterSequence:a,beforeSequence:null,limit:100}),u=[],p=0,m=a,w=s,g=l.entries.length<100;e:for(let f of l.entries){if(f.sequence>c){g=!0;break}let y=MI(await CI(e.store,f.event),f.sequence,w);for(let h of y){f.event.name==="turn.completed"&&(h.artifactIds=o.filter(S=>S.sourceTurnId===f.event.turnId).map(S=>S.id).slice(0,100));let k=Buffer.byteLength(JSON.stringify(h));if(p+k>2e5){g=!1;break e}u.push(h),p+=k,h.type==="message"&&(w+=h.text?.length??0)}if(m=f.sequence,w=0,m>=c){g=!0;break}}return{snapshotId:d,taskId:t.id,historyGeneration:n,watermark:c,items:u,nextCursor:g?null:Buffer.from(JSON.stringify({generation:n,taskId:t.id,after:m,watermark:c,snapshotId:d,fragment:w})).toString("base64url"),capturedAt:new Date().toISOString(),provenance:"live"}}i(OB,"readRemoteHistory");function HB(e){let{deps:t,current:r,subscriptions:n,scheduleCatalog:o,catalog:a,send:s,serial:c,disconnect:d,schedule:l}=e,u=0;return t.listen(p=>{let m=["session.started","session.updated","session.title.updated","session.closed","turn.started","turn.completed","turn.failed","turn.interrupted","approval.requested","approval.resolved"].includes(p.name);m&&o();let w=p.sessionId;if(!r().authority||!w||!n.has(w))return;let g=AI(p,p.sequence??0);if(!g)return;let f=Buffer.byteLength(JSON.stringify(g));if(u+f>so.socketQueueBytes){d({state:"reconnecting",reason:"relay_backpressure"}).then(l);return}u+=f,c(async()=>{let{selected:y,authority:h}=r();if(!y||!h||!n.has(w))return;let k=await t.store.getSession(w);if(!k||r().authority!==h||r().selected!==y)return;let{deviceOwnsLocalSession:S}=await import("./local-scope-HVF2GZ5W.js");if(S(k,y.owner)){m&&await a(),p.name==="turn.completed"&&(g.artifactIds=(await t.outputs(k)).filter(I=>I.sourceTurnId===p.turnId).map(I=>I.id).slice(0,100));for(let I of MI(await CI(t.store,p),p.sequence??0)){if(r().authority!==h||r().selected!==y)return;g.artifactIds&&(I.artifactIds=g.artifactIds),s({protocolVersion:1,type:"events",taskId:k.id,payload:{historyGeneration:Pu(k),items:[I]}})}}}).catch(()=>{d({state:"reconnecting",reason:"connection_failed"}).then(l)}).finally(()=>{u-=f})})}i(HB,"listenRemoteRelayEvents");var DB=b.object({deviceId:b.string(),epoch:b.string(),fence:b.number().int().positive(),grantRevision:b.number().int().positive(),leaseExpiresAt:b.string().datetime()}),jI=b.object({keys:b.array(b.object({keyId:b.string(),publicKey:b.string()})).max(10),artifactUploadOrigins:b.array(b.string().url()).max(10).default([])});import{randomUUID as tN}from"node:crypto";import OQ from"node:os";var vQ=Qr(C$(),1),bQ=Qr(mg(),1),kQ=Qr(nd(),1),IQ=Qr(zI(),1),SQ=Qr(GI(),1),PQ=Qr(ZI(),1),vg=Qr(wg(),1),tS=Qr($$(),1);var rS=vg.default;import{createHash as q$,randomUUID as RQ}from"node:crypto";import{mkdir as xQ,open as N$,readFile as _Q,rename as TQ,unlink as EQ}from"node:fs/promises";import nS from"node:path";var AQ=b.object({version:b.literal(1),disabled:b.array(b.string().regex(/^[a-f0-9]{64}$/)),devices:b.record(b.string(),b.string().uuid()).default({})}).strict();function Zo(e){return q$("sha256").update(JSON.stringify([e.installationId,e.profileId,e.ownerUserId,e.teamId,e.audience])).digest("hex")}i(Zo,"deviceOwnerKey");function U$(e){return q$("sha256").update(JSON.stringify([e.installationId,e.profileId,e.ownerUserId,e.audience])).digest("hex")}i(U$,"accountPreferenceKey");async function F$(e){let t=nS.join(e,"remote-relay"),r=nS.join(t,"preference.json");await xQ(t,{recursive:!0,mode:448});let n=new Set,o={};try{let s=AQ.parse(JSON.parse(await _Q(r,"utf8")));n=new Set(s.disabled),o=s.devices}catch(s){if(s.code!=="ENOENT")throw s}let a=Promise.resolve();return{enabled(s){return!n.has(U$(s))&&!n.has(Zo(s))},async capture(s){n.has(Zo(s))&&await this.set(s,!1)},deviceId(s){return o[Zo(s)]??null},setDeviceId(s,c){return this.set(s,this.enabled(s),c)},set(s,c,d){let l=a.then(async()=>{let u=new Set(n),p=U$(s),m=Zo(s);u.delete(m),c?u.delete(p):u.add(p);let w={...o,...d?{[m]:d}:{}},g=nS.join(t,`${RQ()}.tmp`);try{let f=await N$(g,"wx",384);try{await f.writeFile(JSON.stringify({version:1,disabled:[...u],devices:w})),await f.sync()}finally{await f.close()}await TQ(g,r);let y=await N$(t,"r");try{await y.sync()}finally{await y.close()}n=u,o=w}finally{await EQ(g).catch(f=>{if(f.code!=="ENOENT")throw f})}});return a=l.catch(()=>{}),l}}}i(F$,"loadRemoteAccessPreference");import{createHash as CQ,randomUUID as z$}from"node:crypto";function MQ(e){let t=z$();return{runtimeId:t,request:e.request,signed(r,n){let o={version:1,scope:e.scope,runtimeId:t,audience:e.audience,nonce:z$(),issuedAt:new Date().toISOString(),payloadHash:CQ("sha256").update(Zl({method:"POST",path:r,payload:n})).digest("hex")};return e.request({path:r.replace(/^\/v1/,""),method:"POST",body:{payload:n,proof:{...o,signature:e.installation.sign(YM(o))}}})}}}i(MQ,"createRemoteDeviceClient");function W$(e,t){return MQ({installation:e,scope:{installationId:t.owner.installationId,profileId:t.owner.profileId,ownerUserId:t.owner.ownerUserId,teamId:t.owner.teamId},audience:t.owner.audience,request:t.request})}i(W$,"createSelectedRemoteClient");async function V$(e){let t=b.object({taskId:b.string(),artifactId:b.string(),uploadUrl:b.string().url(),maxBytes:b.number().int().positive().max(26214400)}).strict().parse(e.payload),r=new URL(t.uploadUrl);if(r.protocol!=="https:"||r.username||r.password||!e.uploadOrigins.includes(r.origin))throw new Error("remote_artifact_upload_origin_denied");let n=await e.session(t.taskId);if(!n||!ar(n,e.owner))throw new Error("remote_artifact_not_owned");let o=(await e.outputs(n)).find(d=>d.id===t.artifactId);if(!o||o.sourceTaskId!==n.id||o.sizeBytes>t.maxBytes)throw new Error("remote_artifact_unavailable_or_too_large");let a=await e.read(n,o.id);if(a.outputRef.sha256!==o.sha256||a.outputRef.sizeBytes!==o.sizeBytes||!e.stillCurrent())throw new Error("remote_artifact_authority_changed");let s=Buffer.from(a.contentsBase64,"base64");if(s.byteLength>t.maxBytes||s.byteLength!==o.sizeBytes)throw new Error("remote_artifact_size_changed");if(!(await fetch(r,{method:"PUT",body:s,headers:{"Content-Type":o.contentType},redirect:"error",signal:AbortSignal.timeout(15e3)})).ok)throw new Error("remote_artifact_upload_failed");if(!e.stillCurrent())throw new Error("remote_artifact_authority_changed");return{artifactId:o.id}}i(V$,"uploadRemoteArtifact");async function G$(e){let t=[];for(let r of e.sessions){if(e.assertCurrent(),!Xi(r)||!(await e.qualify(r)).eligible)continue;let n=await e.latestTurn(r.id);t.push({id:r.id,title:r.title,revision:za(r,n?.id??null)})}return e.assertCurrent(),t}i(G$,"unresolvedLocalOwnership");async function J$(e){e.assertCurrent();let t=await e.store.getSession(e.sessionId);if(!t)throw new Error("remote_local_attachment_session_unavailable");if(!ar(t,e.owner)){if(!Xi(t))throw new Error("remote_local_attachment_not_eligible");let r=await e.qualify(t);if(!r.eligible)throw new Error(r.reason??"remote_local_attachment_not_eligible")}return e.assertCurrent(),e.store.attachLocalSessionOwner({sessionId:e.sessionId,expectedRevision:e.expectedRevision,owner:e.owner,assertCurrent:e.assertCurrent})}i(J$,"attachQualifiedLocalOwner");function K$(){let e=[],t=null,r=null,n=!1;function o(){if(n||t)return;let a=e.shift();a&&(r=a,t=Promise.resolve().then(async()=>{try{a.current()&&await a.run()}catch(s){try{a.failed(s)}catch{}}finally{a.release()}}).finally(()=>{t=null,r=null,o()}))}return i(o,"advance"),{contains(a,s){let c=[...r?[r]:[],...e].filter(d=>d.commandId===a);if(c.some(d=>d.payloadHash!==s))throw new Error("remote_command_identity_changed");return c.length>0},enqueue(a){if(n||!a.current()){a.release();return}e.push(a),o()},invalidate(){e=e.filter(a=>a.current()?!0:(a.release(),!1))},async close(){n=!0;for(let a of e)a.release();e=[],await t}}}i(K$,"createRemoteCommandExecution");async function Y$(e){let{command:t,deps:r,send:n}=e;try{let o=await r.execute(t);n({protocolVersion:1,type:"receipt",payload:o})}catch(o){let a=await r.store.getRemoteDeviceReceipt(t.id);if(a){n({protocolVersion:1,type:"receipt",payload:{...a,state:"reconciling"}});return}n({protocolVersion:1,type:"receipt",payload:{id:t.id,deviceId:t.deviceId,payloadHash:t.payloadHash,action:t.action,targetId:t.targetId,state:"rejected",revision:2,error:o instanceof b.ZodError?"remote_command_configuration_invalid":o instanceof Error&&/^remote_[a-z0-9_]+$/.test(o.message)?o.message:"remote_command_failed",createdAt:new Date().toISOString(),expiresAt:t.deadline}})}}i(Y$,"executeRemoteCommand");async function X$(e){let{request:t,requestId:r,store:n,pending:o,current:a}=e,s=o(t.commandId,t.payloadHash),c=await n.getRemoteDeviceReceipt(t.commandId);if(!a())return null;let d=await n.getTaskInput(`remote-input:${t.commandId}`);if(!a())return null;let l=d?.payload.remoteDevice,u=await n.getRemoteDeviceCancellation(t.commandId);if(!a())return null;if(u&&u.payload_hash!==t.payloadHash)throw new Error("remote_command_identity_changed");if(c&&c.payloadHash!==t.payloadHash||l&&l.payloadHash!==t.payloadHash)throw new Error("remote_command_identity_changed");return{protocolVersion:1,type:"receipt_query_result",requestId:r,payload:{commandId:t.commandId,payloadHash:t.payloadHash,receipt:c??(d&&l?{id:l.id,deviceId:l.deviceId,state:"admitted",revision:2,payloadHash:l.payloadHash,action:l.action,targetId:l.targetId,localSessionId:d.sessionId,inputId:d.id,turnId:d.turnId,createdAt:d.createdAt,expiresAt:l.deadline}:null),notAdmitted:!c&&!d&&!s,cancelled:!!u}}}i(X$,"readRemoteCommandReceiptQuery");import{randomUUID as jQ}from"node:crypto";function Q$(e){let t=null,r=0,n=null,o=!1,a=0,s=i(c=>{if(!n)return;let d=n;n=null,clearTimeout(d.timeout),d.reject(c)},"cancel");return{reset(c=0){a++,s(new Error("remote_catalog_connection_lost")),t=null,r=Math.max(r,c)},resync(c){a++,t=null,r=Math.max(r,c),s(new Error("remote_catalog_resync_required"))},acknowledge(c){let d=QM.parse(c);if(!n||d.snapshotId!==n.snapshotId||d.revision!==n.revision||d.mode!==n.mode||d.pageIndex!==n.pageIndex)return;if(d.committed!==n.final||n.final&&d.catalogRevision!==n.revision)throw new Error("remote_catalog_ack_invalid");let l=n;n=null,clearTimeout(l.timeout),l.resolve()},async publish(c,d){if(o)throw new Error("remote_catalog_publication_in_progress");let l={tasks:new Map(c.map(R=>[R.id,R])),starters:new Map(d.map(R=>[R.id,R]))},u=i((R,T)=>[...R.values()].filter(P=>{let x=P.id;return!T?.has(x)||Zl(T.get(x))!==Zl(P)}),"changed"),p=i((R,T)=>[...R?.keys()??[]].filter(P=>!T.has(P)),"removed"),m={tasks:u(l.tasks,t?.tasks),starters:u(l.starters,t?.starters),removedIds:p(t?.tasks,l.tasks),removedStarterIds:p(t?.starters,l.starters)};if(t&&Object.values(m).every(R=>R.length===0))return!1;let w=t?"patch":"snapshot",g=r,f=Math.max(Date.now(),r+1),y=jQ(),h={mode:w,revision:f,snapshotId:y,...w==="patch"?{baseRevision:g}:{}},k=[{tasks:[],starters:[],removedIds:[],removedStarterIds:[]}];for(let R of["tasks","starters","removedIds","removedStarterIds"])for(let T of m[R]){let P=k.at(-1),x={...P,[R]:[...P[R],T]};(P[R].length>=100||Buffer.byteLength(JSON.stringify(x))>so.frameBytes-4096)&&(P={tasks:[],starters:[],removedIds:[],removedStarterIds:[]},k.push(P)),P[R].push(T)}if(k.length>100||Buffer.byteLength(JSON.stringify(k))>8388608)throw new Error("remote_catalog_publication_limit");let S=k.map((R,T)=>XM.parse({...h,...R,pageIndex:T,pageCount:k.length,complete:T===k.length-1})),I=a;o=!0;let v=Date.now()+45e3;try{for(let R of S){if(I!==a)throw new Error("remote_catalog_connection_lost");let T=v-Date.now();if(T<=0)throw new Error("remote_catalog_publication_timeout");let P=new Promise((x,_)=>{let E=setTimeout(()=>s(new Error("remote_catalog_ack_timeout")),Math.min(5e3,T));E.unref(),n={mode:w,snapshotId:y,revision:f,pageIndex:R.pageIndex,final:R.complete,resolve:x,reject:_,timeout:E}});try{e(R),await P}catch(x){throw s(x instanceof Error?x:new Error("remote_catalog_failed")),await P.catch(()=>{}),x}}if(I!==a)throw new Error("remote_catalog_connection_lost");return r=f,t=l,!0}finally{o=!1}}}}i(Q$,"createCatalogPublication");function Z$(e,t){if(e===4006||t.startsWith("protocol_unsupported")){let r=/minimum=(\d+)/.exec(t);return{state:"update_required",reason:"protocol_unsupported",...r?{minimumSupportedProtocolVersion:Number(r[1])}:{}}}return["grant_revoked","remote_access_off","ticket_revoked"].includes(t)?{state:"off",reason:t}:["authentication_required","ticket_invalid"].includes(t)?{state:"reconnecting",reason:"authentication_expired"}:{state:"reconnecting",reason:e===1013?"relay_backpressure":"connection_lost"}}i(Z$,"remoteCloseFailure");function eN(e){let t=Math.min(5e3,250*2**Math.min(e,5));return Math.round(t*(.8+Math.random()*.4))}i(eN,"remoteReconnectDelay");function rN(e){let t,r=null,n=null,o=null,a=null,s=null,c=null,d=null,l=null,u=!1,p=0,m=0,w=!1,g=null,f=null,y=null,h=Promise.resolve(),k="offline",S={state:"signed_out",account:null,team:null,webBaseUrl:null},I=null,v=0,R=null,T=!0,P=ng(),x=0,_=K$(),E=new Map,C=null,O=null,D=null,B=new Map,F=i(X=>{let W=h.then(X);return h=W.catch(()=>{}),W},"serial"),J=i(X=>W$(e.installation,X),"clientFor"),z=i(X=>{if(!n||n.readyState!==rS.OPEN)throw new Error("remote_connection_unavailable");let W=JSON.stringify({...o?{deviceId:o.id}:{},...l?{epoch:l}:{},...s?{fence:s.fence}:{},...X});if(Buffer.byteLength(W)>so.frameBytes||n.bufferedAmount+Buffer.byteLength(W)>so.socketQueueBytes)throw new Error("remote_connection_backpressure");n.send(W)},"send"),te=Q$(X=>z({protocolVersion:1,type:"catalog",payload:X}));async function M(X){X&&(I?.state!=="update_required"||X.state==="update_required")&&(I=X),I?.state==="update_required"&&g&&(clearTimeout(g),g=null),R&&clearTimeout(R),R=null,f&&clearTimeout(f),f=null,p++,_.invalidate(),T=!0,te.reset(),a=null,l=null,d=null,B.clear(),s=null,D?.(new Error("remote_connection_lost")),C=null,O=null,D=null;for(let G of E.values())clearTimeout(G.timer),G.reject(new Error("remote_connection_lost"));E.clear();let W=n;n=null,W?.close(1e3,"authority_changed"),await e.store.setRemoteDeviceAuthority(null),k=r&&t&&!t.enabled(r.owner)?"off":I?.state??"offline"}i(M,"disconnect");async function L(){return e.store.sessionShells()}i(L,"sessions");async function H(){if(!r||!a||!t.enabled(r.owner))return;let X=r,W=a,G=p,re=i(()=>!u&&r===X&&a===W&&p===G,"catalogCurrent"),le=await e.store.latestEventSequence();if(!re()||(og(le)&&(T=!0),P!==ng()&&(T=!0),!T))return;T=!1;let oe=await L(),pe=await e.store.pendingApprovals();if(!re())return;let me=await jB({owner:X.owner,sessions:oe,inspect:e.inspect,approvals:pe,latestTurn:i(ye=>e.store.latestTurnForSession(ye),"latestTurn")});for(let ye of me){if(!re())return;let ie=oe.find(Oe=>Oe.id===ye.localSessionId);ye.capabilities.artifacts=ie.experience==="work";let be=await e.store.runtimeEventPageRows({sessionId:ie.id,afterSequence:0,beforeSequence:await e.store.latestEventSequence()+1,limit:1});ye.lastEventSequence=be.entries[0]?.sequence??0}let Fe=[...Y1(oe,X.owner).values()].map(ye=>ye.target);if(re()){try{await te.publish(me,Fe)}catch(ye){if(ye instanceof Error&&ye.message==="remote_catalog_resync_required")T=!0,await te.publish(me,Fe);else throw ye}re()&&(P=ng())}}i(H,"catalog");async function N(X=!1){if(u||w||I?.state==="update_required")return;let W=p,G=await e.current(),re=await e.accountStatus();if(G&&await t.capture(G.owner),w||W!==p||u)return;if(S=re,r&&(!G||Zo(G.owner)!==Zo(r.owner)||G.credentialKey!==r.credentialKey)){m++;let De=p+1;if(await M(),p!==De||u||w)return;o=null}r=G;let le=!!G&&!t.enabled(G.owner);if(!G||le&&!e.caller?.needsConnection()){await M();return}for(let[De,Le]of B){for(let[it,ge]of Le)ge<=Date.now()&&Le.delete(it);Le.size===0&&B.delete(De)}if(n){if(s&&d&&o){let De=n,Le=d,it=o,ge=p,ce=i(()=>!u&&!w&&n===De&&p===ge,"renewalCurrent"),Ee=jI.parse(await Le.request({path:"/remote-devices/service-keys"}));if(!ce())return;c=Ee;let ut=b.object({ticket:b.string()}).parse(await Le.signed("/v1/remote-devices/connection-tickets",{role:"device",deviceId:it.id,client:"desktop",mode:le?"request":"remote",...e.caller?.requestAuthority(it.id,Le.runtimeId)?{requestAuthority:e.caller.requestAuthority(it.id,Le.runtimeId)}:{}}));if(!ce())return;z({protocolVersion:1,type:"renew",payload:{ticket:ut.ticket}}),z({protocolVersion:1,type:"heartbeat"}),await H()}return}k="connecting";let oe=p,pe=J(G),me;try{me=await pe.signed("/v1/remote-devices/enroll",{publicKey:e.installation.publicKey,name:OQ.hostname(),platform:process.platform,enabled:!le,...le?{requestOnly:!0}:{},...X?{reenable:!0}:{}})}catch(De){if(oe!==p||u||w)return;if(String(De).includes("deliberate_local_reenable_required")){if(await t.set(G.owner,!1),oe!==p||u||w)return;k="off";return}throw De}let Fe=jI.parse(await pe.request({path:"/remote-devices/service-keys"}));if(oe!==p||u||w)return;c=Fe;let ye=b.object({ticket:b.string(),connectUrl:b.string().url()}).parse(await pe.signed("/v1/remote-devices/connection-tickets",{role:"device",deviceId:me.device.id,client:"desktop",mode:le?"request":"remote",...e.caller?.requestAuthority(me.device.id,pe.runtimeId)?{requestAuthority:e.caller.requestAuthority(me.device.id,pe.runtimeId)}:{}}));if(oe!==p||u||(o=me.device,await t.setDeviceId(G.owner,o.id),oe!==p||u||w))return;d=pe;let ie=new rS(ye.connectUrl,{maxPayload:so.frameBytes});C=new Promise((De,Le)=>{O=De,D=Le}),C.catch(()=>{}),n=ie,R=setTimeout(()=>{n===ie&&!s&&M({state:"reconnecting",reason:"authentication_timeout"}).then($)},6e3),R.unref(),ie.on("open",()=>{n===ie&&z({protocolVersion:1,type:"hello",payload:{ticket:ye.ticket}})});let be=i(()=>!u&&n===ie&&oe===p,"connectionCurrent"),Oe=i(De=>{be()&&z(De)},"sendCurrent");ie.on("message",De=>{if(!be())return;try{let ge=JSON.parse(De.toString()),ce=ge.type==="error"&&ge.payload?.error==="catalog_resync_required";if(ge.type==="catalog_ack"||ce){if(n!==ie||oe!==p||!s)return;if(ge.protocolVersion!==Ac||ge.deviceId!==o?.id||ge.epoch!==s.epoch||ge.fence!==s.fence)throw new Error("remote_catalog_ack_authority_changed");if(ce){let Ee=b.object({catalogRevision:b.number().int().nonnegative()}).parse(ge.payload);te.resync(Ee.catalogRevision),T=!0}else te.acknowledge(ge.payload);return}}catch(ge){if(!be())return;e.warn(`Remote relay acknowledgement: ${ge instanceof Error?ge.name:"invalid_frame"}`),M({state:"reconnecting",reason:"connection_failed"}).then($);return}let Le=Buffer.byteLength(De.toString());if(x+Le>so.socketQueueBytes){M({state:"reconnecting",reason:"relay_backpressure"}).then($);return}x+=Le;let it=!1;F(async()=>{if(n!==ie||oe!==p)return;let ge=JSON.parse(De.toString());if(ge.protocolVersion!==Ac){await M({state:"update_required",reason:"protocol_unsupported"});return}if(ge.type==="hello"||ge.type==="heartbeat"||ge.type==="renew"){let ce=DB.parse(ge.payload);if(ge.type==="hello"){let Ee=b.object({catalogRevision:b.number().int().nonnegative(),minimumSupportedProtocolVersion:b.number().int().positive(),supportedProtocolVersion:b.number().int().positive()}).parse(ge.payload);if(Ee.minimumSupportedProtocolVersion>Ac||Ee.supportedProtocolVersion!==Ac){await M({state:"update_required",reason:"protocol_unsupported",minimumSupportedProtocolVersion:Ee.minimumSupportedProtocolVersion});return}te.reset(Ee.catalogRevision)}if(ce.deviceId!==o?.id)throw new Error("remote_device_identity_changed");if(l=ce.epoch,s=ce,a=le?null:{...ce,owner:G.owner,publicKeys:c?.keys??[]},await e.store.setRemoteDeviceAuthority(a),!be()||(R&&clearTimeout(R),R=null,I=null,v=0,O?.(),O=null,ge.type==="hello"&&await H(),!be()))return;k=le?"off":"connected"}else if(ge.type==="error"){let ce=b.object({error:b.string(),minimumSupportedProtocolVersion:b.number().int().positive().optional()}).parse(ge.payload);if(ce.error==="protocol_unsupported")await M({state:"update_required",reason:ce.error,minimumSupportedProtocolVersion:ce.minimumSupportedProtocolVersion});else throw new Error("remote_relay_rejected_frame")}else if(ge.type==="revoked"){if(await t.set(G.owner,!1),!be())return;await M()}else if(ge.type==="drain")await M({state:"reconnecting",reason:"connection_lost"}),$();else if(ge.type==="subscribe"||ge.type==="history_request"){if(!a)throw new Error("remote_authority_unavailable");let ce=b.object({taskId:b.string(),viewerId:b.string().optional(),cursor:b.unknown().optional()}).parse(ge.payload);if(ge.type==="subscribe"){if(!ce.viewerId)throw new Error("remote_viewer_identity_required");if(!B.has(ce.taskId)&&B.size>=so.deviceSubscriptions)throw new Error("remote_subscription_limit");let Rr=B.get(ce.taskId)??new Map,sc=Rr.has(ce.viewerId);if(Rr.size>=100&&!sc)throw new Error("remote_viewer_limit");if(Rr.set(ce.viewerId,Date.now()+75e3),B.set(ce.taskId,Rr),!ge.requestId&&ce.cursor===void 0)return}let Ee=typeof ce.cursor=="string"?ce.cursor:null;if(ce.cursor&&typeof ce.cursor=="object"){let Rr=b.object({historyGeneration:b.string(),sequence:b.number().int().nonnegative()}).parse(ce.cursor);Ee=Buffer.from(JSON.stringify({generation:Rr.historyGeneration,taskId:ce.taskId,after:Rr.sequence,watermark:await e.store.latestEventSequence(),snapshotId:tN()})).toString("base64url")}if(!be())return;let ut=await OB({store:e.store,owner:G.owner,taskId:ce.taskId,cursor:Ee,outputs:e.outputs});Oe({protocolVersion:1,type:"snapshot",taskId:ce.taskId,requestId:ge.requestId,payload:ut})}else if(ge.type==="unsubscribe"){let ce=b.object({taskId:b.string(),viewerId:b.string()}).parse(ge.payload),Ee=B.get(ce.taskId);Ee?.delete(ce.viewerId),Ee?.size===0&&B.delete(ce.taskId)}else if(ge.type==="receipt_query"){let ce=b.object({commandId:b.string(),payloadHash:b.string()}).parse(ge.payload),Ee=await X$({request:ce,requestId:ge.requestId,store:e.store,pending:_.contains,current:be});Ee&&Oe(Ee)}else if(ge.type==="command_cancel"){let ce=b.object({commandId:b.string(),payloadHash:b.string()}).parse(ge.payload),Ee=await e.store.cancelRemoteDeviceCommand(ce.commandId,ce.payloadHash);Oe({protocolVersion:1,type:"command_cancel_result",requestId:ge.requestId,payload:{...ce,...Ee}})}else if(ge.type==="caller_offers")e.caller?.receiveOffers(ge.payload);else if(ge.type==="caller_result"){let ce=ge.requestId?E.get(ge.requestId):null;if(!ce)return;let Ee=b.object({result:b.unknown().optional(),error:b.string().optional()}).parse(ge.payload);E.delete(ge.requestId),clearTimeout(ce.timer),Ee.error?ce.reject(new Error(Ee.error)):ce.resolve(Ee.result)}else if(ge.type==="artifact_request")try{let ce=await V$({payload:ge.payload,owner:G.owner,uploadOrigins:c?.artifactUploadOrigins??[],session:i(Ee=>e.store.getSession(Ee),"session"),outputs:e.outputs,read:e.readOutput,stillCurrent:i(()=>n===ie&&p===oe&&!!a,"stillCurrent")});Oe({protocolVersion:1,type:"artifact_result",requestId:ge.requestId,payload:ce})}catch(ce){Oe({protocolVersion:1,type:"artifact_result",requestId:ge.requestId,payload:{artifactId:ge.payload.artifactId,error:ce instanceof Error?ce.message:"remote_artifact_failed"}})}else if(ge.type==="command"){let ce=ge.payload,Ee=i(()=>!u&&!w&&!!a&&n===ie&&p===oe,"current");it=!0,_.enqueue({commandId:ce.id,payloadHash:ce.payloadHash,current:Ee,run:i(()=>Y$({command:ce,deps:e,send:i(ut=>{Ee()&&z(ut)},"send")}),"run"),failed:i(ut=>{Ee()&&(e.warn(`Remote relay command: ${ut instanceof Error?ut.name:"command_failed"}`),M({state:"reconnecting",reason:"connection_failed"}).then($))},"failed"),release:i(()=>{x-=Le},"release")})}}).catch(ge=>{n!==ie||oe!==p||u||(e.warn(`Remote relay frame: ${ge instanceof Error?ge.name:"invalid_frame"}`),M({state:"reconnecting",reason:"connection_failed"}).then($))}).finally(()=>{it||(x-=Le)})}),ie.on("close",(De,Le)=>{if(n!==ie)return;let it=Z$(De,Le.toString());it.state==="off"&&t.set(G.owner,!1),M(it).then($)}),ie.on("error",De=>e.warn(`Remote relay connection: ${De.name}`))}i(N,"connect");function $(){if(g&&clearTimeout(g),g=null,u||I?.state==="update_required")return;let W=!!r&&(t.enabled(r.owner)||!!e.caller?.needsConnection())&&!n?eN(v++):15e3;g=setTimeout(()=>{g=null,F(N).catch(G=>{k="reconnecting",I={state:k,reason:"connection_failed"},e.warn(`Remote relay: ${G instanceof Error?G.name:"connection_failed"}`)}).finally($)},W),g.unref()}i($,"schedule");function Z(){T=!0,!(u||f||!a)&&(f=setTimeout(()=>{f=null,F(H).catch(()=>{T=!0,M({state:"reconnecting",reason:"connection_failed"}).then($)})},100),f.unref())}return i(Z,"scheduleCatalog"),{async start(){t=await F$(e.storeDir),await e.store.initializeRemoteDeviceStore(),y=HB({deps:e,current:i(()=>({selected:r,authority:a}),"current"),subscriptions:B,scheduleCatalog:Z,catalog:H,send:z,serial:F,disconnect:M,schedule:$}),await F(N).catch(X=>e.warn(`Remote relay startup: ${X instanceof Error?X.name:"connection_failed"}`)),$()},async close(){u=!0,g&&clearTimeout(g),y?.(),await M(),await h,await _.close()},async beforeAuthorityChange(){w=!0,m++,I=null,await M(),r&&await t.capture(r.owner),r=null,o=null,k="offline"},afterAuthorityChange(){w=!1,this.wake()},wake(){F(N).catch(X=>e.warn(`Remote relay wake: ${X instanceof Error?X.name:"connection_failed"}`)).finally($)},async callerRequest(X){if(E.size>=32)throw new Error("ponder_relay_request_limit");if(await F(N),await C,!s)throw new Error("ponder_relay_connection_unavailable");let W=tN();return new Promise((G,re)=>{let le=setTimeout(()=>{E.delete(W),re(new Error("ponder_relay_request_timeout"))},3e4);le.unref(),E.set(W,{resolve:G,reject:re,timer:le});try{z({protocolVersion:1,type:"caller_request",requestId:W,payload:X})}catch(oe){clearTimeout(le),E.delete(W),re(oe)}})},status(){return{state:r?k:"signed_out",enabled:r?t.enabled(r.owner):!1,device:o,owner:r?.owner??null,account:S.account,team:S.team,webBaseUrl:S.webBaseUrl,reason:I?.reason??null,minimumSupportedProtocolVersion:I?.minimumSupportedProtocolVersion??null,supportedProtocolVersion:Ac}},async settings(X,W){if(w)throw new Error("remote_account_changing");let G=m,re=i(()=>{if(u||w||G!==m)throw new Error("remote_account_changing")},"assertCurrentAccount"),le=await e.accountStatus(),oe=await e.current();if(oe&&await t.capture(oe.owner),w||G!==m)throw new Error("remote_account_changing");if(S=le,!oe)return await M(),r=null,o=null,{...this.status(),devices:[],unresolvedTasks:[]};if(r&&Zo(r.owner)!==Zo(oe.owner)&&(await M(),r=oe,o=null),(X==="enable"||X==="disable")&&await this.setEnabled(X==="enable"),X==="retry"){if(!t.enabled(oe.owner))throw new Error("remote_access_off");I=null,v=0,await M(),r=oe,await F(N),$()}if(X==="attach"){let ie=b.object({sessionId:b.string(),expectedRevision:b.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(W),be=await e.prepareOwnerAttachment(oe.owner);await J$({...ie,store:e.store,owner:oe.owner,qualify:be,assertCurrent:re}),T=!0,a&&await H()}if(X==="rename"||X==="remove"||X==="disable-device"){let ie=b.object({deviceId:b.string().uuid(),revision:b.number().int().positive(),name:b.string().min(1).max(200).optional()}).strict().parse(W),be=t.deviceId(oe.owner);if(!be)throw new Error("remote_device_not_enrolled");let Oe=await J(oe).signed("/v1/remote-devices/device-management",{deviceId:be,action:X==="disable-device"?"disable":X,targetDeviceId:ie.deviceId,revision:ie.revision,...ie.name?{name:ie.name}:{}});ie.deviceId===o?.id&&(o=Oe.device),["remove","disable-device"].includes(X)&&ie.deviceId===o?.id&&(await t.set(oe.owner,!1),await M())}let pe=t.deviceId(oe.owner),me=pe?await J(oe).signed("/v1/remote-devices/device-management",{deviceId:pe,action:"list"}):{devices:[]};o=me.devices.find(ie=>ie.id===pe)??o;let Fe=await e.prepareOwnerAttachment(oe.owner),ye=await G$({sessions:await L(),qualify:Fe,latestTurn:i(ie=>e.store.latestTurnForSession(ie),"latestTurn"),assertCurrent:re});return{...this.status(),devices:me.devices,unresolvedTasks:ye}},async setEnabled(X){if(w)throw new Error("remote_account_changing");I=null,v=0;let W=m,G=await e.current();if(w||W!==m)throw new Error("remote_account_changing");if(!G)throw new Error("Sign in to your OpenPond account first.");if(await t.set(G.owner,X),w||W!==m)throw new Error("remote_account_changing");if(await M(),w||W!==m)throw new Error("remote_account_changing");return r=G,!X&&o&&await J(G).signed("/v1/remote-devices/device-management",{deviceId:o.id,targetDeviceId:o.id,action:"disable",revision:o.revision}),X&&await F(()=>N(!0)),$(),this.status()}}}i(rN,"createRemoteRelayManager");function oS(e){let t=new Map,r=0;return async n=>{if(n.experience!=="work")return[];let o=await e.latestEventSequence(),a=t.get(n.id);if(a?.watermark===o)return t.delete(n.id),t.set(n.id,a),a.outputs;let s=RH(5e3),c=0;for(;c<o;){let p=(await e.runtimeEventPageRows({sessionId:n.id,afterSequence:c,beforeSequence:null,limit:100})).entries.filter(m=>m.sequence<=o);for(let m of p)s.accept(m.event);if(p.length<100)break;c=p.at(-1).sequence}let d=s.values().filter(u=>u.sourceTaskId===n.id&&u.location.kind==="local").sort((u,p)=>p.revision-u.revision),l=Buffer.byteLength(JSON.stringify(d));if(l>10485760)throw new Error("remote_output_reference_limit");for(a&&(r-=a.bytes,t.delete(n.id));t.size>=20||r+l>33554432;){let u=t.entries().next().value;if(!u)break;t.delete(u[0]),r-=u[1].bytes}return t.set(n.id,{watermark:o,outputs:d,bytes:l}),r+=l,d}}i(oS,"createRemoteOutputReader");function nN(e,t){let r=oS(e);return async(n,o)=>{let a=(await r(n)).find(s=>s.id===o);if(!a)throw new Error("remote_artifact_unavailable");return t(n,a)}}i(nN,"createRemoteQualifiedOutputReader");function oN(e){let{loadAppPreferences:t,commands:r,readQualifiedOutput:n,...o}=e,a=TB(o.installation.installationId,t);return rN({...o,current:a,accountStatus:i(()=>EB(t),"accountStatus"),execute:AB({...r,store:o.store,inspect:o.inspect,resolveStarter:X1({store:o.store,current:a})}),outputs:oS(o.store),readOutput:nN(o.store,n)})}i(oN,"createAccountRemoteRelayManager");import{createHash as HQ}from"node:crypto";import{readFile as DQ,writeFile as LQ,rename as BQ,mkdir as $Q}from"node:fs/promises";import aN from"node:path";function iN(e){let t=!1,r=Promise.resolve(),n=i(p=>{t||(r=r.then(p).catch(()=>e.warn("Ponder Pal activity sync will retry.")))},"queue");async function o(){let p=await Mn(),m=p?.accountState;if(!m?.activeProfile||m.state!=="signed_in")return null;let w=fo(p,e.deviceId,await e.teamId(),new URL(p.apiBaseUrl).origin);if(!w?.teamId)return null;let g=HQ("sha256").update(JSON.stringify([m.baseUrl,m.activeProfile,w.teamId,e.deviceId,w.ownerUserId])).digest("hex");return{key:g,owner:w,context:p,file:aN.join(e.storeDir,"ponder-activity",`${g}.json`)}}i(o,"scope");async function a(p,m){let w=await e.sessionOwner(p);return w?.installationId===m.installationId&&w.profileId===m.profileId&&w.ownerUserId===m.ownerUserId&&w.teamId===m.teamId&&w.audience===m.audience}i(a,"owns");async function s(p){try{return JSON.parse(await DQ(p,"utf8"))}catch(m){if(m.code==="ENOENT")return{pending:[],observed:{}};throw m}}i(s,"read");async function c(p,m){await $Q(aN.dirname(p),{recursive:!0}),await LQ(p+".tmp",JSON.stringify(m),{mode:384}),await BQ(p+".tmp",p)}i(c,"save");let d=e.subscribe(p=>{if(t||!p.sessionId||!["session.started","turn.completed","turn.failed","turn.interrupted","turn.started"].includes(p.name))return;let m=o().then(w=>({owner:w}),w=>({error:w}));n(async()=>{let w=await m;if("error"in w)throw w.error;let g=w.owner;if(!g||t||!await a(p.sessionId,g.owner))return;let f=await e.sessionTitle(p.sessionId),y=await s(g.file),h={id:`local:${e.deviceId}:${p.id}`,source:"local",kind:p.name==="session.started"?"thread.started":"run.updated",resourceId:p.sessionId,title:f.slice(0,300),status:p.name==="session.started"?"started":p.name.slice(5),occurredAt:p.timestamp};y.pending.some(k=>k.id===h.id)||y.pending.push(h),await c(g.file,y)})});async function l(){let p=await o();if(!p||t)return;let m=await e.request({path:"/ponder/settings"},p.context,p.owner.teamId);if((await o())?.key!==p.key)return;let w=m.settings,g=m.bindingId;if(typeof g!="string")throw new Error("Ponder Pal binding missing.");let f=await s(p.file);if(!w.watchLocalThreads){f.pending=[],await c(p.file,f);return}if(w.watchWorkflows){let{workflows:S,runs:I}=await e.workflows(),v=new Map(S.map(R=>[R.id,R.name]));for(let R of[...S.map(T=>({...T,status:"available",resourceId:T.id,title:T.name})),...I.map(T=>({...T,resourceId:T.sessionId,title:v.get(T.workflowId)??"Workflow run"}))]){if(!await a(R.resourceId,p.owner))continue;let T=`workflow:${R.id}`,P=`${R.updatedAt}:${R.status}`;f.observed[T]!==P&&(f.pending.push({id:`local:${e.deviceId}:${T}:${P}`,source:"local",kind:"workflow.updated",resourceId:R.resourceId,title:R.title.slice(0,300),status:R.status,occurredAt:R.updatedAt}),f.observed[T]=P)}await c(p.file,f)}if((await o())?.key!==p.key||!f.pending.length)return;let y=f.pending.slice(0,100),h=await e.request({path:"/ponder/activity",method:"POST",body:{bindingId:g,items:y}},p.context,p.owner.teamId);if((await o())?.key!==p.key)return;let k=new Set([...h.delivered,...h.ignored]);f.pending=f.pending.filter(S=>!k.has(S.id)),await c(p.file,f)}i(l,"flush");let u=setInterval(()=>n(l),1e4);return u.unref(),n(l),{close(){return t||(t=!0,clearInterval(u),d()),r},flush:i(()=>(n(l),r),"flush")}}i(iN,"createPonderActivityBridge");async function sN(e){let{teamId:t,...r}=e,n=await wr();return ho(n,t).request(r)}i(sN,"requestHostedPonder");var NQ=b.object({teamId:b.string().trim().min(1).max(240),resource:b.enum(["options","policies","definitions","serving-targets"]),method:b.enum(["GET","POST"]),body:b.record(b.string(),b.unknown()).optional()}).strict();async function cN(e){let t=NQ.parse(e);if(t.method==="POST"&&t.resource==="options")throw new Error("Learning options are read-only.");let r=sI({teamId:t.teamId,path:`/connected-evidence/learning/${t.resource}`,method:t.method,...t.method==="POST"?{body:t.body??{}}:{}});if(t.method==="GET"&&t.resource==="options"){let[n,o]=await Promise.all([r,sI({teamId:t.teamId,path:"/ponder/settings",method:"GET"})]);return{...n,ponderBindingId:o.bindingId}}return r}i(cN,"requestConversationLearning");import{randomUUID as UQ}from"node:crypto";import{isDeepStrictEqual as qQ}from"node:util";function dN(e){async function t(n){let o=await e.getSession(n);if(!o)throw new Wo("This task no longer exists. Choose an available task before sending.",404);let[a,s,c,d]=await Promise.all([e.store.taskInboxSnapshot(n),e.latestTurn(n),e.readiness(o),e.approvalBlocked(n)]),l=Ch(o),u=Mh(o.provider),p=o.metadata?.nativeResumeAvailable===!0&&!o.metadata?.nativeBranch&&o.nativeAgent?.provider===o.provider&&o.nativeAgent.cwd===o.cwd,m=o.archived||o.status==="closed"?"This task is closed or archived.":o.workspaceKind==="sandbox"||o.workspaceKind==="sandbox_template"||o.workspaceKind==="sandbox_app"?"This target is hosted; use its hosted message action.":o.metadata?.nativeHistoryProjection===!0&&!p||lu(o.id)?"This imported conversation has not been qualified for original-session continuation. Open it in the desktop and check its connection before sending a task follow-up.":!u||!l?"This conversation has no managed local session. Imported history alone cannot receive messages.":c.available?null:c.reason??"The original managed agent is unavailable.",w=L1(o,s?.id??null);return{sessionId:n,provider:o.provider,title:o.title,managedSessionId:l,targetRevision:w,latestTurnId:s?.id??null,activeTurnId:a.activeTurnId,paused:a.paused,approvalBlocked:d,canSendFollowup:m===null,canSteer:m===null&&c.canSteer&&a.acceptingInput&&!d,unavailableReason:m,inbox:a}}i(t,"inspect");async function r(n,o){let a=gO.parse(o),s={localManagedMessage:{targetRevision:a.expectedTargetRevision,recommendationId:a.recommendationId??null,authority:a.authority}},c=a.mode==="steer"?"steer":"queued",d,l=0;for(;!d;){let p=await e.store.taskInputsForSession(n,{afterSequence:l,limit:500});if(d=p.find(m=>m.senderKind==="user"&&m.senderSessionId===null&&m.idempotencyKey===a.idempotencyKey),p.length<500)break;l=p.at(-1).sequence}if(d){let p=d.payload.localManagedMessage;if(d.kind!==c||d.body!==a.prompt||d.expectedTurnId!==(a.expectedTurnId??null)||!qQ(p,s.localManagedMessage))throw new Wo("This message identity was already used with different content or target. Refresh before sending a changed message.");return d}let u=await t(n);if(!u.canSendFollowup)throw new Wo(u.unavailableReason,422);if(u.targetRevision!==a.expectedTargetRevision)throw new Wo("The managed target changed. Refresh and review the message before sending.");if(a.mode==="steer"&&(!u.canSteer||u.activeTurnId!==a.expectedTurnId))throw new Wo("The observed turn is no longer accepting corrections. Your text was not sent to another turn; refresh or queue a follow-up.");return e.admit({id:UQ(),sessionId:n,senderSessionId:null,senderKind:"user",kind:c,body:a.prompt,payload:s,idempotencyKey:a.idempotencyKey,expectedTurnId:a.expectedTurnId??null,replyTo:null})}return i(r,"send"),{inspect:t,send:r}}i(dN,"createLocalManagedMessaging");function lN(e){return async t=>{let r=mo.safeParse(t.metadata?.ponderLocalOwner);if(!r.success)return{available:!1,reason:"This OpenPond task has no captured local account owner."};try{let n=await Mn(),o=(await e()).defaultTeamId,a=fo(n,r.data.installationId,o,new URL(n.apiBaseUrl).origin);return!a||!ar(t,a)?{available:!1,reason:"Sign in to this task's original OpenPond account and workspace before sending."}:{available:!0,reason:null}}catch{return{available:!1,reason:"The captured OpenPond account could not be authenticated."}}}}i(lN,"createOpenPondManagedReadiness");import{access as FQ,constants as uN}from"node:fs/promises";import{delimiter as zQ,extname as WQ,isAbsolute as VQ,join as GQ}from"node:path";async function JQ(e){let t=process.platform==="win32"&&!WQ(e)?[e,...(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(n=>e+n)]:[e],r=VQ(e)?t:(process.env.PATH??"").split(zQ).filter(Boolean).flatMap(n=>t.map(o=>GQ(n,o)));for(let n of r)try{return await FQ(n,process.platform==="win32"?uN.F_OK:uN.X_OK),!0}catch{}return!1}i(JQ,"executableAvailable");function bg(e){return async t=>{let r=i(a=>({available:!1,canSteer:!1,reason:a}),"unavailable");if(t.provider==="openpond"){if(!(await e.configProvider("openpond"))?.enabled)return r("Enable OpenPond in Providers before sending.");let s=await e.openPondStatus(t);return s.available?{available:!0,canSteer:!0,reason:null}:r(s.reason??"The captured OpenPond account is unavailable.")}if(t.provider==="codex"){if(!t.codexThreadId||!t.cwd)return r("This conversation has no original managed Codex thread and working directory.");let a=await e.codexStatus();return!a.enabled||!a.available?r(a.reason??"The local Codex installation is unavailable or disabled."):{available:!0,canSteer:!0,reason:null}}if(!Zi(t.provider)||!t.nativeAgent)return r("Imported history has no qualified managed session.");let n=await e.configProvider(t.provider);if(!n?.enabled)return r("Enable the original local agent in Providers before sending.");let o;try{o=Br(t.provider,n)}catch(a){return r(a instanceof Error?a.message:"The local agent configuration is invalid.")}if(t.nativeAgent.provider!==t.provider||t.nativeAgent.instanceId!==o.instanceId||!t.cwd||t.nativeAgent.cwd!==t.cwd)return r("The original agent installation, account configuration or working directory changed. Restore it before sending.");if(!await JQ(o.command))return r("The original local agent executable is unavailable. Restore it before sending.");if(e.nativeStatus){let a=await e.nativeStatus(t);if(!a.available)return r(a.reason??"The original local agent is unavailable.")}return{available:!0,canSteer:!1,reason:null}}}i(bg,"createLocalManagedReadiness");function pN(e){let t=mo.parse(e.owner),r,n=new Map,o=i(c=>({eligible:!1,reason:c}),"unavailable"),a=bg({configProvider:i(async c=>e.providers.providers[c]??null,"configProvider"),codexStatus:i(async()=>{let c=await(r??=e.codexStatus());return{enabled:e.providers.providers.codex?.enabled??!1,available:c.available&&c.authHealth==="signed_in",reason:c.authHealth==="signed_in"?null:"Sign in to the original local Codex installation before adding this task."}},"codexStatus"),openPondStatus:i(async c=>ar(c,t)?{available:!0,reason:null}:{available:!1,reason:"The selected local account changed."},"openPondStatus")});async function s(c){if(!c.currentProfile&&!c.profileWorkflowBinding&&!c.profileComponentBinding)return{eligible:!0,reason:null};let d=JSON.stringify([c.currentProfile??null,c.profileWorkflowBinding??null,c.profileComponentBinding??null]),l=n.get(d);return l||(l=(async()=>{try{if(c.profileWorkflowBinding||c.profileComponentBinding){let u=await e.loadHarness(c);if(!u||c.profileWorkflowBinding&&!u.workflow)return o("The task's original released Profile workflow or component is unavailable.")}else if(c.currentProfile){let u=await e.loadProfile(c.currentProfile);if(u.mode!=="local"||u.activeProfile!==c.currentProfile.profileId||u.error||u.setupGate.status!=="ready")return o("Restore this task's original Profile and complete its setup before adding it.")}return{eligible:!0,reason:null}}catch{return o("The task's original Profile or released workflow could not be loaded.")}})(),n.set(d,l)),l}return i(s,"profileAvailable"),async c=>{if(!Xi(c))return o("Only an eligible local task without an existing account owner can be added.");if(!Mh(c.provider)||!Ch(c))return o("This conversation has no qualified original managed session.");let d={...c,metadata:{...c.metadata,ponderLocalOwner:t}},l;try{l=await a(d)}catch{return o("The original managed provider is unavailable.")}return l.available?s(c):o(l.reason??"The original managed provider is unavailable.")}}i(pN,"createLocalOwnerAttachmentInspection");function mN(e){return{localManagedMessaging:dN({store:e.store,getSession:i(async r=>await e.store.getSession(r)?e.getSession(r):null,"getSession"),latestTurn:i(r=>e.store.latestTurnForSession(r),"latestTurn"),approvalBlocked:i(async r=>{let n=await e.store.latestTurnForSession(r);return n?.status==="in_progress"&&(await e.store.pendingApprovals()).some(o=>o.sessionId===r&&!!o.turnId&&(o.turnId===n.id||o.turnId===n.providerTurnId))},"approvalBlocked"),readiness:bg({openPondStatus:lN(e.loadAppPreferences),configProvider:i(async r=>(await e.localByokRuntimeState()).settings.providers[r]??null,"configProvider"),codexStatus:i(async()=>{let r=await e.refreshCodexStatus();return{enabled:(await e.localByokRuntimeState()).settings.providers.codex?.enabled??!1,available:r.available&&r.authHealth==="signed_in",reason:r.authHealth==="signed_in"?null:"Sign in to the original local Codex installation before sending."}},"codexStatus")}),admit:i(r=>e.turnRunner.admitUserLocalMessage(r),"admit")}),prepareOwnerAttachment:i(async r=>pN({owner:r,providers:structuredClone((await e.localByokRuntimeState()).settings),codexStatus:e.refreshCodexStatus,loadProfile:e.loadProfile,loadHarness:e.loadHarness}),"prepareOwnerAttachment"),conversationLearningRequestPayload:cN,ponderRequestPayload:i(async r=>sN({...r,teamId:(await e.loadAppPreferences()).defaultTeamId??void 0}),"ponderRequestPayload")}}i(mN,"createDesktopManagedAgentRoutes");function fN(e){let{loadAppPreferences:t,...r}=e;return iN({...r,teamId:i(async()=>(await t()).defaultTeamId,"teamId"),request:i(async(n,o,a)=>ho(o,a).request(n),"request")})}i(fN,"createDesktopPonderActivityBridge");function hN(e){return fN({storeDir:e.storeDir,deviceId:e.installation.installationId,subscribe:e.subscribe,loadAppPreferences:e.loadAppPreferences,sessionTitle:i(async t=>(await e.store.getSession(t))?.title??"Local chat","sessionTitle"),sessionOwner:i(async t=>{let r=mo.safeParse((await e.store.getSession(t))?.metadata?.ponderLocalOwner);return r.success?r.data:null},"sessionOwner"),workflows:i(async()=>({workflows:await e.store.listChatWorkflows(),runs:await e.store.listChatWorkflowRuns(null,500)}),"workflows"),warn:e.warn})}i(hN,"createServerPonderActivity");import eZ from"node:path";import{rm as KQ}from"node:fs/promises";import gN from"node:path";var YQ=b.object({source:b.literal("openpond_git"),repositoryId:b.string().min(1),profileId:b.string().min(1)}).strict(),wN=b.object({schemaVersion:b.literal("openpond.profileExperimentOrigin.v1"),apiBaseUrl:b.string().url(),actorId:b.string().min(1),teamId:b.string().min(1),projectId:b.string().min(1),ref:YQ,sourceRevision:b.string().regex(/^[a-f0-9]{40}$/),sourcePath:b.string(),sourceFilesHash:b.string().regex(/^[a-f0-9]{64}$/)}).strict(),yN=b.object({id:b.string(),teamId:b.string(),name:b.string(),metadata:b.record(b.string(),b.unknown())});function ei(e){let t=i(async(u,p,m)=>{let w=xe(u.token);w.set("x-openpond-team-id",u.teamId),m!==void 0&&w.set("content-type","application/json");let g=await(e.fetch??fetch)(new URL(p,u.apiBaseUrl),{method:m===void 0?"GET":"POST",headers:w,...m===void 0?{}:{body:JSON.stringify(m)}});if(!g.ok)throw new ee("local_profile_origin_access_denied","This Profile origin is unavailable to the current account.",g.status===401?401:403);let f=await g.text();if(Buffer.byteLength(f)>4e7)throw new Error("Profile origin response exceeds its size limit.");return JSON.parse(f)},"request");function r(u){let p=b.object({sourceUpload:b.object({sourceCommitSha:b.string().regex(/^[a-f0-9]{40}$/)}),manifest:b.object({profiles:b.record(b.string(),b.unknown())})}).parse(u.metadata.hostedProfileRepo);return{revision:p.sourceUpload.sourceCommitSha,profiles:Object.keys(p.manifest.profiles)}}i(r,"source");async function n(u,p,m={}){let w=await e.resolveAccess();if(w.actorId!==u.actorId||w.teamId!==u.teamId||w.apiBaseUrl.replace(/\/$/,"")!==u.apiBaseUrl.replace(/\/$/,"")||u.projectId!==u.ref.repositoryId||p&&(p.ownerScope.kind!=="team"||p.ownerScope.id!==u.teamId||p.location!=="local"||p.metadata.selectionEligible!==!1))throw new ee("local_profile_origin_access_denied","The cached Profile belongs to another actor or origin.",403);let g=b.object({project:yN}).parse(await t(w,`/v1/projects/${encodeURIComponent(u.projectId)}?teamId=${encodeURIComponent(w.teamId)}`)),f=r(g.project);if(g.project.id!==u.projectId||g.project.teamId!==u.teamId||m.requireCurrentRevision!==!1&&f.revision!==u.sourceRevision||!f.profiles.includes(u.ref.profileId))throw new ee("local_profile_origin_changed","The original committed Profile origin has changed or is no longer accessible.",409);return w}i(n,"authorize");async function o(u,p){for(let m of await e.store.listHarnessWorkspaces()){let w=wN.safeParse(m.metadata.profileExperimentOrigin);if(!w.success||A(w.data.ref)!==A(u))continue;let g=p?await e.store.getHarnessReleaseRecord(p.contentHash):m.currentChannel.release&&await e.store.getHarnessReleaseRecord(m.currentChannel.release.contentHash);if(!(!g||g.workspaceId!==m.id||p&&g.harnessRelease.id!==p.id))return{workspace:m,release:g,origin:w.data}}throw new ee("local_profile_origin_access_denied","The exact Profile has no trusted installed origin on this device.",403)}i(o,"cached");let a=i(async(u,p,m,w)=>{let g=wN.parse(u.metadata.profileExperimentOrigin);if(A(g.ref)!==A(m))throw new Error("Profile origin reference was substituted.");await n(g,u,w);let f=`profile-origin-${A([g.apiBaseUrl,g.actorId,g.teamId,g.ref,g.sourceRevision]).slice(0,40)}`;if(u.id!==f||g.sourcePath!==gN.join(e.storeDir,"library","profile-experiment-origins",f))throw new Error("Profile origin provenance was substituted.");if(await gH(g.sourcePath)!==g.sourceFilesHash)throw new Error("Installed Profile tree differs from its complete committed source.");let y=await Yl(g.sourcePath,m.profileId);if(y.error||!y.sourcePath)throw new Error("The installed Profile source is incomplete.");let h=await GC({storeDir:e.storeDir,workspaceId:u.id,name:m.profileId,profile:y,repositoryId:m.repositoryId,sourceRevision:g.sourceRevision});if(h.harnessRelease.id!==p.id||h.harnessRelease.contentHash!==p.contentHash)throw new Error("Installed Profile source differs from its original compiler identity.");await n(g,u,w)},"authority");async function s(u,p){let m=await o(u,p?.harnessRelease);if(await a(m.workspace,{id:m.release.harnessRelease.id,contentHash:m.release.harnessRelease.contentHash},u),p&&p.sourceRevision!==m.origin.sourceRevision)throw new Error("Selected Profile source revision changed.");return Wc({store:e.store,ref:u,release:m.release,sourceRevision:m.origin.sourceRevision})}i(s,"workflows");let c=new Map;async function d(u,p,m,w){let g=p.profileId,f=A([w.apiBaseUrl,w.actorId,w.teamId,p,m]),y=c.get(f);if(y)return y;let h=(async()=>{let k=`profile-origin-${A([w.apiBaseUrl,w.actorId,w.teamId,p,m]).slice(0,40)}`,S=await e.store.getHarnessWorkspace(k);if(!S){let I=gN.join(e.storeDir,"library","profile-experiment-origins",k),v={schemaVersion:"openpond.profileExperimentOrigin.v1",apiBaseUrl:w.apiBaseUrl,actorId:w.actorId,teamId:w.teamId,projectId:u.id,ref:p,sourceRevision:m,sourcePath:I,sourceFilesHash:"0".repeat(64)};await n(v),await KQ(I,{recursive:!0,force:!0});let R=await hH({root:I,revision:m,read:i(_=>t(w,`/v1/projects/${encodeURIComponent(u.id)}/files`,{teamId:w.teamId,..._}),"read")}),T={...v,sourceFilesHash:A(R)};await n(T);let P=await Yl(I,g);if(P.error||!P.sourcePath)throw new Error("Profile source is invalid.");S=(await VC({store:e.store,storeDir:e.storeDir,id:k,ownerId:w.actorId,name:g,profile:P,sourceRevision:m,repositoryId:u.id,selectionEligible:!1,originOwnerScope:{kind:"team",id:w.teamId},originMetadata:{profileExperimentOrigin:T}})).workspace}return S})();c.set(f,h);try{return await h}finally{c.delete(f)}}i(d,"install");async function l(){let u=await e.resolveAccess(),{projects:p}=b.object({projects:b.array(yN).max(1e3)}).parse(await t(u,`/v1/projects?teamId=${encodeURIComponent(u.teamId)}&role=profile`)),m=[],w=0;for(let g of p.slice(0,100))try{if(g.teamId!==u.teamId)continue;let f=r(g);for(let y of f.profiles.slice(0,20)){if(++w>100)return m;let h={source:"openpond_git",repositoryId:g.id,profileId:y};await d(g,h,f.revision,u),await s(h),m.push({ref:h,name:`${g.name} / ${y} (installed origin)`})}}catch{}return m}return i(l,"discover"),{authority:a,workflows:s,discover:l,resolveRef:i(async(u,p,m)=>{let w={source:"openpond_git",repositoryId:u,profileId:p},g=await o(w,m);return await a(g.workspace,m,w),w},"resolveRef")}}i(ei,"createLocalProfileOriginAdapter");function yr(e){let t=ff(e),r=e.modelResources?.rewards??(e.learningResources?Zm(e.taskset).rewards:[]);if(t&&A(Ll(t,r))!==A(e.taskset.graders))throw new ee("local_grader_closure_conflict","The retained Reward closure differs from the released Dataset graders.",422);return e.taskset.graders.map(n=>{let o=t?.sources.find(s=>s.graderId===n.id),a=o&&r.find(s=>s.id===o.reward.id&&s.revision===o.reward.revision&&s.contentHash===o.reward.contentHash);return{id:n.id,version:n.version,contentHash:A(n),name:a?.name??("config"in n&&n.config.operator==="final_answer_equals_expected"?"Answer accuracy":`${n.kind.replaceAll("_"," ")} grader`),feedbackKey:a?Jm(a):`grader_${A(n.id).slice(0,24)}`,release:a?{id:a.id,revision:a.revision,contentHash:a.contentHash}:null}})}i(yr,"localPackageGraders");function kg(e,t){let r=yr(e),n=t?t.map(o=>{let a=r.find(s=>s.id===o.id&&s.version===o.version&&s.contentHash===o.contentHash);if(!a)throw new ee("local_grader_pin_unavailable","Select an exact grader from the retained Dataset package.",422);return{...a,mappings:o.mappings}}):r;try{return IC(n)}catch(o){throw new ee("experiment_grader_feedback_conflict",o instanceof Error?o.message:"Grader selection conflicts.",422)}}i(kg,"selectLocalPackageGraders");function vN(e,t,r,n=!1,o=!1,a=!1){let s=Ze(t),c=e.configuration.request;if(s.contentHash!==e.packageHash||A(c.taskset)!==A({id:s.taskset.id,revision:s.taskset.revision,contentHash:s.taskset.contentHash}))throw new ee("local_dataset_pin_conflict","Local execution requires the exact retained Dataset package.",422);if(c.policy.kind!=="hosted_chat"&&!(c.policy.kind==="hosted_harness"&&a))throw new ee("local_target_not_qualified","This local execution path requires a qualified exact target owner.",422);if(e.model.providerId==="claude-code"&&(XQ(s)||s.taskset.environment.kind!=="text"||s.taskset.tools.length))throw new ee("claude_environment_not_admitted","The Claude process adapter requires a text Dataset with no environment tools. Additional tool owners require explicit admission.",422);let d=c.policy.kind==="hosted_chat"?c.policy.harness:void 0;if(d&&!n)throw new ee("local_harness_not_qualified","A released Harness must execute through its native turn owner.",422);let l=zl(s);if(s.taskset.policy.connectedAppScopes.length)throw new ee("local_connected_scope_not_qualified","This Dataset requires connected scopes that have not been admitted for local execution.",422);for(let u of s.taskset.capabilities.filter(p=>p.required)){if(u.id==="tools"&&a&&u.scopes.every(m=>["work_exec","work_save_output"].includes(m)&&s.taskset.tools.some(w=>w.name===m)))continue;if(u.id!=="private-verifier")throw new ee("local_capability_not_qualified","This Dataset requires capabilities not supplied by the local execution owner.",422);if((u.scopes.length?u.scopes:s.taskset.policy.hiddenGraderRefs).some(m=>!s.taskset.policy.hiddenGraderRefs.includes(m)||!s.taskset.graders.some(w=>w.id===m&&w.privileged&&w.kind!=="human")))throw new ee("local_capability_not_qualified","The required private grader scope has no supported exact local grader owner.",422)}if(!l&&s.taskset.tools.length&&!a)throw new ee("local_tool_target_not_qualified","This Dataset's tools require a released native target executor.",422);if(l?.execution.javascript.executionServices?.length&&!o)throw new ee("local_prepared_environment_not_qualified","This Dataset requires prepared compute services that are not yet bound to the local execution owner.",422);if(s.taskset.environment.kind!=="text"&&!l)throw new ee("local_environment_unavailable","The released Dataset has no supported local environment executor.",422);if(d&&(l||s.taskset.environment.kind!=="text"))throw new ee("local_harness_environment_not_qualified","This native Harness requires a compatible text Dataset.",422);return c.population.map(u=>{let p=s.taskset.tasks.find(y=>y.id===u.taskId);if(!p)throw new ee("local_population_unavailable","The selected task is absent from this immutable Dataset release.",422);let m=IE(p);if((m.artifactRefs.length||p.requiredOutputs?.length)&&!(a&&c.policy.kind==="hosted_harness"))throw new ee("local_work_target_not_qualified","This Dataset requires document input or Work output capabilities not supplied by this local model target.",422);let w=l?.assets.find(y=>y.id===l.execution.javascript.module.id),g=l?.assets.find(y=>y.id===p.privilegedContextRef);if(l&&(!w||!g))throw new ee("local_environment_assets_missing","Private environment resources are missing from the retained package.",422);let f={kind:"model",id:`local-case-${A([r,u.receiptId]).slice(0,48)}`,taskId:p.id,model:e.model,...d?{harness:d}:{},instructions:y0(s),input:m.input,policyVisibleContext:m.policyVisibleContext,timeoutMs:s.taskset.environment.defaultTimeoutMs,environment:l?{kind:"javascript",definition:l.execution.javascript,asset:w,initialState:JSON.parse(Zr(g,g.asset)),seed:Number(u.seed)}:{kind:"text"}};return{receiptId:u.receiptId,taskId:u.taskId,seed:u.seed,request:e1.parse({...f,admissionHash:A(f)})}})}i(vN,"localExperimentAdmissions");function XQ(e){return!!zl(e)}i(XQ,"executionForClaude");import{readFile as QQ}from"node:fs/promises";import ZQ from"node:path";async function Tr(e,t,r,n){let o=await e.getHarnessReleaseRecord(t.contentHash),a=o&&await e.getHarnessWorkspace(o.workspaceId);if(!o||!a||o.harnessRelease.id!==t.id||a.location!=="local"||a.metadata.sourceLayout!=="openpond.harnessSourceManifest.v1")throw new ee("local_profile_source_unavailable","The exact Profile Harness is unavailable.",403);let s=a.metadata.profileExperimentOrigin!==void 0||a.metadata.experimentCandidateOrigin!==void 0;if(s){if(!n||!r)throw new ee("local_profile_origin_access_denied","This source requires its authenticated origin.",403);await n(a,t,r)}else{if(a.ownerScope.kind!=="personal"||a.ownerScope.id!=="desktop-personal"||typeof o.harnessRelease.metadata.profileRepositoryId=="string"||typeof o.agentSnapshot.metadata.profileRepositoryId=="string")throw new ee("local_profile_origin_access_denied","The Profile is not device-owned.",403);let m=o.harnessRelease.metadata.profile;if(r&&(r.source!=="local"||m?.id!==r.profileId||m.repositoryId&&m.repositoryId!==r.repositoryId))throw new ee("local_profile_origin_access_denied","The retained Harness differs from this exact Profile reference.",403);if(a.metadata.selectionEligible===!1&&(!r||!m?.repositoryId||m.repositoryId!==r.repositoryId||a.id!==`${qH}${A({ref:r,sourceRevision:m.sourceRevision}).slice(0,24)}`))throw new ee("local_profile_origin_access_denied","This explicit Profile release requires its canonical accepted reference.",403)}let c=await rM({workspace:a,release:o}),d=new Map;for(let m of o.harnessRelease.files)d.set(m.path,await QQ(ZQ.join(o.bundlePath,"source",...m.path.split("/"))));let l=Ea({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,files:d}),u=Xm(o);$m({sourcePackage:l,expectedRelease:t,baseSystemPrompt:"",runtimeId:"openpond.native-profile-experiment.v1",maxContextCharacters:262144,tools:u.map(m=>({name:m.name,inputSchema:m.inputSchema,definition:{type:"function",function:{name:m.name,description:m.description,parameters:m.inputSchema}}}))});let p=await e.getHarnessWorkspace(a.id);if(!p||A(p.ownerScope)!==A(a.ownerScope)||A(p.metadata)!==A(a.metadata))throw new ee("local_profile_origin_access_denied","Profile source ownership changed during admission.",403);return s&&await n(a,t,r),c}i(Tr,"resolveLocalProfileExperimentSource");var Mu=b.string().min(1).max(240),bN=b.string().regex(/^[a-f0-9]{64}$/),aS=b.object({schemaVersion:b.literal("openpond.experimentCandidateOrigin.v1"),candidateId:Mu,actorId:Mu,teamId:Mu,baseWorkspaceId:Mu,baseProfileRef:qo,baseProfileSourceRevision:b.string().min(1).max(500),baseRelease:b.object({id:Mu,contentHash:bN}).strict(),frozenRevision:b.number().int().positive(),frozenHash:bN}).strict();function kN(e){async function t(n,o,a){let s=aS.parse(n.metadata.experimentCandidateOrigin),c=await e.actorId(),d=await e.teamId();if(s.actorId!==c||s.teamId!==d||n.metadata.selectionEligible!==!1||n.location!=="local"||n.ownerScope.kind!=="personal"||n.ownerScope.id!==c)throw new Error("Candidate origin is unavailable to this account or placement.");let l=await e.improvements.read({actorId:c,teamId:d},s.candidateId);if(!l.frozen||["draft","authoring","failed","cancelled","declined"].includes(l.status)||l.ownerWorkspaceId!==s.baseWorkspaceId||A(l.profileRef)!==A(s.baseProfileRef)||l.baseProfileSourceRevision!==s.baseProfileSourceRevision||A(l.baseRelease)!==A(s.baseRelease)||l.frozen.candidateRevision!==s.frozenRevision||A(l.frozen)!==s.frozenHash||A(o)!==A(l.frozen.release)||A(n.currentChannel.release)!==A(o)||a&&A(a)!==A(l.profileRef))throw new Error("Candidate origin differs from its durable owner and exact frozen revision.");if(await Tr(e.store,l.baseRelease,l.profileRef,e.authorizeBaseOrigin),await e.actorId()!==c||await e.teamId()!==d)throw new Error("Candidate account changed during admission.");return l}i(t,"require");async function r(n){let o=await e.store.getHarnessReleaseRecord(n.contentHash);if(!o||o.harnessRelease.id!==n.id)return null;let a=await e.store.getHarnessWorkspace(o.workspaceId);return a?.metadata.experimentCandidateOrigin!==void 0?{workspace:a,release:o}:null}return i(r,"workspace"),{hasOrigin:i(async n=>!!await r(n),"hasOrigin"),authority:i((async(n,o,a)=>{await t(n,o,a)}),"authority"),async resolveRef(n,o,a){let s=await r(a);if(!s)throw new Error("Candidate source is unavailable.");let c=await t(s.workspace,a);if(c.profileRef.repositoryId!==n||c.profileRef.profileId!==o)throw new Error("Candidate Profile reference changed.");return c.profileRef},async workflows(n,o){if(!o)throw new Error("Candidate discovery requires its frozen source reference.");let a=await r(o.harnessRelease);if(!a)throw new Error("Candidate source is unavailable.");let s=await t(a.workspace,o.harnessRelease,n);if(o.sourceRevision!==s.frozen.profileSourceRevision)throw new Error("Candidate Profile source revision changed.");let c=await Wc({store:e.store,release:a.release,ref:n,sourceRevision:o.sourceRevision});return await t(a.workspace,o.harnessRelease,n),c}}}i(kN,"createLocalExperimentCandidateOriginAdapter");function dd(e){return async(t,r)=>{let n=await e.identity(),o=await e.resolveAccess(),a={baseUrl:o.apiBaseUrl,apiKey:o.token,teamId:n.teamId},s=new hr(a),c=new Qi(a),d=new rn(a),l=ei({...e,resolveAccess:i(async()=>({...await e.resolveAccess(),...await e.identity()}),"resolveAccess")});async function u(){if(A(await e.identity())!==A(n))throw new Error("The external Dataset account or workspace changed.");let w=await e.resolveAccess();if(w.apiBaseUrl.replace(/\/$/,"")!==o.apiBaseUrl.replace(/\/$/,"")||w.token!==o.token)throw new Error("The external Dataset connection changed.")}i(u,"current");async function p(){if(await u(),t.profileId!==r.profileRef.profileId)throw new Error("The external Dataset recipe names another Profile.");let w=await e.store.getHarnessReleaseRecord(r.harnessRelease.contentHash);if(!w||w.harnessRelease.id!==r.harnessRelease.id)throw new Error("The exact released Profile is unavailable.");let g=await e.store.getHarnessWorkspace(w.workspaceId);if(!g)throw new Error("The released Profile owner is unavailable.");let f=g.metadata.experimentCandidateOrigin===void 0?null:aS.parse(g.metadata.experimentCandidateOrigin);if(f&&(f.actorId!==n.actorId||f.teamId!==n.teamId||g.ownerScope.kind!=="personal"||g.ownerScope.id!==n.actorId||g.metadata.selectionEligible!==!1||A(f.baseProfileRef)!==A(r.profileRef)))throw new Error("The candidate source belongs to another owner or Profile.");if(r.profileRef.source==="local"){let I=await et(),v=await ft(r.profileRef);if(!I.profiles.some(R=>A(R.ref)===A(r.profileRef))||v.error||!v.sourcePath||v.activeProfile!==r.profileRef.profileId)throw new Error("The original Profile is no longer installed for this owner.")}else if(f){let I=await e.store.getHarnessWorkspace(f.baseWorkspaceId);if(!I)throw new Error("The candidate's original Profile is unavailable.");await l.authority(I,f.baseRelease,r.profileRef)}else await l.authority(g,r.harnessRelease,r.profileRef);let y=await _c({workspaceId:typeof w.agentSnapshot.metadata.workspaceId=="string"?w.agentSnapshot.metadata.workspaceId:w.workspaceId,sourceDir:eZ.join(w.bundlePath,"source")});if(y.harnessRelease.contentHash!==r.harnessRelease.contentHash||En(y).protectedClosureHash!==t.protectedProfileClosureHash)throw new Error("The original Profile's protected evaluator closure changed.");await u();let h=await s.getByRelease(t.dataset,{expectedPackageHash:t.packageHash});if(await u(),t.recordedOrigin){let I=t.recordedOrigin,v=await c.recordedExecution(I.execution.id),R=await d.scoringPass(I.originalEvidence.id),T=await d.scoringResult(I.originalEvidence.id);if(await u(),v.contentHash!==I.execution.contentHash||A(v.request.dataset)!==A(t.dataset)||T.manifest.population.length!==I.members.length||R.request.executionKind!=="recorded_evidence"||R.request.execution.id!==v.id||T.result.contentHash!==I.originalEvidence.contentHash||A(T.manifest.evaluators)!==A(t.evaluators))throw new Error("The original recorded grading evidence differs from this rerun recipe.");for(let[P,x]of I.members.entries()){let _=v.sources.filter(D=>D.boundaryId===x.caseId);if(_.length!==1)throw new Error("The original recorded case has no unique retained source cutoff.");let E=_[0],C=h.taskset.tasks.find(D=>D.id===x.caseId),O=C&&oI.parse(C.input.connectedEvidenceRef);if(!O||E.boundaryId!==x.caseId||E.id!==x.sourceId||E.snapshotHash!==x.snapshotHash||E.boundaryRevisionHash!==x.boundaryRevisionHash||A(O)!==A({id:E.id,snapshotHash:E.snapshotHash,boundaryId:E.boundaryId,boundaryRevisionHash:E.boundaryRevisionHash})||A(T.manifest.population[P])!==A({caseId:x.caseId,seed:x.seed,fixtureId:x.fixtureId}))throw new Error("The rerun changed an original ordered source cutoff.")}}let k=t.gradingSource?{pass:await d.scoringPass(t.gradingSource.pass.id),evidence:await d.scoringResult(t.gradingSource.evidence.id)}:void 0;await u();let S=Df({binding:t,packageValue:h,graders:yr(h),actualGrading:k});return await u(),S}i(p,"read");let m=await p();return{binding:t,packageValue:m,authorize:i(async()=>{if(A(await p())!==A(m))throw new Error("The external Dataset authority changed during preparation.")},"authorize")}}}i(dd,"createLocalExternalDatasetPreparation");function IN(e){let t=dd(e);async function r(o){let a=Rc(o),s=await e.identity();if(s.actorId!==a.actorId||s.teamId!==a.teamId)throw new Error("The advanced evaluation owner changed.");let c=await e.loadEvidence(s,a.evidence);if(c.result.status!=="completed"||c.manifest.dataset.id!==a.externalDatasetBinding.dataset.id||c.manifest.dataset.contentHash!==a.externalDatasetBinding.dataset.contentHash)throw new Error("Advanced Refiner evaluation requires exact completed source evidence from the selected Dataset.");if(!(await mh(e.storeDir)).releases.some(y=>y.id===a.refinerRelease.id&&y.contentHash===a.refinerRelease.contentHash))throw new Error("The exact admitted Refiner release is unavailable.");let l={profileRef:a.profileRef,sourceRevision:a.sourceRevision,harnessRelease:a.baselineRelease,workflows:[]},u=await t(a.adaptationDatasetBinding,l);await u.authorize();let p=await t(a.externalDatasetBinding,l),m=p.packageValue;if(m.environment.contentHash!==a.environmentPolicy.environmentHash)throw new Error("The advanced environment release changed.");if(a.mode==="downstream_adaptation"&&m.environment.contract.kind!=="work")throw new Error("This native Refiner adapter requires a released Work environment.");if(m.taskset.tools.some(y=>y.name==="web_search"||y.name==="web_fetch"))throw new Error("Advanced live web tools require a separately admitted budget and frozen-observation owner.");if(m.environment.contract.networkPolicy!=="none")throw new Error("This advanced adapter cannot bound live external tool charges. Select a resettable environment with network disabled; live-tool evaluation needs its own qualified admission owner.");if(u.packageValue.contentHash!==m.contentHash)throw new Error("This native adapter requires the same exact released package for adaptation and independent holdout.");let w=a.adaptationTaskIds.map(y=>u.packageValue.taskset.tasks.find(h=>h.id===y)),g=a.holdoutTaskIds.map(y=>m.taskset.tasks.find(h=>h.id===y));if(w.some(y=>!y||y.split!==a.adaptationSplit)||g.some(y=>!y||y.split!==a.holdoutSplit))throw new Error("The advanced population changed its ordered split membership.");let f=new Set(w.map(y=>y.clusterKey));if(g.some(y=>f.has(y.clusterKey)))throw new Error("Private holdout families overlap adaptation evidence.");if(m.verifierSet.graders.some(y=>y.kind==="human"||y.kind==="model_judge"&&y.calibrationStatus!=="passed"))throw new Error("Advanced evaluation needs executable deterministic or separately calibrated graders; human preference labels cannot become online reward.");if(await p.authorize(),a.mode==="review_quality"){let y=m.taskset.metadata.advancedRefinerReview;if(y?.outputConvention!=="openpond.refinerReviewOutput.v1"||A(y.contextEvidence)!==A(a.evidence))throw new Error("Review quality needs grounded independent labels bound to the exact retained context evidence.")}if(A(await e.identity())!==A(s))throw new Error("The advanced evaluation account changed during source admission.");return p}i(r,"read");async function n(o,a){if(await r(o),!e.localExperiments||!o.evidence.id.startsWith("local-"))throw new Error("This native review adapter requires actual retained local execution context. Hosted trace import requires a separately qualified current-owner context transport.");let s=RO.parse(await e.localExperiments().result({teamId:o.teamId,id:o.evidence.id}));if(s.execution.ownerActorId!==o.actorId)throw new Error("The review context belongs to another actor.");let c=s.cases.filter(f=>f.taskId===a&&f.status==="completed");if(c.length!==1)throw new Error("Choose one exact completed retained context per independent review case.");let d=c[0],l=d.profileNative??d.native;if(!l)throw new Error("The selected context has no actual native session/turn provenance.");if(l.outputHash!==A(d.output))throw new Error("The retained review output differs from its native execution.");let u=await e.store.getSession(l.sessionId),p=await e.store.getTurn(l.turnId);if(!u||!p||p.sessionId!==u.id||p.status==="in_progress")throw new Error("The actual retained review context is unavailable.");let m=await e.store.runtimeEventsForTurn(p.id),w=new Set(l.runtimeEventRefs),g=m.filter(f=>w.has(f.id));if(g.length!==w.size)throw new Error("The exact native review trace is incomplete.");return await r(o),{session:u,turn:p,events:g,case:d,traceHash:l.traceHash}}return i(n,"reviewContext"),{read:r,reviewContext:n,evidence:i(async o=>(await r(o),e.loadEvidence({actorId:o.actorId,teamId:o.teamId},o.evidence)),"evidence"),authorize:i(async o=>{await(await r(o)).authorize()},"authorize")}}i(IN,"createAdvancedRefinerEvaluationSource");import{randomUUID as RN}from"node:crypto";var wo=b.string().min(1).max(240),iS=b.object({id:wo,targetId:wo,jobId:wo,hostedModelId:wo,artifactHash:b.string().length(64),registryArtifactId:wo,registryArtifactHash:b.string().length(64),deploymentId:wo,servingPoolId:wo,authorizationHash:b.string().length(64),priorBindingId:wo,leaseId:wo.nullable(),bindingId:wo.nullable(),activatedAt:b.string().datetime().nullable(),canarySeconds:b.number().int().min(30).max(600),status:b.enum(["queued","claimed","canary","active","rolled_back","failed"])}).passthrough(),SN=b.object({request:iS,authorized:b.boolean()});function PN(e){let t=null,r=null,n=!1;async function o(g,f){return e.store.saveConversationServingExecution({...g,...f,revision:g.revision+1,updatedAt:new Date().toISOString()},g.revision)}i(o,"save");async function a(g,f){return SN.parse(await e.request(g.teamId,`serving-requests/${encodeURIComponent(f)}?ownerInstanceId=${encodeURIComponent(g.ownerInstanceId)}`))}i(a,"inspect");async function s(g,f,y){return iS.parse(await e.request(g.teamId,"serving-requests",{action:y,requestId:f.id,targetId:g.id,ownerInstanceId:g.ownerInstanceId,leaseId:f.leaseId,bindingId:f.bindingId,restoredBindingId:f.restoredBindingId,failure:f.failure}))}i(s,"command");async function c(g,f){let y=(await e.store.listConversationServingGrants()).find(h=>h.id===g.id);if(!y)throw new Error("The native serving grant disappeared.");y.expectedBindingId!==f&&await e.store.saveConversationServingGrant({...y,expectedBindingId:f,revision:y.revision+1,updatedAt:new Date().toISOString()},y.revision)}i(c,"updateExpectedBinding");async function d(g,f,y){let h=f.bindingId?await e.store.getModelBinding(f.bindingId):(await e.store.listModelBindings()).find(S=>S.promotedBy===`conversation:${f.id}`);if(!h){f=await o(f,{status:"failed",failure:y}),await s(g,f,"fail");return}let k=await e.store.getActiveModelBinding({profileId:g.profileId,role:g.role,roleTargetId:g.roleTargetId});if(f=await o(f,{status:"rolling_back",bindingId:h.id,failure:y}),k?.id===h.id){let S=await e.training.rollbackModelBinding({bindingId:h.id,rolledBackBy:`conversation:${f.id}:rollback`});if(!S.activeBinding)throw new Error("The authorized prior Model binding was not restored.");f=await o(f,{restoredBindingId:S.activeBinding.id})}else{let S=(await e.store.listModelBindings()).find(I=>I.status==="active"&&I.promotedBy===`conversation:${f.id}:rollback`&&I.priorBindingId===h.id);if(!S)throw new Error("The serving target changed outside this operation; automatic rollback cannot replace another owner's choice.");f=await o(f,{restoredBindingId:S.id})}await e.synchronization.reconcile(),await s(g,f,"rollback"),f=await o(f,{status:"rolled_back"}),await c(g,f.restoredBindingId)}i(d,"rollback");async function l(g,f){let y=f.request,h=(await e.store.listConversationServingExecutions(g.id)).find(T=>T.id===y.id);if(!h){if(!g.enabled||!f.authorized||g.authorizedConfigurationHash!==y.authorizationHash||y.hostedModelId!==g.hostedModelId||y.priorBindingId!==g.expectedBindingId)throw new Error("The requested serving change differs from the exact native grant.");let T=iS.parse(await e.request(g.teamId,"serving-requests",{action:"claim",requestId:y.id,targetId:g.id,ownerInstanceId:g.ownerInstanceId,leaseId:null,bindingId:null,restoredBindingId:null,failure:null}));if(!T.leaseId)throw new Error("The serving owner did not receive a retained lease.");h=await e.store.saveConversationServingExecution(tH.parse({id:y.id,grantId:g.id,revision:1,jobId:y.jobId,artifactHash:y.artifactHash,priorBindingId:y.priorBindingId,bindingId:null,restoredBindingId:null,status:"prepared",leaseId:T.leaseId,canarySeconds:y.canarySeconds,activatedAt:null,failure:null,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}),0)}if(["superseded","rolled_back","failed"].includes(h.status))return;if(h.status==="active"){if(!g.enabled)return;let T=h.bindingId?await e.store.getModelBinding(h.bindingId):null;if(!T||T.status!=="active"){await o(h,{status:"superseded"});return}let P=await e.store.getModelArtifactLineage(T.modelArtifactLineageId),_=(await e.registry.listRegistry(g.teamId)).deployments.find(E=>E.id===P?.managedServing?.canonicalDeploymentId);(!_||["degraded","failed","deleted","deleting"].includes(_.state))&&await d(g,h,"The current candidate deployment failed runtime health after activation.");return}if(y.status==="active"){await o(h,{status:"active"}),await c(g,y.bindingId);return}if(!g.enabled||!f.authorized||h.status==="rolling_back")return d(g,h,"Serving authority was revoked or the retained rollout requires rollback.");if(Date.now()-Date.parse(h.createdAt)>=12e5)return d(g,h,"The serving rollout exceeded its authorized reconciliation deadline.");if(await s(g,h,"renew"),h.status==="prepared"||h.status==="binding"){await e.hosting.pullProject({hostedProjectId:g.hostedModelId,profileId:g.profileId}),await e.training.refreshManagedRunEvidence(h.jobId),await e.synchronization.reconcile();let T=(await e.store.listModelBindings()).find(P=>P.promotedBy===`conversation:${h.id}`);if(T){if(T.status!=="active"||T.profileId!==g.profileId||T.role!==g.role||T.roleTargetId!==g.roleTargetId)throw new Error("The retained serving promotion changed outside its owner.");h=await o(h,{status:"canary",bindingId:T.id,activatedAt:T.promotedAt})}else{let P=(await e.store.listModelArtifactLineage()).filter(O=>O.jobId===h.jobId&&O.status==="imported");if(P.length!==1)throw new Error("The exact hosted candidate is not imported into the serving owner.");if(P[0].managedServing?.canonicalArtifactId!==y.registryArtifactId||P[0].managedServing?.canonicalDeploymentId!==y.deploymentId)throw new Error("The candidate differs from the exact authorized serving deployment.");let x=await e.store.getTrainingArtifact(P[0].artifactId);if(!x||x.sha256!==h.artifactHash)throw new Error("The serving candidate's immutable artifact changed.");let _=(await e.store.listConversationServingGrants()).find(O=>O.id===g.id),E=await a(g,h.id);if(!_?.enabled||_.authorizedConfigurationHash!==y.authorizationHash||!E.authorized)return d(g,h,"Serving authority changed immediately before native activation.");h=await o(h,{status:"binding"});let C=await e.training.bindModel({profileId:g.profileId,modelId:P[0].id,role:g.role,roleTargetId:g.roleTargetId,promotedBy:`conversation:${h.id}`,expectedActiveBindingId:h.priorBindingId,servingGrant:{id:_.id,expectedRevision:_.revision,authorizationHash:y.authorizationHash}});h=await o(h,{status:"canary",bindingId:C.id,activatedAt:C.promotedAt})}}await e.synchronization.reconcile();let k=await e.store.getModelBinding(h.bindingId),S=k?await e.store.getModelArtifactLineage(k.modelArtifactLineageId):null;if(!k||k.status!=="active"||!S?.managedServing)return d(g,h,"The active binding lost its verified serving projection.");let v=(await e.registry.listRegistry(g.teamId)).deployments.find(T=>T.id===S.managedServing.canonicalDeploymentId);if(!v||["degraded","failed","deleted","deleting"].includes(v.state))return d(g,h,"The candidate deployment failed the runtime canary.");if(v.state!=="ready")return;let R=await s(g,h,"canary");Date.now()-Date.parse(R.activatedAt)>=h.canarySeconds*1e3&&(await s(g,h,"complete"),await o(h,{status:"active"}),await c(g,h.bindingId))}i(l,"advance");async function u(){for(let g of await e.store.listConversationServingGrants())try{g.enabled&&await e.request(g.teamId,"serving-targets",{action:"heartbeat",targetId:g.id,ownerInstanceId:g.ownerInstanceId});let f=(await e.store.listConversationServingExecutions(g.id)).filter(h=>!["superseded","rolled_back","failed"].includes(h.status));for(let h of f)await l(g,await a(g,h.id));if(!g.enabled||!g.authorizedConfigurationHash)continue;let y=b.object({requests:b.array(SN)}).parse(await e.request(g.teamId,`serving-requests?targetId=${encodeURIComponent(g.id)}&ownerInstanceId=${encodeURIComponent(g.ownerInstanceId)}`));for(let h of y.requests)f.some(k=>k.id===h.request.id)||await l(g,h)}catch(f){let y=(await e.store.listConversationServingExecutions(g.id)).filter(h=>!["active","superseded","rolled_back","failed"].includes(h.status));for(let h of y)await o(h,{failure:f instanceof Error?f.message.slice(0,2e3):"Serving reconciliation failed."})}}i(u,"once");function p(){return n?Promise.resolve():(t||(t=u().finally(()=>{t=null})),t)}i(p,"reconcile");function m(){if(n||r||t)return;let g=i(()=>{r=null,p().finally(()=>{n||(r=setTimeout(g,1e4),r.unref?.())})},"tick");g()}i(m,"start");async function w(){n=!0,r&&clearTimeout(r),r=null,await t}return i(w,"close"),{start:m,close:w,reconcile:p}}i(PN,"createConversationServingWorker");var ds=b.string().trim().min(1).max(240),Ig=b.object({profileId:ds,modelId:ds});function xN(e){async function t(o,a,s){let c=await e.resolveAccess();if(c.teamId!==o)throw new Error("Select the serving grant's authorized workspace.");let d=xe(c.token);d.set("X-OpenPond-Team-Id",o),d.set("content-type","application/json");let l=await fetch(`${c.apiBaseUrl}/v1/connected-evidence/learning/${a}`,{headers:d,redirect:"error",signal:AbortSignal.timeout(2e4),method:s===void 0?"GET":"POST",...s===void 0?{}:{body:JSON.stringify(s)}}),u=await l.json();if(!l.ok)throw new Error(`Serving owner request failed (${l.status}): ${u.code??"request_failed"}`);return u}i(t,"request");async function r(o){let a=Ig.parse(o),s=await e.store.getModelProject(a.modelId);if(!s||s.profileId!==a.profileId||!s.hosted)throw new Error("Select a hosted Model in the serving Profile.");let c=await e.resolveAccess();if(s.hosted.teamId!==c.teamId||s.hosted.apiOrigin!==new URL(c.apiBaseUrl).origin)throw new Error("The serving Model belongs to a different workspace.");return{model:s,access:c}}i(r,"scoped");let n=PN({...e,request:t});return{start:n.start,close:n.close,reconcile:n.reconcile,async state(o){let{model:a,access:s}=await r(o),c=(await e.store.listConversationServingGrants()).filter(u=>u.profileId===a.profileId&&u.hostedModelId===a.hosted.projectId&&u.teamId===s.teamId),d=(await e.store.listModelBindings()).filter(u=>u.profileId===a.profileId&&u.status==="active"),l=await t(s.teamId,"policies");return{grants:c,bindings:d,policies:l.filter(u=>u.configuration.configuration?.id===a.hosted.projectId).map(u=>({...u,servingAuthorized:c.some(p=>p.enabled&&p.authorizedConfigurationHash===A(u.configuration)&&p.id===u.configuration.serving?.targetId)})),executions:(await Promise.all(c.map(u=>e.store.listConversationServingExecutions(u.id)))).flat()}},async register(o){let a=Ig.extend({projectId:ds,bindingId:ds}).strict().parse(o),{model:s,access:c}=await r(a),d=await e.store.getModelBinding(a.bindingId);if(!d||d.status!=="active"||d.profileId!==s.profileId)throw new Error("Select an active OpenPond binding in this Profile with a retained rollback target.");let u=(await e.store.listConversationServingGrants()).find(m=>m.teamId===c.teamId&&m.profileId===s.profileId&&m.role===d.role&&m.roleTargetId===d.roleTargetId&&m.projectId===a.projectId&&m.hostedModelId===s.hosted.projectId&&m.enabled);if(u)return await t(c.teamId,"serving-targets",{action:"register",targetId:u.id,projectId:u.projectId,ownerInstanceId:u.ownerInstanceId,profileId:u.profileId,role:u.role,roleTargetId:u.roleTargetId,expectedBindingId:u.expectedBindingId}),u;let p=eH.parse({id:`conversation-serving-${RN()}`,revision:1,ownerInstanceId:`serving-owner-${RN()}`,teamId:c.teamId,profileId:s.profileId,projectId:a.projectId,hostedModelId:s.hosted.projectId,role:d.role,roleTargetId:d.roleTargetId,expectedBindingId:d.id,policyId:null,authorizedConfigurationHash:null,enabled:!0,updatedAt:new Date().toISOString()});return await e.store.saveConversationServingGrant(p,0),await t(c.teamId,"serving-targets",{action:"register",targetId:p.id,projectId:p.projectId,ownerInstanceId:p.ownerInstanceId,profileId:p.profileId,role:p.role,roleTargetId:p.roleTargetId,expectedBindingId:p.expectedBindingId}),p},async authorize(o){let a=Ig.extend({grantId:ds,policyId:ds,expectedRevision:b.number().int().positive()}).strict().parse(o),{model:s,access:c}=await r(a),d=(await e.store.listConversationServingGrants()).find(p=>p.id===a.grantId&&p.enabled&&p.profileId===s.profileId&&p.hostedModelId===s.hosted.projectId&&p.teamId===c.teamId);if(!d)throw new Error("The native serving grant is unavailable.");let l=await t(c.teamId,"serving-targets",{action:"authorize",targetId:d.id,ownerInstanceId:d.ownerInstanceId,policyId:a.policyId,expectedRevision:a.expectedRevision}),u=await e.store.saveConversationServingGrant({...d,revision:d.revision+1,policyId:a.policyId,authorizedConfigurationHash:b.string().length(64).parse(l.authorizedConfigurationHash),updatedAt:new Date().toISOString()},d.revision);return await n.reconcile(),u},async revoke(o){let a=Ig.extend({grantId:ds}).strict().parse(o),{model:s,access:c}=await r(a),d=(await e.store.listConversationServingGrants()).find(u=>u.id===a.grantId&&u.profileId===s.profileId&&u.hostedModelId===s.hosted.projectId&&u.teamId===c.teamId);if(!d)throw new Error("The native serving grant is unavailable.");let l=await e.store.saveConversationServingGrant({...d,enabled:!1,authorizedConfigurationHash:null,revision:d.revision+1,updatedAt:new Date().toISOString()},d.revision);return await t(c.teamId,"serving-targets",{action:"revoke",targetId:l.id,ownerInstanceId:l.ownerInstanceId}),await n.reconcile(),l}}}i(xN,"createConversationServingOwner");var Ft=b.string().trim().min(1).max(240),_N=b.number().int().positive(),tZ=b.enum(["dataset","evaluator","model","training_configuration","training_run","harness","environment","experiment","learning_policy","deployment"]),rZ=b.object({kind:tZ,resourceId:Ft,release:ik.nullable(),role:b.enum(["training","validation","holdout","target","reward","evaluation","serving","source"])}).strict(),nZ=b.discriminatedUnion("kind",[b.object({kind:b.literal("model"),providerId:Ft,modelId:Ft,artifact:ik.nullable(),messages:b.array(b.object({role:b.enum(["system","user","assistant"]),content:b.string().max(1e5)}).strict()).max(100)}).strict(),b.object({kind:b.literal("harness"),profileRepositoryId:Ft,source:Yb}).strict(),b.object({kind:b.literal("agent"),source:TE}).strict(),b.object({kind:b.literal("suite"),profileRepositoryId:Ft,suiteId:Ft,sources:b.array(Yb).min(1).max(1e3)}).strict().superRefine((e,t)=>{let r=e.sources[0],n=new Set;for(let[o,a]of e.sources.entries())n.has(a.definitionId)&&t.addIssue({code:"custom",path:["sources",o],message:"Suite definitions must be unique."}),n.add(a.definitionId),(a.profileId!==r.profileId||a.sourceRevision!==r.sourceRevision||a.catalogHash!==r.catalogHash||ao(a.harnessRelease)!==ao(r.harnessRelease))&&t.addIssue({code:"custom",path:["sources",o],message:"Suite checks must belong to the same pinned Profile source and Harness release."})})]),TN=b.object({name:b.string().trim().min(1).max(200),description:b.string().max(1e4),targets:b.array(b.object({id:Ft,name:b.string().trim().min(1).max(200),target:nZ}).strict()).max(100),defaultTargetId:Ft.nullable(),resources:b.array(rZ).max(1e3)}).strict().superRefine((e,t)=>{new Set(e.targets.map(r=>r.id)).size!==e.targets.length&&t.addIssue({code:"custom",path:["targets"],message:"Target identities must be unique."}),e.defaultTargetId&&!e.targets.some(r=>r.id===e.defaultTargetId)&&t.addIssue({code:"custom",path:["defaultTargetId"],message:"Default target must belong to this Project."}),new Set(e.resources.map(r=>ao(r))).size!==e.resources.length&&t.addIssue({code:"custom",path:["resources"],message:"Resource links must be unique."})}),EN=b.object({schemaVersion:b.literal("openpond.trainingProject.v1"),id:Ft,teamId:Ft,creatorUserId:Ft,ownerScope:b.enum(["workspace","personal"]).optional(),revision:_N,content:TN,archived:b.boolean(),createdAt:b.string().datetime(),updatedAt:b.string().datetime()}).strict(),oZ=b.object({operationId:Ft,id:Ft,expectedRevision:b.number().int().nonnegative(),content:TN,ownerScope:b.enum(["workspace","personal"]).optional()}).strict(),aZ=b.object({operationId:Ft,expectedRevision:_N,archived:b.boolean()}).strict(),iZ=b.object({teamId:Ft,projects:b.array(EN).max(100),nextCursor:Ft.nullable()}).strict(),ETe=b.object({operation:b.enum(["evaluate","train","enable_learning","accept_candidate","serve"]),support:b.enum(["supported","unsupported"]),state:b.enum(["ready","needs_setup","blocked"]),reasons:b.array(b.object({code:Ft,message:b.string().min(1).max(2e3),field:b.string().nullable(),action:b.enum(["choose_target","choose_data","choose_evaluator","configure_runtime","request_access","configure_budget","wait","review_evidence"]).nullable()}).strict()).max(100)}).strict().superRefine((e,t)=>{e.state==="ready"&&(e.support!=="supported"||e.reasons.length)&&t.addIssue({code:"custom",message:"Ready operations must be supported with no blockers."}),e.state!=="ready"&&!e.reasons.length&&t.addIssue({code:"custom",message:"Unavailable operations must explain the next step."})}),zt=class{static{i(this,"OpenPondTrainingProjectClient")}constructor(e){this.options=e;let t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash||!e.apiKey.trim()||!e.teamId.trim())throw new Error("A clean API origin and workspace credentials are required.");this.baseUrl=t.toString().replace(/\/+$/,"")}options;baseUrl;async list(e={}){let t=iZ.parse(await this.request(`?${new URLSearchParams(e.cursor?{cursor:e.cursor}:{})}`,"GET",void 0,e.signal));if(t.teamId!==this.options.teamId||t.projects.some(r=>r.teamId!==this.options.teamId))throw new Error("Project list workspace mismatch.");return t}async get(e,t){return this.readback(await this.request(`/${encodeURIComponent(e)}`,"GET",void 0,t),e)}async save(e,t){let r=oZ.parse(e),n=this.readback(await this.request(`/${encodeURIComponent(r.id)}`,"PUT",r,t),r.id);if(n.revision!==r.expectedRevision+1||ao(n.content)!==ao(r.content))throw new Error("Project write revision mismatch.");if(r.ownerScope&&n.ownerScope!==r.ownerScope)throw new Error("Project owner scope mismatch.");return n}async archive(e,t,r){let n=aZ.parse(t),o=this.readback(await this.request(`/${encodeURIComponent(e)}/archive`,"POST",n,r),e);if(o.revision!==n.expectedRevision+1||o.archived!==n.archived)throw new Error("Project archive receipt mismatch.");return o}readback(e,t){let r=EN.parse(e);if(r.id!==t||r.teamId!==this.options.teamId)throw new Error("Project identity mismatch.");return r}async request(e,t,r,n){let o=await(this.options.fetch??fetch)(`${this.baseUrl}/v1/training-projects${e}`,{method:t,signal:n,redirect:"error",headers:{Authorization:`Bearer ${this.options.apiKey}`,"X-OpenPond-Team-Id":this.options.teamId,"Content-Type":"application/json"},...r===void 0?{}:{body:JSON.stringify(r)}});if(!o.ok)throw new Error(`Project request failed (${o.status}).`);return o.json()}};function AN(e){return async t=>{let r=await e.identity(),n=await e.access(),o=new zt({baseUrl:n.apiBaseUrl,apiKey:n.token,teamId:r.teamId}),a=new Set,s,c=new Set;for(let l=0;;l++){if(l>=100)throw new Error("Project associations exceeded the supported launch bound.");let u=await o.list(s?{cursor:s}:{});for(let p of u.projects)!p.archived&&p.content.resources.some(m=>m.kind==="training_configuration"&&m.resourceId===t)&&a.add(p.id);if(!u.nextCursor)break;if(c.has(u.nextCursor))throw new Error("Project association pagination did not advance.");c.add(u.nextCursor),s=u.nextCursor}if(a.size>1)throw new Error("This training configuration belongs to several Projects. Retain one explicit Project association before starting.");let d=await e.identity();if(d.actorId!==r.actorId||d.teamId!==r.teamId)throw new Error("The active account changed before training admission.");return Vo.parse({schemaVersion:"openpond.trainingActivityAuthority.v1",...r,projectId:[...a][0]??null})}}i(AN,"createTrainingActivityAuthorityResolver");import{randomUUID as SZ}from"node:crypto";import{mkdir as PZ,readFile as RZ,rename as xZ,rm as _Z,writeFile as TZ}from"node:fs/promises";import KN from"node:path";import{readFile as GN}from"node:fs/promises";import _g from"node:path";import{createHash as sZ}from"node:crypto";import{createReadStream as cZ}from"node:fs";import{copyFile as dZ,mkdir as sS,readFile as CN,stat as lZ,writeFile as cS}from"node:fs/promises";import ls from"node:path";async function MN(e){if(!e.plan.compatibility.compatible)throw new Error("Training Plan is incompatible and cannot be bundled.");if(!e.plan.dataPolicy.exportApproved)throw new Error("Training export approval is required before bundle creation.");if(e.taskset.contentHash!==e.plan.tasksetHash)throw new Error("Training Plan references a different Taskset hash.");let t=new Set(e.plan.dataPolicy.approvedSourceIds),r=e.projectedTrainingData?{...e.projectedTrainingData,sourcePath:e.projectedTrainingData.path}:uZ(e.taskset,e.plan,t);if(r.exampleCount===0)throw new Error("Training Bundle has no approved training examples.");await sS(e.directory,{recursive:!0});let n=[{path:"recipe.json",role:"recipe",content:ot(e.plan.recipe)},{path:"policy.json",role:"policy",content:ot({tasksetId:e.taskset.id,tasksetHash:e.taskset.contentHash,sourceIds:e.plan.dataPolicy.approvedSourceIds,retentionDays:e.plan.dataPolicy.retentionDays,region:e.plan.dataPolicy.region,trainingData:{exampleCount:r.exampleCount,eligibleRows:r.eligibleRows,selectionSeed:r.selectionSeed,selectionStrategy:r.selectionStrategy,taskIdsHash:r.taskIdsHash}})},{path:"provenance.json",role:"provenance",content:ot(e.taskset.authoringProvenance)}],o=[{path:"data/train.jsonl",sha256:r.contentHash,sizeBytes:r.sizeBytes,role:"task_data"}],a=ls.join(e.directory,"data/train.jsonl");await sS(ls.dirname(a),{recursive:!0}),"sourcePath"in r?await dZ(r.sourcePath,a):await cS(a,r.content,{encoding:"utf8",mode:384});let s=await pZ(a);if(s.contentHash!==r.contentHash||s.sizeBytes!==r.sizeBytes)throw new Error("Projected training data changed while the Bundle was created.");for(let m of n){let w=ls.join(e.directory,m.path);await sS(ls.dirname(w),{recursive:!0}),await cS(w,m.content,"utf8"),o.push({path:m.path,sha256:Re(m.content),sizeBytes:Buffer.byteLength(m.content),role:m.role})}let c=new Date().toISOString(),d={schemaVersion:"openpond.trainingBundle.v1",id:`training_bundle_${A([e.plan.contentHash,o]).slice(0,24)}`,planId:e.plan.id,tasksetId:e.taskset.id,tasksetHash:e.taskset.contentHash,recipeHash:A(e.plan.recipe),files:[{path:"manifest.json",sha256:"00000000",sizeBytes:0,role:"manifest"},...o],totalSizeBytes:o.reduce((m,w)=>m+w.sizeBytes,0),sourceIds:e.plan.dataPolicy.approvedSourceIds,excludedSourceIds:e.taskset.sourceRefs.map(m=>m.id).filter(m=>!t.has(m)),containsRawChats:!1,containsSecrets:!1,containsHiddenGraderAssets:!1,createdAt:c,contentHash:"00000000"},l=ah.parse(d),u=A({...l,contentHash:"",files:l.files.map(m=>m.path==="manifest.json"?{...m,sha256:"",sizeBytes:0}:m)}),p=ah.parse({...l,contentHash:u,files:l.files.map(m=>m.path==="manifest.json"?{...m,sha256:u,sizeBytes:0}:m)});return await cS(ls.join(e.directory,"manifest.json"),ot(p),"utf8"),p}i(MN,"buildTrainingBundle");function uZ(e,t,r){if(t.recipe.method!=="sft"&&t.recipe.method!=="dpo"&&t.recipe.method!=="grpo"&&t.recipe.method!=="ppo")throw new Error(`Training method ${t.recipe.method} cannot produce task data.`);let n=new Set(e.learningSignals.demonstrations.flatMap(p=>p.approved&&p.taskId?[p.taskId]:[])),o=e.metadata.learning===void 0?null:zE.parse(e.metadata.learning),a=i(p=>o?o.admissions.find(m=>m.taskId===p.id)?.supervisedTarget??null:p.expectedOutput,"supervisedTarget"),s=t.recipe.method==="grpo"?t.recipe.rollout.seed:t.recipe.method==="ppo"?t.recipe.policyOptimization.seed:t.recipe.optimizer.seed;if(t.recipe.method==="dpo"){let p=e.learningSignals.preferences.filter(g=>g.approved&&g.sourceRefs.every(f=>r.has(f))).map(g=>({priority:A([e.contentHash,s,"preference",g.id]),record:{id:g.id,prompt:g.prompt,chosen:g.chosen,rejected:g.rejected,sourceRefs:g.sourceRefs}})).sort((g,f)=>g.priority.localeCompare(f.priority)||g.record.id.localeCompare(f.record.id)).slice(0,t.recipe.dataset.maxPairs),m=p.length?`${p.map(g=>JSON.stringify(g.record)).join(`
|
|
14
14
|
`)}
|
|
15
15
|
`:"",w=Buffer.from(m,"utf8");return{content:m,contentHash:Re(w),sizeBytes:w.byteLength,exampleCount:p.length,eligibleRows:p.length,selectionSeed:s,selectionStrategy:t.recipe.dataset.selectionStrategy,taskIdsHash:A(p.map(g=>g.record.id))}}let c=t.recipe.method==="ppo"?t.recipe.policyOptimization.dataset.maxExamples:t.recipe.dataset.maxExamples,d=e.tasks.filter(p=>p.split==="train"&&p.sourceRefs.every(m=>r.has(m))&&(t.recipe.method==="grpo"||t.recipe.method==="ppo"||a(p)!==null&&n.has(p.id))).map(p=>({priority:A([e.contentHash,s,"train",p.id]),record:t.recipe.method==="grpo"||t.recipe.method==="ppo"?{id:p.id,input:p.input,policyVisibleContext:p.policyVisibleContext,tags:p.tags}:{id:p.id,input:p.input,policyVisibleContext:p.policyVisibleContext,expectedOutput:a(p),tags:p.tags}})).sort((p,m)=>p.priority.localeCompare(m.priority)||p.record.id.localeCompare(m.record.id)).slice(0,c),l=d.length?`${d.map(p=>JSON.stringify(p.record)).join(`
|
|
16
16
|
`)}
|