@astralbeam/sdk 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +0,0 @@
1
- import{n as e}from"./rolldown-runtime-Bh1tDfsg.js";import"./constants-enyqxaJi.js";import{t}from"./debug-qLts7gEt.js";import{$ as n,$n as r,$r as i,An as a,Ar as o,At as s,B as c,Bn as l,Br as u,Bt as d,C as f,Cn as p,Cr as m,Ct as h,D as g,Dn as _,Dr as v,Dt as y,E as b,En as x,Er as S,Et as C,Fn as w,Fr as T,Ft as E,G as D,Gn as O,Gr as k,Gt as A,Hn as j,Hr as M,Ht as N,In as P,Ir as F,It as I,J as ee,Jn as te,Jr as L,K as R,Kn as z,Kr as B,Kt as ne,L as V,Ln as re,Lr as ie,Lt as ae,M as oe,Mn as H,Mr as se,Mt as ce,Nn as le,Nr as U,Nt as W,O as G,On as ue,Or as de,Ot as fe,P as pe,Pn as me,Pr as he,Pt as ge,Q as _e,Qn as ve,Qr as ye,Rn as be,Rr as xe,Rt as Se,S as Ce,Sn as we,Sr as Te,St as Ee,T as De,Tn as Oe,Tr as ke,Tt as Ae,Un as je,Ur as Me,Ut as Ne,Vr as K,Vt as Pe,Wn as Fe,Wr as Ie,Wt as Le,X as Re,Xr as ze,Xt as Be,Y as Ve,Yn as He,Yr as Ue,Z as We,Zn as Ge,Zr as Ke,_ as qe,_i as Je,_r as Ye,_t as Xe,a as Ze,ai as Qe,an as $e,ar as et,at as tt,b as nt,bn as rt,br as it,bt as at,c as ot,ci as st,cn as ct,ct as lt,d as ut,di as dt,dn as ft,dr as pt,dt as mt,ei as ht,er as gt,et as _t,f as vt,fi as yt,fn as bt,fr as xt,ft as St,g as Ct,gi as wt,gn as Tt,gr as Et,gt as Dt,hn as Ot,hr as kt,ht as At,i as jt,ii as Mt,in as Nt,it as Pt,jn as Ft,jr as It,jt as Lt,k as Rt,kn as zt,kr as Bt,kt as Vt,l as Ht,li as Ut,ln as Wt,lr as Gt,lt as Kt,m as qt,mn as Jt,mr as Yt,mt as Xt,n as Zt,ni as q,nn as Qt,nr as $t,nt as en,o as tn,oi as nn,on as rn,or as an,ot as on,p as sn,pi as cn,pn as ln,pr as un,pt as dn,q as fn,qn as J,qr as pn,qt as mn,r as hn,ri as gn,rn as _n,rr as vn,rt as yn,s as bn,si as xn,sn as Sn,sr as Cn,st as wn,t as Tn,ti as En,tn as Dn,tt as On,u as kn,ui as An,un as jn,ur as Mn,ut as Nn,v as Pn,vi as Fn,vn as In,vr as Ln,vt as Rn,w as zn,wn as Bn,wr as Vn,wt as Hn,x as Un,xn as Wn,xr as Gn,xt as Kn,y as qn,yi as Jn,yn as Yn,yr as Xn,yt as Zn,zn as Qn,zr as $n,zt as er}from"./styles.generated-Ucyw8D9G.js";var Y=e(Jn(),1);const tr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M208.49,120.49a12,12,0,0,1-17,0L140,69V216a12,12,0,0,1-24,0V69L64.49,120.49a12,12,0,0,1-17-17l72-72a12,12,0,0,1,17,0l72,72A12,12,0,0,1,208.49,120.49Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M200,112H56l72-72Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M205.66,106.34l-72-72a8,8,0,0,0-11.32,0l-72,72A8,8,0,0,0,56,120h64v96a8,8,0,0,0,16,0V120h64a8,8,0,0,0,5.66-13.66ZM75.31,104,128,51.31,180.69,104Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M207.39,115.06A8,8,0,0,1,200,120H136v96a8,8,0,0,1-16,0V120H56a8,8,0,0,1-5.66-13.66l72-72a8,8,0,0,1,11.32,0l72,72A8,8,0,0,1,207.39,115.06Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M204.24,116.24a6,6,0,0,1-8.48,0L134,54.49V216a6,6,0,0,1-12,0V54.49L60.24,116.24a6,6,0,0,1-8.48-8.48l72-72a6,6,0,0,1,8.48,0l72,72A6,6,0,0,1,204.24,116.24Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M205.66,117.66a8,8,0,0,1-11.32,0L136,59.31V216a8,8,0,0,1-16,0V59.31L61.66,117.66a8,8,0,0,1-11.32-11.32l72-72a8,8,0,0,1,11.32,0l72,72A8,8,0,0,1,205.66,117.66Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M202.83,114.83a4,4,0,0,1-5.66,0L132,49.66V216a4,4,0,0,1-8,0V49.66L58.83,114.83a4,4,0,0,1-5.66-5.66l72-72a4,4,0,0,1,5.66,0l72,72A4,4,0,0,1,202.83,114.83Z`}))]]),nr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M208,160H48l80-80Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M213.66,154.34l-80-80a8,8,0,0,0-11.32,0l-80,80A8,8,0,0,0,48,168H208a8,8,0,0,0,5.66-13.66ZM67.31,152,128,91.31,188.69,152Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M215.39,163.06A8,8,0,0,1,208,168H48a8,8,0,0,1-5.66-13.66l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,215.39,163.06Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M212.24,164.24a6,6,0,0,1-8.48,0L128,88.49,52.24,164.24a6,6,0,0,1-8.48-8.48l80-80a6,6,0,0,1,8.48,0l80,80A6,6,0,0,1,212.24,164.24Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M213.66,165.66a8,8,0,0,1-11.32,0L128,91.31,53.66,165.66a8,8,0,0,1-11.32-11.32l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,213.66,165.66Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M210.83,162.83a4,4,0,0,1-5.66,0L128,85.66,50.83,162.83a4,4,0,0,1-5.66-5.66l80-80a4,4,0,0,1,5.66,0l80,80A4,4,0,0,1,210.83,162.83Z`}))]]),rr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M140,80v41.21l34.17,20.5a12,12,0,1,1-12.34,20.58l-40-24A12,12,0,0,1,116,128V80a12,12,0,0,1,24,0ZM128,28A99.38,99.38,0,0,0,57.24,57.34c-4.69,4.74-9,9.37-13.24,14V64a12,12,0,0,0-24,0v40a12,12,0,0,0,12,12H72a12,12,0,0,0,0-24H57.77C63,86,68.37,80.22,74.26,74.26a76,76,0,1,1,1.58,109,12,12,0,0,0-16.48,17.46A100,100,0,1,0,128,28Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M136,80v43.47l36.12,21.67a8,8,0,0,1-8.24,13.72l-40-24A8,8,0,0,1,120,128V80a8,8,0,0,1,16,0Zm-8-48A95.44,95.44,0,0,0,60.08,60.15C52.81,67.51,46.35,74.59,40,82V64a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H72a8,8,0,0,0,0-16H49c7.15-8.42,14.27-16.35,22.39-24.57a80,80,0,1,1,1.66,114.75,8,8,0,1,0-11,11.64A96,96,0,1,0,128,32Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M224,128A96,96,0,0,1,62.11,197.82a8,8,0,1,1,11-11.64A80,80,0,1,0,71.43,71.43C67.9,75,64.58,78.51,61.35,82L77.66,98.34A8,8,0,0,1,72,112H32a8,8,0,0,1-8-8V64a8,8,0,0,1,13.66-5.66L50,70.7c3.22-3.49,6.54-7,10.06-10.55A96,96,0,0,1,224,128ZM128,72a8,8,0,0,0-8,8v48a8,8,0,0,0,3.88,6.86l40,24a8,8,0,1,0,8.24-13.72L136,123.47V80A8,8,0,0,0,128,72Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M134,80v44.6l37.09,22.25a6,6,0,0,1-6.18,10.3l-40-24A6,6,0,0,1,122,128V80a6,6,0,0,1,12,0Zm-6-46A93.4,93.4,0,0,0,61.51,61.56c-8.58,8.68-16,17-23.51,25.8V64a6,6,0,0,0-12,0v40a6,6,0,0,0,6,6H72a6,6,0,0,0,0-12H44.73C52.86,88.29,60.79,79.35,70,70a82,82,0,1,1,1.7,117.62,6,6,0,1,0-8.24,8.72A94,94,0,1,0,128,34Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M136,80v43.47l36.12,21.67a8,8,0,0,1-8.24,13.72l-40-24A8,8,0,0,1,120,128V80a8,8,0,0,1,16,0Zm-8-48A95.44,95.44,0,0,0,60.08,60.15C52.81,67.51,46.35,74.59,40,82V64a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H72a8,8,0,0,0,0-16H49c7.15-8.42,14.27-16.35,22.39-24.57a80,80,0,1,1,1.66,114.75,8,8,0,1,0-11,11.64A96,96,0,1,0,128,32Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M132,80v45.74l38.06,22.83a4,4,0,0,1-4.12,6.86l-40-24A4,4,0,0,1,124,128V80a4,4,0,0,1,8,0Zm-4-44A91.42,91.42,0,0,0,62.93,63C53.05,73,44.66,82.47,36,92.86V64a4,4,0,0,0-8,0v40a4,4,0,0,0,4,4H72a4,4,0,0,0,0-8H40.47C49.61,89,58.3,79,68.6,68.6a84,84,0,1,1,1.75,120.49,4,4,0,1,0-5.5,5.82A92,92,0,1,0,128,36Z`}))]]),ir=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,28H88A12,12,0,0,0,76,40V76H40A12,12,0,0,0,28,88V216a12,12,0,0,0,12,12H168a12,12,0,0,0,12-12V180h36a12,12,0,0,0,12-12V40A12,12,0,0,0,216,28ZM156,204H52V100H156Zm48-48H180V88a12,12,0,0,0-12-12H100V52H204Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,40V168H168V88H88V40Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M216,32H88a8,8,0,0,0-8,8V80H40a8,8,0,0,0-8,8V216a8,8,0,0,0,8,8H168a8,8,0,0,0,8-8V176h40a8,8,0,0,0,8-8V40A8,8,0,0,0,216,32ZM160,208H48V96H160Zm48-48H176V88a8,8,0,0,0-8-8H96V48H208Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,32H88a8,8,0,0,0-8,8V80H40a8,8,0,0,0-8,8V216a8,8,0,0,0,8,8H168a8,8,0,0,0,8-8V176h40a8,8,0,0,0,8-8V40A8,8,0,0,0,216,32Zm-8,128H176V88a8,8,0,0,0-8-8H96V48H208Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,34H88a6,6,0,0,0-6,6V82H40a6,6,0,0,0-6,6V216a6,6,0,0,0,6,6H168a6,6,0,0,0,6-6V174h42a6,6,0,0,0,6-6V40A6,6,0,0,0,216,34ZM162,210H46V94H162Zm48-48H174V88a6,6,0,0,0-6-6H94V46H210Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,32H88a8,8,0,0,0-8,8V80H40a8,8,0,0,0-8,8V216a8,8,0,0,0,8,8H168a8,8,0,0,0,8-8V176h40a8,8,0,0,0,8-8V40A8,8,0,0,0,216,32ZM160,208H48V96H160Zm48-48H176V88a8,8,0,0,0-8-8H96V48H208Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,36H88a4,4,0,0,0-4,4V84H40a4,4,0,0,0-4,4V216a4,4,0,0,0,4,4H168a4,4,0,0,0,4-4V172h44a4,4,0,0,0,4-4V40A4,4,0,0,0,216,36ZM164,212H44V92H164Zm48-48H172V88a4,4,0,0,0-4-4H92V44H212Z`}))]]),ar=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M225.6,62.64l-88-48.17a19.91,19.91,0,0,0-19.2,0l-88,48.17A20,20,0,0,0,20,80.19v95.62a20,20,0,0,0,10.4,17.55l88,48.17a19.89,19.89,0,0,0,19.2,0l88-48.17A20,20,0,0,0,236,175.81V80.19A20,20,0,0,0,225.6,62.64ZM128,36.57,200,76,128,115.4,56,76ZM44,96.79l72,39.4v76.67L44,173.44Zm96,116.07V136.19l72-39.4v76.65Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M128,129.09V232a8,8,0,0,1-3.84-1l-88-48.16a8,8,0,0,1-4.16-7V80.2a8,8,0,0,1,.7-3.27Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M223.68,66.15,135.68,18h0a15.88,15.88,0,0,0-15.36,0l-88,48.17a16,16,0,0,0-8.32,14v95.64a16,16,0,0,0,8.32,14l88,48.17a15.88,15.88,0,0,0,15.36,0l88-48.17a16,16,0,0,0,8.32-14V80.18A16,16,0,0,0,223.68,66.15ZM128,32h0l80.34,44L128,120,47.66,76ZM40,90l80,43.78v85.79L40,175.82Zm96,129.57V133.82L216,90v85.78Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M223.68,66.15,135.68,18a15.88,15.88,0,0,0-15.36,0l-88,48.17a16,16,0,0,0-8.32,14v95.64a16,16,0,0,0,8.32,14l88,48.17a15.88,15.88,0,0,0,15.36,0l88-48.17a16,16,0,0,0,8.32-14V80.18A16,16,0,0,0,223.68,66.15ZM128,120,47.65,76,128,32l80.35,44Zm8,99.64V133.83l80-43.78v85.76Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M222.72,67.9l-88-48.17a13.9,13.9,0,0,0-13.44,0l-88,48.18A14,14,0,0,0,26,80.18v95.64a14,14,0,0,0,7.28,12.27l88,48.18a13.92,13.92,0,0,0,13.44,0l88-48.18A14,14,0,0,0,230,175.82V80.18A14,14,0,0,0,222.72,67.9ZM127,30.25a2,2,0,0,1,1.92,0L212.51,76,128,122.24,43.49,76ZM39,177.57a2,2,0,0,1-1-1.75V86.66l84,46V223Zm177.92,0L134,223V132.64l84-46v89.16A2,2,0,0,1,217,177.57Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M223.68,66.15,135.68,18h0a15.88,15.88,0,0,0-15.36,0l-88,48.17a16,16,0,0,0-8.32,14v95.64a16,16,0,0,0,8.32,14l88,48.17a15.88,15.88,0,0,0,15.36,0l88-48.17a16,16,0,0,0,8.32-14V80.18A16,16,0,0,0,223.68,66.15ZM128,32h0l80.34,44L128,120,47.66,76ZM40,90l80,43.78v85.79L40,175.82Zm96,129.57V133.82L216,90v85.78Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M221.76,69.66l-88-48.18a12,12,0,0,0-11.52,0l-88,48.18A12,12,0,0,0,28,80.18v95.64a12,12,0,0,0,6.24,10.52l88,48.18a11.95,11.95,0,0,0,11.52,0l88-48.18A12,12,0,0,0,228,175.82V80.18A12,12,0,0,0,221.76,69.66ZM126.08,28.5a3.94,3.94,0,0,1,3.84,0L216.67,76,128,124.52,39.33,76Zm-88,150.83A4,4,0,0,1,36,175.82V83.29l88,48.16v94.91Zm179.84,0-85.92,47V131.45l88-48.16v92.53A4,4,0,0,1,217.92,179.32Z`}))]]),or=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M144,128a16,16,0,1,1-16-16A16,16,0,0,1,144,128ZM60,112a16,16,0,1,0,16,16A16,16,0,0,0,60,112Zm136,0a16,16,0,1,0,16,16A16,16,0,0,0,196,112Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M240,96v64a16,16,0,0,1-16,16H32a16,16,0,0,1-16-16V96A16,16,0,0,1,32,80H224A16,16,0,0,1,240,96Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm56-12a12,12,0,1,0,12,12A12,12,0,0,0,196,116ZM60,116a12,12,0,1,0,12,12A12,12,0,0,0,60,116Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M224,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V96A16,16,0,0,0,224,80ZM60,140a12,12,0,1,1,12-12A12,12,0,0,1,60,140Zm68,0a12,12,0,1,1,12-12A12,12,0,0,1,128,140Zm68,0a12,12,0,1,1,12-12A12,12,0,0,1,196,140Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M138,128a10,10,0,1,1-10-10A10,10,0,0,1,138,128ZM60,118a10,10,0,1,0,10,10A10,10,0,0,0,60,118Zm136,0a10,10,0,1,0,10,10A10,10,0,0,0,196,118Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm56-12a12,12,0,1,0,12,12A12,12,0,0,0,196,116ZM60,116a12,12,0,1,0,12,12A12,12,0,0,0,60,116Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M136,128a8,8,0,1,1-8-8A8,8,0,0,1,136,128Zm-76-8a8,8,0,1,0,8,8A8,8,0,0,0,60,120Zm136,0a8,8,0,1,0,8,8A8,8,0,0,0,196,120Z`}))]]),sr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M180.49,143.51a12,12,0,0,1,0,17l-24,24a12,12,0,0,1-17-17L155,152l-15.52-15.51a12,12,0,1,1,17-17Zm-64-24a12,12,0,0,0-17,0l-24,24a12,12,0,0,0,0,17l24,24a12,12,0,0,0,17-17L101,152l15.52-15.51A12,12,0,0,0,116.49,119.51ZM220,88V216a20,20,0,0,1-20,20H56a20,20,0,0,1-20-20V40A20,20,0,0,1,56,20h96a12,12,0,0,1,8.49,3.52l56,56A12,12,0,0,1,220,88ZM160,57V80h23Zm36,155V104H148a12,12,0,0,1-12-12V44H60V212Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M208,88H152V32Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M181.66,146.34a8,8,0,0,1,0,11.32l-24,24a8,8,0,0,1-11.32-11.32L164.69,152l-18.35-18.34a8,8,0,0,1,11.32-11.32Zm-72-24a8,8,0,0,0-11.32,0l-24,24a8,8,0,0,0,0,11.32l24,24a8,8,0,0,0,11.32-11.32L91.31,152l18.35-18.34A8,8,0,0,0,109.66,122.34ZM216,88V216a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-56-8h28.69L160,51.31Zm40,136V96H152a8,8,0,0,1-8-8V40H56V216H200Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M213.66,82.34l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40V216a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V88A8,8,0,0,0,213.66,82.34Zm-104,88a8,8,0,0,1-11.32,11.32l-24-24a8,8,0,0,1,0-11.32l24-24a8,8,0,0,1,11.32,11.32L91.31,152Zm72-12.68-24,24a8,8,0,0,1-11.32-11.32L164.69,152l-18.35-18.34a8,8,0,0,1,11.32-11.32l24,24A8,8,0,0,1,181.66,157.66ZM152,88V44l44,44Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M180.24,147.76a6,6,0,0,1,0,8.48l-24,24a6,6,0,0,1-8.48-8.48L167.51,152l-19.75-19.76a6,6,0,1,1,8.48-8.48Zm-72-24a6,6,0,0,0-8.48,0l-24,24a6,6,0,0,0,0,8.48l24,24a6,6,0,1,0,8.48-8.48L88.49,152l19.75-19.76A6,6,0,0,0,108.24,123.76ZM214,88V216a14,14,0,0,1-14,14H56a14,14,0,0,1-14-14V40A14,14,0,0,1,56,26h96a6,6,0,0,1,4.25,1.76l56,56A6,6,0,0,1,214,88Zm-56-6h35.52L158,46.48Zm44,134V94H152a6,6,0,0,1-6-6V38H56a2,2,0,0,0-2,2V216a2,2,0,0,0,2,2H200A2,2,0,0,0,202,216Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M181.66,146.34a8,8,0,0,1,0,11.32l-24,24a8,8,0,0,1-11.32-11.32L164.69,152l-18.35-18.34a8,8,0,0,1,11.32-11.32Zm-72-24a8,8,0,0,0-11.32,0l-24,24a8,8,0,0,0,0,11.32l24,24a8,8,0,0,0,11.32-11.32L91.31,152l18.35-18.34A8,8,0,0,0,109.66,122.34ZM216,88V216a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-56-8h28.69L160,51.31Zm40,136V96H152a8,8,0,0,1-8-8V40H56V216H200Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M178.83,149.17a4,4,0,0,1,0,5.66l-24,24a4,4,0,0,1-5.66-5.66L170.34,152l-21.17-21.17a4,4,0,1,1,5.66-5.66Zm-72-24a4,4,0,0,0-5.66,0l-24,24a4,4,0,0,0,0,5.66l24,24a4,4,0,1,0,5.66-5.66L85.66,152l21.17-21.17A4,4,0,0,0,106.83,125.17ZM212,88V216a12,12,0,0,1-12,12H56a12,12,0,0,1-12-12V40A12,12,0,0,1,56,28h96a4,4,0,0,1,2.83,1.17l56,56A4,4,0,0,1,212,88Zm-56-4h42.34L156,41.65Zm48,132V92H152a4,4,0,0,1-4-4V36H56a4,4,0,0,0-4,4V216a4,4,0,0,0,4,4H200A4,4,0,0,0,204,216Z`}))]]),cr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M48,180c0,8.67,5.49,16,12,16a10.27,10.27,0,0,0,7.33-3.43,12,12,0,1,1,17.34,16.6A34,34,0,0,1,60,220C40.15,220,24,202,24,180s16.15-40,36-40a34,34,0,0,1,24.67,10.83,12,12,0,1,1-17.34,16.6A10.27,10.27,0,0,0,60,164C53.49,164,48,171.31,48,180Zm97.51-5.71c-5.13-3.45-11.33-5.24-16.8-6.82a79.5,79.5,0,0,1-7.91-2.59c2.45-1.18,9.71-1.3,16.07.33A12,12,0,0,0,143,142a69.24,69.24,0,0,0-12-1.86c-9.93-.66-18,1.08-24.1,5.17a24.45,24.45,0,0,0-10.69,17.76c-1.1,8.74,2.48,16.27,10.11,21.19,4.78,3.09,10.36,4.7,15.75,6.26,3,.89,7.94,2.3,9.88,3.53a2,2,0,0,1-.22.71c-1.36,1.55-9.57,1.79-16.39-.06a12,12,0,0,0-6.45,23.11A63.73,63.73,0,0,0,125.09,220c6.47,0,13.74-1.17,19.74-5.15a24.73,24.73,0,0,0,10.95-18C157,187.53,153.32,179.53,145.51,174.27ZM216,140.68A12,12,0,0,0,200.7,148L192,172.3,183.3,148A12,12,0,1,0,160.7,156l20,56a12,12,0,0,0,22.6,0l20-56A12,12,0,0,0,216,140.68ZM36,108V40A20,20,0,0,1,56,20h96a12,12,0,0,1,8.49,3.51l56,56A12,12,0,0,1,220,88v20a12,12,0,1,1-24,0v-4H148a12,12,0,0,1-12-12V44H60v64a12,12,0,1,1-24,0ZM160,80h23L160,57Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M208,88H152V32Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.83-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M213.66,82.34l-56-56A8,8,0,0,0,152,24H56A16,16,0,0,0,40,40v76a4,4,0,0,0,4,4H212a4,4,0,0,0,4-4V88A8,8,0,0,0,213.66,82.34ZM152,88V44l44,44ZM48,180c0,11,7.18,20,16,20a14.18,14.18,0,0,0,10.06-4.5,8.21,8.21,0,0,1,10.9-.91,8,8,0,0,1,.82,11.81A30.06,30.06,0,0,1,64,216c-17.64,0-32-16.15-32-36s14.36-36,32-36a30,30,0,0,1,21.39,9.19,8.26,8.26,0,0,1,.73,11.09,8,8,0,0,1-11.9.38A14.17,14.17,0,0,0,64,160C55.18,160,48,169,48,180Zm103.81,16.31a20.82,20.82,0,0,1-9.19,15.23C137.43,215,131,216,125.13,216A61.14,61.14,0,0,1,110,214a8,8,0,1,1,4.3-15.41c4.38,1.2,14.95,2.7,19.55-.36.88-.59,1.83-1.52,2.14-3.93.35-2.67-.71-4.1-12.78-7.59-9.35-2.7-25-7.23-23-23.11a20.56,20.56,0,0,1,9-14.95c11.84-8,30.71-3.31,32.83-2.76a8,8,0,0,1-4.07,15.48c-4.49-1.17-15.23-2.56-19.83.56a4.54,4.54,0,0,0-2,3.67c-.12.9-.14,1.09,1.11,1.9,2.31,1.49,6.45,2.68,10.45,3.84C137.49,174.17,154.05,179,151.81,196.31ZM215.42,155l-19.89,55.68a8,8,0,0,1-15.06,0L160.58,155a8.21,8.21,0,0,1,4.5-10.45,8,8,0,0,1,10.45,4.76L188,184.21l12.47-34.9a8,8,0,0,1,10.45-4.76A8.23,8.23,0,0,1,215.42,155Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M46,180c0,12.13,8.07,22,18,22a16.24,16.24,0,0,0,11.67-5.28,6,6,0,0,1,8.66,8.3A28.06,28.06,0,0,1,64,214c-16.54,0-30-15.25-30-34s13.46-34,30-34a28.06,28.06,0,0,1,20.33,9,6,6,0,0,1-8.66,8.3A16.23,16.23,0,0,0,64,158C54.07,158,46,167.86,46,180Zm81.05-6.77c-10.86-3.13-13.41-4.69-13-7.91a6.59,6.59,0,0,1,2.88-5.08c5.6-3.79,17.66-1.82,21.45-.84a6,6,0,0,0,3.06-11.6c-2-.53-20.1-5-31.21,2.48a18.61,18.61,0,0,0-8.08,13.54c-1.8,14.19,12.26,18.25,21.57,20.94,12.12,3.5,14.78,5.33,14.2,9.76a6.85,6.85,0,0,1-3,5.34c-5.61,3.73-17.48,1.64-21.19.62A6,6,0,0,0,110.48,212a59.41,59.41,0,0,0,14.68,2c5.49,0,11.54-.95,16.36-4.14a18.89,18.89,0,0,0,8.31-13.81C151.84,180.39,136.92,176.08,127.05,173.22Zm83-26.88a6,6,0,0,0-7.67,3.63L188,190.15,173.65,150a6,6,0,1,0-11.3,4l20,56a6,6,0,0,0,11.3,0l20-56A6,6,0,0,0,210,146.34ZM214,88v24a6,6,0,1,1-12,0V94H152a6,6,0,0,1-6-6V38H56a2,2,0,0,0-2,2v72a6,6,0,1,1-12,0V40A14,14,0,0,1,56,26h96a6,6,0,0,1,4.24,1.76l56,56A6,6,0,0,1,214,88Zm-20.49-6L158,46.48V82Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M44,180c0,13.23,9,24,20,24a18.15,18.15,0,0,0,13.11-5.9,4,4,0,1,1,5.78,5.54A26.11,26.11,0,0,1,64,212c-15.44,0-28-14.36-28-32s12.56-32,28-32a26.11,26.11,0,0,1,18.89,8.36,4,4,0,1,1-5.78,5.54A18.15,18.15,0,0,0,64,156C53,156,44,166.77,44,180Zm82.49-4.85c-10.53-3-15.08-4.91-14.42-10.08a8.51,8.51,0,0,1,3.75-6.49c6.25-4.23,18.77-2.24,23.06-1.11a4,4,0,0,0,2-7.74,61.11,61.11,0,0,0-10.47-1.61c-8.12-.54-14.54.75-19.1,3.82a16.66,16.66,0,0,0-7.22,12.13c-1.58,12.49,10.46,16,20.14,18.77,11.26,3.25,16.47,5.49,15.64,11.94a8.94,8.94,0,0,1-3.91,6.75c-6.27,4.17-18.61,2.05-22.83.88a4,4,0,1,0-2.15,7.7A57.89,57.89,0,0,0,125.19,212c5.18,0,10.83-.86,15.22-3.77a17,17,0,0,0,7.43-12.41C149.64,181.84,136.26,178,126.49,175.15Zm82.85-26.92a4,4,0,0,0-5.11,2.42L188,196.11l-16.23-45.46a4,4,0,1,0-7.54,2.7l20,56a4,4,0,0,0,7.54,0l20-56A4,4,0,0,0,209.34,148.23ZM212,88v24a4,4,0,0,1-8,0V92H152a4,4,0,0,1-4-4V36H56a4,4,0,0,0-4,4v72a4,4,0,0,1-8,0V40A12,12,0,0,1,56,28h96a4,4,0,0,1,2.83,1.17l56,56A4,4,0,0,1,212,88Zm-13.66-4L156,41.65V84Z`}))]]),lr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M232.49,55.51l-32-32a12,12,0,0,0-17,0l-96,96A12,12,0,0,0,84,128v32a12,12,0,0,0,12,12h32a12,12,0,0,0,8.49-3.51l96-96A12,12,0,0,0,232.49,55.51ZM192,49l15,15L196,75,181,60Zm-69,99H108V133l56-56,15,15Zm105-7.43V208a20,20,0,0,1-20,20H48a20,20,0,0,1-20-20V48A20,20,0,0,1,48,28h67.43a12,12,0,0,1,0,24H52V204H204V140.57a12,12,0,0,1,24,0Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M200,88l-72,72H96V128l72-72Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M229.66,58.34l-32-32a8,8,0,0,0-11.32,0l-96,96A8,8,0,0,0,88,128v32a8,8,0,0,0,8,8h32a8,8,0,0,0,5.66-2.34l96-96A8,8,0,0,0,229.66,58.34ZM124.69,152H104V131.31l64-64L188.69,88ZM200,76.69,179.31,56,192,43.31,212.69,64ZM224,128v80a16,16,0,0,1-16,16H48a16,16,0,0,1-16-16V48A16,16,0,0,1,48,32h80a8,8,0,0,1,0,16H48V208H208V128a8,8,0,0,1,16,0Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M224,128v80a16,16,0,0,1-16,16H48a16,16,0,0,1-16-16V48A16,16,0,0,1,48,32h80a8,8,0,0,1,0,16H48V208H208V128a8,8,0,0,1,16,0Zm5.66-58.34-96,96A8,8,0,0,1,128,168H96a8,8,0,0,1-8-8V128a8,8,0,0,1,2.34-5.66l96-96a8,8,0,0,1,11.32,0l32,32A8,8,0,0,1,229.66,69.66Zm-17-5.66L192,43.31,179.31,56,200,76.69Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M228.24,59.76l-32-32a6,6,0,0,0-8.48,0l-96,96A6,6,0,0,0,90,128v32a6,6,0,0,0,6,6h32a6,6,0,0,0,4.24-1.76l96-96A6,6,0,0,0,228.24,59.76ZM125.51,154H102V130.49l66-66L191.51,88ZM200,79.51,176.49,56,192,40.49,215.51,64ZM222,128v80a14,14,0,0,1-14,14H48a14,14,0,0,1-14-14V48A14,14,0,0,1,48,34h80a6,6,0,0,1,0,12H48a2,2,0,0,0-2,2V208a2,2,0,0,0,2,2H208a2,2,0,0,0,2-2V128a6,6,0,0,1,12,0Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M229.66,58.34l-32-32a8,8,0,0,0-11.32,0l-96,96A8,8,0,0,0,88,128v32a8,8,0,0,0,8,8h32a8,8,0,0,0,5.66-2.34l96-96A8,8,0,0,0,229.66,58.34ZM124.69,152H104V131.31l64-64L188.69,88ZM200,76.69,179.31,56,192,43.31,212.69,64ZM224,128v80a16,16,0,0,1-16,16H48a16,16,0,0,1-16-16V48A16,16,0,0,1,48,32h80a8,8,0,0,1,0,16H48V208H208V128a8,8,0,0,1,16,0Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M226.83,61.17l-32-32a4,4,0,0,0-5.66,0l-96,96A4,4,0,0,0,92,128v32a4,4,0,0,0,4,4h32a4,4,0,0,0,2.83-1.17l96-96A4,4,0,0,0,226.83,61.17ZM126.34,156H100V129.66l68-68L194.34,88ZM200,82.34,173.66,56,192,37.66,218.34,64ZM220,128v80a12,12,0,0,1-12,12H48a12,12,0,0,1-12-12V48A12,12,0,0,1,48,36h80a4,4,0,0,1,0,8H48a4,4,0,0,0-4,4V208a4,4,0,0,0,4,4H208a4,4,0,0,0,4-4V128a4,4,0,0,1,8,0Z`}))]]),ur=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M212.48,136.49l-82.06,82a60,60,0,0,1-84.85-84.88l98.16-97.89a40,40,0,0,1,56.56,56.59l-.17.16-95.8,92.22a12,12,0,1,1-16.64-17.3l95.71-92.12a16,16,0,0,0-22.7-22.56L62.53,150.57a36,36,0,0,0,50.93,50.91l82.06-82a12,12,0,0,1,17,17Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M180.75,104.75,204,128l-82.06,81.94a48,48,0,0,1-67.88-67.88L153.37,41.37a32,32,0,0,1,45.26,45.26Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M209.66,122.34a8,8,0,0,1,0,11.32l-82.05,82a56,56,0,0,1-79.2-79.21L147.67,35.73a40,40,0,1,1,56.61,56.55L105,193A24,24,0,1,1,71,159L154.3,74.38A8,8,0,1,1,165.7,85.6L82.39,170.31a8,8,0,1,0,11.27,11.36L192.93,81A24,24,0,1,0,159,47L59.76,147.68a40,40,0,1,0,56.53,56.62l82.06-82A8,8,0,0,1,209.66,122.34Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm37.66,50.34a8,8,0,0,0-11.32,0L87.09,143A24,24,0,1,0,121,177l49.32-50.32a8,8,0,1,1,11.42,11.2l-49.37,50.38a40,40,0,1,1-56.62-56.51L143,63.09A24,24,0,1,1,177,97L109.71,165.6a8,8,0,1,1-11.42-11.2L165.6,85.71a8,8,0,0,0,.06-11.37Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M208.25,123.76a6,6,0,0,1,0,8.49l-82.06,82a54,54,0,0,1-76.36-76.39L149.1,37.14a38,38,0,1,1,53.77,53.72L103.59,191.54a22,22,0,1,1-31.15-31.09l83.28-84.67a6,6,0,0,1,8.56,8.42L81,168.91a10,10,0,1,0,14.11,14.18L194.35,82.4a26,26,0,1,0-36.74-36.8L58.33,146.28a42,42,0,1,0,59.37,59.44l82.06-82A6,6,0,0,1,208.25,123.76Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M209.66,122.34a8,8,0,0,1,0,11.32l-82.05,82a56,56,0,0,1-79.2-79.21L147.67,35.73a40,40,0,1,1,56.61,56.55L105,193A24,24,0,1,1,71,159L154.3,74.38A8,8,0,1,1,165.7,85.6L82.39,170.31a8,8,0,1,0,11.27,11.36L192.93,81A24,24,0,1,0,159,47L59.76,147.68a40,40,0,1,0,56.53,56.62l82.06-82A8,8,0,0,1,209.66,122.34Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M206.83,125.17a4,4,0,0,1,0,5.66l-82.06,82a52,52,0,0,1-73.54-73.55L150.52,38.55a36,36,0,1,1,50.94,50.9l-99.3,100.69a20,20,0,1,1-28.3-28.27l83.29-84.68a4,4,0,1,1,5.7,5.61L79.54,167.5a12,12,0,1,0,16.95,17L195.78,83.81A28,28,0,1,0,156.2,44.18L56.91,144.87a44,44,0,1,0,62.21,62.26l82-82A4,4,0,0,1,206.83,125.17Z`}))]]),dr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M230.14,70.54,185.46,25.85a20,20,0,0,0-28.29,0L33.86,149.17A19.85,19.85,0,0,0,28,163.31V208a20,20,0,0,0,20,20H92.69a19.86,19.86,0,0,0,14.14-5.86L230.14,98.82a20,20,0,0,0,0-28.28ZM91,204H52V165l84-84,39,39ZM192,103,153,64l18.34-18.34,39,39Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M221.66,90.34,192,120,136,64l29.66-29.66a8,8,0,0,1,11.31,0L221.66,79A8,8,0,0,1,221.66,90.34Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M225.9,74.78,181.21,30.09a14,14,0,0,0-19.8,0L38.1,153.41a13.94,13.94,0,0,0-4.1,9.9V208a14,14,0,0,0,14,14H92.69a13.94,13.94,0,0,0,9.9-4.1L225.9,94.58a14,14,0,0,0,0-19.8ZM94.1,209.41a2,2,0,0,1-1.41.59H48a2,2,0,0,1-2-2V163.31a2,2,0,0,1,.59-1.41L136,72.48,183.51,120ZM217.41,86.1,192,111.51,144.49,64,169.9,38.58a2,2,0,0,1,2.83,0l44.68,44.69a2,2,0,0,1,0,2.83Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M224.49,76.2,179.8,31.51a12,12,0,0,0-17,0L133.17,61.17h0L39.52,154.83A11.9,11.9,0,0,0,36,163.31V208a12,12,0,0,0,12,12H92.69a12,12,0,0,0,8.48-3.51L224.48,93.17a12,12,0,0,0,0-17Zm-129,134.63A4,4,0,0,1,92.69,212H48a4,4,0,0,1-4-4V163.31a4,4,0,0,1,1.17-2.83L136,69.65,186.34,120ZM218.83,87.51,192,114.34,141.66,64l26.82-26.83a4,4,0,0,1,5.66,0l44.69,44.68a4,4,0,0,1,0,5.66Z`}))]]),fr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M200,36H56A20,20,0,0,0,36,56V200a20,20,0,0,0,20,20H200a20,20,0,0,0,20-20V56A20,20,0,0,0,200,36Zm-4,160H60V60H196Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M208,56V200a8,8,0,0,1-8,8H56a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H200A8,8,0,0,1,208,56Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,56V200a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V56A16,16,0,0,1,56,40H200A16,16,0,0,1,216,56Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M200,42H56A14,14,0,0,0,42,56V200a14,14,0,0,0,14,14H200a14,14,0,0,0,14-14V56A14,14,0,0,0,200,42Zm2,158a2,2,0,0,1-2,2H56a2,2,0,0,1-2-2V56a2,2,0,0,1,2-2H200a2,2,0,0,1,2,2Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M200,44H56A12,12,0,0,0,44,56V200a12,12,0,0,0,12,12H200a12,12,0,0,0,12-12V56A12,12,0,0,0,200,44Zm4,156a4,4,0,0,1-4,4H56a4,4,0,0,1-4-4V56a4,4,0,0,1,4-4H200a4,4,0,0,1,4,4Z`}))]]),pr=new Map([[`bold`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,48H180V36A28,28,0,0,0,152,8H104A28,28,0,0,0,76,36V48H40a12,12,0,0,0,0,24h4V208a20,20,0,0,0,20,20H192a20,20,0,0,0,20-20V72h4a12,12,0,0,0,0-24ZM100,36a4,4,0,0,1,4-4h48a4,4,0,0,1,4,4V48H100Zm88,168H68V72H188ZM116,104v64a12,12,0,0,1-24,0V104a12,12,0,0,1,24,0Zm48,0v64a12,12,0,0,1-24,0V104a12,12,0,0,1,24,0Z`}))],[`duotone`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M200,56V208a8,8,0,0,1-8,8H64a8,8,0,0,1-8-8V56Z`,opacity:`0.2`}),Y.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z`}))],[`fill`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM112,168a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm0-120H96V40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8Z`}))],[`light`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,50H174V40a22,22,0,0,0-22-22H104A22,22,0,0,0,82,40V50H40a6,6,0,0,0,0,12H50V208a14,14,0,0,0,14,14H192a14,14,0,0,0,14-14V62h10a6,6,0,0,0,0-12ZM94,40a10,10,0,0,1,10-10h48a10,10,0,0,1,10,10V50H94ZM194,208a2,2,0,0,1-2,2H64a2,2,0,0,1-2-2V62H194ZM110,104v64a6,6,0,0,1-12,0V104a6,6,0,0,1,12,0Zm48,0v64a6,6,0,0,1-12,0V104a6,6,0,0,1,12,0Z`}))],[`regular`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z`}))],[`thin`,Y.createElement(Y.Fragment,null,Y.createElement(`path`,{d:`M216,52H172V40a20,20,0,0,0-20-20H104A20,20,0,0,0,84,40V52H40a4,4,0,0,0,0,8H52V208a12,12,0,0,0,12,12H192a12,12,0,0,0,12-12V60h12a4,4,0,0,0,0-8ZM92,40a12,12,0,0,1,12-12h48a12,12,0,0,1,12,12V52H92ZM196,208a4,4,0,0,1-4,4H64a4,4,0,0,1-4-4V60H196ZM108,104v64a4,4,0,0,1-8,0V104a4,4,0,0,1,8,0Zm48,0v64a4,4,0,0,1-8,0V104a4,4,0,0,1,8,0Z`}))]]),mr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:tr}));mr.displayName=`ArrowUpIcon`;const hr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:nr}));hr.displayName=`CaretUpIcon`;const gr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:rr}));gr.displayName=`ClockCounterClockwiseIcon`;const _r=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:ir}));_r.displayName=`CopyIcon`;const vr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:ar}));vr.displayName=`CubeIcon`;const yr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:or}));yr.displayName=`DotsThreeIcon`;const br=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:sr}));br.displayName=`FileCodeIcon`;const xr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:cr}));xr.displayName=`FileCsvIcon`;const Sr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:lr}));Sr.displayName=`NotePencilIcon`;const Cr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:ur}));Cr.displayName=`PaperclipIcon`;const wr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:dr}));wr.displayName=`PencilSimpleIcon`;const Tr=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:fr}));Tr.displayName=`StopIcon`;const Er=Y.forwardRef((e,t)=>Y.createElement(wt,{ref:t,...e,weights:pr}));Er.displayName=`TrashIcon`;var Dr=Je(),X=u();function Or({className:e,size:t=`default`,...n}){return(0,X.jsx)(`div`,{"data-slot":`card`,"data-size":t,className:K(`group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl`,e),...n})}function kr({className:e,...t}){return(0,X.jsx)(`div`,{"data-slot":`card-header`,className:K(`group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)`,e),...t})}function Ar({className:e,...t}){return(0,X.jsx)(`div`,{"data-slot":`card-title`,className:K(`font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm`,e),...t})}function jr({className:e,...t}){return(0,X.jsx)(`div`,{"data-slot":`card-content`,className:K(`px-(--card-spacing)`,e),...t})}function Mr({className:e,...t}){return(0,X.jsx)(`div`,{"data-slot":`card-footer`,className:K(`flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)`,e),...t})}const Nr={reading:`uploading`,ready:`done`,error:`error`};function Pr({attachments:e,onRemove:t}){let n=(0,Y.useRef)(null),r=e.at(-1)?.id;return(0,Y.useEffect)(()=>{let e=n.current;e&&(e.scrollLeft=e.scrollWidth)},[r]),e.length===0?null:(0,X.jsx)(Jt,{ref:n,className:`w-full`,children:e.map(e=>{let n=e.kind===`image`&&e.data!==void 0?Bn(e.mimeType,e.data):void 0;return(0,X.jsxs)(Wt,{size:`sm`,state:Nr[e.status],role:e.status===`error`?`alert`:void 0,children:[(0,X.jsx)(Ot,{variant:n?`image`:`icon`,children:n?(0,X.jsx)(`img`,{src:n,alt:``}):e.status===`reading`?(0,X.jsx)(ct,{}):(0,X.jsx)(Sn,{kind:e.kind,mimeType:e.mimeType})}),(0,X.jsxs)(bt,{children:[(0,X.jsx)(Tt,{children:e.name}),(0,X.jsx)(ln,{children:e.error??a(e.size)})]}),(0,X.jsx)(ft,{children:(0,X.jsx)(jn,{type:`button`,"aria-label":`Remove ${e.name}`,title:`Remove`,onClick:()=>t(e.id),children:(0,X.jsx)(Ut,{})})})]},e.id)})})}function Fr({title:e,actionsSlot:t,draft:n,onDraftChange:r,onSend:i,onStop:a,onRetry:o,retryLabel:s,showError:c,error:l,streamBusy:u,isBusy:d,authPending:f,authError:p,onAuthRetry:m,attachments:h,attachmentLimits:g,onAddFiles:_,onRemoveAttachment:v}){let y=(0,Y.useRef)(null),[b,x]=(0,Y.useState)(!1),S=f||p!==void 0,C=h.some(e=>e.status===`reading`),w=h.some(e=>e.status===`ready`),T=h.filter(e=>e.status!==`error`).length>=g.maxFiles,E=g.enabled&&!S,D=d||S||C||n.trim().length===0&&!w,k=e=>{!E||!e||e.length===0||_([...e])},A=e=>E&&(e?.types.includes(`Files`)??!1);return(0,X.jsxs)(`form`,{className:`w-full`,onSubmit:e=>{e.preventDefault(),i()},onDragOver:e=>{A(e.dataTransfer)&&(e.preventDefault(),x(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||x(!1)},onDrop:e=>{A(e.dataTransfer)&&(e.preventDefault(),x(!1),k(e.dataTransfer.files))},children:[c&&(0,X.jsxs)(`div`,{role:`alert`,className:`mb-2 flex items-center gap-2 rounded-lg border border-destructive/50 px-3 py-2 text-xs text-destructive`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsx)(`div`,{className:`break-words`,children:ue(l)}),Yn(l)&&l.body?.reference&&(0,X.jsxs)(`div`,{className:`mt-0.5 text-muted-foreground`,children:[`Support reference: `,l.body.reference]})]}),o&&(0,X.jsx)($n,{type:`button`,variant:`outline`,size:`sm`,onClick:o,children:s})]}),p&&(0,X.jsxs)(`div`,{role:`alert`,className:`mb-2 flex items-center gap-2 rounded-lg border border-destructive/50 px-3 py-2 text-xs text-destructive`,children:[(0,X.jsx)(`div`,{className:`min-w-0 flex-1`,children:`The assistant could not verify your session.`}),m&&(0,X.jsx)($n,{type:`button`,variant:`outline`,size:`sm`,onClick:m,children:`Retry`})]}),g.enabled&&(0,X.jsx)(`input`,{ref:y,type:`file`,multiple:!0,className:`sr-only`,accept:we(g),onChange:e=>{k(e.currentTarget.files),e.currentTarget.value=``}}),(0,X.jsxs)(j,{className:K(`cursor-text`,b&&`border-ring ring-3 ring-ring/50`),children:[h.length>0&&(0,X.jsx)(je,{align:`block-start`,children:(0,X.jsx)(Pr,{attachments:h,onRemove:v})}),(0,X.jsx)(O,{"aria-label":`Message`,className:`max-h-24 min-h-9`,placeholder:f?`Verifying your session…`:b?`Drop files to attach…`:`Message ${e}…`,disabled:S,value:n,onChange:e=>r(e.currentTarget.value),onPaste:e=>{!E||e.clipboardData.files.length===0||(e.preventDefault(),k(e.clipboardData.files))},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),i())}}),(0,X.jsxs)(je,{align:`block-end`,children:[g.enabled&&(0,X.jsx)(Fe,{type:`button`,size:`icon-sm`,"aria-label":`Attach files`,title:T?`Up to ${g.maxFiles} files per message`:`Attach images, PDFs, documents, spreadsheets, data, or text files`,disabled:S||T,onClick:()=>y.current?.click(),children:(0,X.jsx)(Cr,{})}),t&&(0,X.jsx)(`slot`,{name:t}),u?(0,X.jsxs)(Fe,{type:`button`,variant:`default`,size:`icon-sm`,className:`ml-auto`,onClick:a,children:[(0,X.jsx)(Tr,{}),(0,X.jsx)(`span`,{className:`sr-only`,children:`Stop`})]}):(0,X.jsxs)(Fe,{type:`submit`,variant:`default`,size:`icon-sm`,className:`ml-auto`,disabled:D,children:[(0,X.jsx)(mr,{}),(0,X.jsx)(`span`,{className:`sr-only`,children:`Send`})]})]})]})]})}const Ir=Y.createContext(void 0);function Lr(e){let t=Y.useContext(Ir);if(t===void 0&&!e)throw Error(i(33));return t}const Rr=Y.createContext(void 0);function zr(e){let t=Y.useContext(Rr);if(t===void 0&&!e)throw Error(i(36));return t}const Br=Y.createContext(void 0);function Vr(e=!0){let t=Y.useContext(Br);if(t===void 0&&!e)throw Error(i(25));return t}function Hr(e){let{closeOnClick:t,highlighted:n,id:r,nodeId:i,store:a,typingRef:o,itemRef:s,itemMetadata:c}=e,{events:l}=a.useState(`floatingTreeRoot`),u=a.useState(`open`),d=Vr(!0),f=d!==void 0;return Y.useMemo(()=>({id:r,role:`menuitem`,tabIndex:u&&n?0:-1,onKeyDown(e){e.key===` `&&o?.current&&e.preventDefault()},onMouseMove(e){i&&l.emit(`itemhover`,{nodeId:i,target:e.currentTarget})},onClick(e){t&&l.emit(`close`,{domEvent:e,reason:gt})},onMouseUp(e){if(d){let t=d.initialCursorPointRef.current;if(d.initialCursorPointRef.current=null,f&&t&&Math.abs(e.clientX-t.x)<=1&&Math.abs(e.clientY-t.y)<=1||f&&!F&&e.button===2)return}s.current&&a.context.allowMouseUpTriggerRef.current&&(!f||e.button===2)&&c.type===`regular-item`&&Ue(s.current,e,{detail:1})}}),[t,n,r,l,i,u,a,o,s,d,f,c])}const Ur={type:`regular-item`};function Wr(e){let{closeOnClick:t,disabled:n,highlighted:r,id:i,store:a,typingRef:o=a.context.typingRef,nativeButton:s,itemMetadata:c,nodeId:l}=e,u=Y.useRef(null),{getButtonProps:d,buttonRef:f}=L({disabled:n,focusableWhenDisabled:!0,native:s,composite:!0}),p=Hr({closeOnClick:t,highlighted:r,id:i,nodeId:l,store:a,typingRef:o,itemRef:u,itemMetadata:c}),m=Y.useCallback(e=>ht(p,{onMouseEnter(){c.type===`submenu-trigger`&&c.setActive()}},e,d),[p,d,c]),h=pn(u,f);return Y.useMemo(()=>({getItemProps:m,itemRef:h}),[m,h])}const Gr=Y.forwardRef(function(e,t){let{render:n,className:r,id:i,label:a,nativeButton:o=!1,disabled:s=!1,closeOnClick:c=!0,style:l,...u}=e,d=W({guess:!0,label:a}),f=Lr(!0),p=ie(i),{store:m}=zr(),h=m.useState(`disabled`),g=s||h,_=m.useState(`isActive`,d.index),v=m.useState(`itemProps`),{getItemProps:y,itemRef:b}=Wr({closeOnClick:c,disabled:g,highlighted:_,id:p,store:m,nativeButton:o,nodeId:f?.context.nodeId,itemMetadata:Ur});return Me(`div`,e,{state:{disabled:g,highlighted:_},props:[v,u,y],ref:[b,t,d.ref]})});function Kr(e,t){return t!=null&&!S(t)?0:typeof e==`function`?e():e}function qr(e,t,n){let r=Kr(e,n);return typeof r==`number`?r:r?.[t]}function Jr(e){return typeof e==`function`?e():e}function Yr(e,t){return t||e===`click`||e===`mousedown`}function Xr(e){return e?.includes(`mouse`)&&e!==`mousedown`}function Zr(e){let{popupStore:t,treatPopupAsFloatingElement:n=!1,floatingRootContext:r,floatingId:i,nested:a,onOpenChange:o}=e,s=t.useState(`open`),c=t.useState(`activeTriggerElement`),l=t.useState(n?`popupElement`:`positionerElement`),u=t.context.triggerElements,d=o,f=Y.useRef(null);r===void 0&&f.current===null&&(f.current=new dn({open:s,transitionStatus:void 0,referenceElement:c,floatingElement:l,triggerElements:u,onOpenChange:d,floatingId:i,syncOnly:!0,nested:a}));let p=r??f.current;return t.useSyncedValue(`floatingId`,i),En(()=>{let e={open:s,floatingId:i,referenceElement:c,floatingElement:l};nn(c)&&(e.domReferenceElement=c),p.state.positionReference===p.state.referenceElement&&(e.positionReference=c),p.update(e)},[s,i,c,l,p]),p.context.onOpenChange=d,p.context.nested=a,p}function Qr(){return new dn({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new Pt,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0})}function $r(){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:Qr(),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:k,inactiveTriggerProps:k,popupProps:k}}const ei=e=>e.triggerIdProp??e.activeTriggerId,ti=e=>e.openProp??e.open,ni=e=>(e.popupElement?.id??e.floatingId)||void 0;function ri(e,t){return t!==void 0&&ti(e)&&ei(e)===t}function ii(e,t){return ri(e,t)?!0:t!==void 0&&ti(e)&&ei(e)==null&&e.triggerCount===1}const ai={open:ti,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:ei,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:ni,isTriggerActive:(e,t)=>t!==void 0&&ei(e)===t,isOpenedByTrigger:(e,t)=>ri(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&ei(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>ii(e,t)?ni(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};var oi=Xe();function si(e){return(0,oi.useSyncExternalStore)(Y.useCallback(t=>e===void 0?B:e.subscribeStore(t),[e]),Y.useCallback(()=>e===void 0?void 0:e.store,[e]),()=>e?.serverStore)}const ci=F&&T;function li(e,t={}){let{enabled:n=!0,delay:r}=t,i=`rootStore`in e?e.rootStore:e,{events:a,dataRef:c}=i.context,l=Y.useRef(!1),u=Y.useRef(null),d=Y.useRef(!0),f=kt();Y.useEffect(()=>{let e=i.select(`domReferenceElement`);if(!n)return;let t=Qe(e);function r(){let e=i.select(`domReferenceElement`);!i.select(`open`)&&xn(e)&&e===se(ze(e))&&(l.current=!0)}function a(){d.current=!0}function o(){d.current=!1}return ce(er(t,`blur`,r),ci&&er(t,`keydown`,a,!0),ci&&er(t,`pointerdown`,o,!0))},[i,n]),Y.useEffect(()=>{if(!n)return;function e(e){if(e.reason===`trigger-press`||e.reason===`escape-key`){let e=i.select(`domReferenceElement`);nn(e)&&(u.current=e,l.current=!0)}}return a.on(`openchange`,e),()=>{a.off(`openchange`,e)}},[a,n,i]);let p=Y.useMemo(()=>{function e(){l.current=!1,u.current=null}return{onMouseLeave(){e()},onFocus(t){let n=t.currentTarget;if(l.current){if(u.current===n)return;e()}let a=he(t.nativeEvent);if(nn(a)){if(ci&&!t.relatedTarget){if(!d.current&&!o(a))return}else if(!It(a))return}let s=Bt(t.relatedTarget,i.context.triggerElements),{nativeEvent:c,currentTarget:p}=t,m=typeof r==`function`?r():r;if(i.select(`open`)&&s||m===0||m===void 0){i.setOpen(!0,J(an,c,p));return}f.start(m,()=>{l.current||i.setOpen(!0,J(an,c,p))})},onBlur(t){e();let n=t.relatedTarget,r=t.nativeEvent,a=nn(n)&&n.hasAttribute(s(`focus-guard`))&&n.getAttribute(`data-type`)===`outside`;f.start(0,()=>{let e=i.select(`domReferenceElement`),t=se(ze(e));!n&&t===e||U(c.current.floatingContext?.refs.floating.current,t)||U(e,t)||a||Bt(n??t,i.context.triggerElements)||i.setOpen(!1,J(an,r))})}}},[c,r,i,f]);return Y.useMemo(()=>n?{reference:p,trigger:p}:{},[n,p])}var ui=class e{constructor(){this.pointerType=void 0,this.interactedInside=!1,this.handler=void 0,this.blockMouseMove=!0,this.performedPointerEventsMutation=!1,this.pointerEventsScopeElement=null,this.pointerEventsReferenceElement=null,this.pointerEventsFloatingElement=null,this.restTimeoutPending=!1,this.openChangeTimeout=new Yt,this.restTimeout=new Yt,this.handleCloseOptions=void 0}static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose};const di=new WeakMap;function fi(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&di.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),di.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function pi(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=di.get(n);a&&a!==e&&fi(a),fi(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,di.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function mi(e){let t=e.context.dataRef.current,n=gn(()=>t.hoverInteractionState??ui.create()).current;return t.hoverInteractionState||=n,Et(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function hi(e,t={}){let{enabled:n=!0,closeDelay:r=0,nodeId:i}=t,a=`rootStore`in e?e.rootStore:e,o=a.useState(`open`),s=a.useState(`floatingElement`),c=a.useState(`domReferenceElement`),{dataRef:l}=a.context,u=Ae(),d=Hn(),f=mi(a),p=kt(),m=q(()=>Yr(l.current.openEvent?.type,f.interactedInside)),h=q(()=>Xr(l.current.openEvent?.type)),g=q(()=>{fi(f)});En(()=>{o||(f.pointerType=void 0,f.restTimeoutPending=!1,f.interactedInside=!1,g())},[o,f,g]),Y.useEffect(()=>g,[g]),En(()=>{if(n&&o&&f.handleCloseOptions?.blockPointerEvents&&h()&&nn(c)&&s){let e=c,t=s,n=ze(s),r=u?.nodesRef.current.find(e=>e.id===d)?.context?.elements.floating;r&&(r.style.pointerEvents=``);let i=f.pointerEventsScopeElement===t?null:f.pointerEventsScopeElement,a=r===t?null:r,o=f.handleCloseOptions?.getScope?.()??i??a??e.closest(`[data-rootownerid]`)??n.body;return pi(f,{scopeElement:o,referenceElement:e,floatingElement:t}),()=>{g()}}},[n,o,c,s,f,h,u,d,g]),Y.useEffect(()=>{if(!n)return;function e(){return!!(u&&d&&v(u.nodesRef.current,d).length>0)}function t(e){let t=qr(r,`close`,f.pointerType),n=()=>{a.setOpen(!1,J(Cn,e)),u?.events.emit(`floating.closed`,e)};t?f.openChangeTimeout.start(t,n):(f.openChangeTimeout.clear(),n())}function o(e){let t=he(e);if(!de(t)){f.interactedInside=!1;return}f.interactedInside=t?.closest(`[aria-haspopup]`)!=null}function c(){f.openChangeTimeout.clear(),p.clear(),u?.events.off(`floating.closed`,y),g()}function _(n){if(e()&&u){u.events.on(`floating.closed`,y);return}if(Bt(n.relatedTarget,a.context.triggerElements))return;let r=l.current.floatingContext?.nodeId??i,o=n.relatedTarget;if(!(u&&r&&nn(o)&&v(u.nodesRef.current,r,!1).some(e=>U(e.context?.elements.floating,o)))){if(f.handler){f.handler(n);return}g(),h()&&!m()&&t(n)}}function y(t){!u||!d||e()||p.start(0,()=>{u.events.off(`floating.closed`,y),a.setOpen(!1,J(Cn,t)),u.events.emit(`floating.closed`,t)})}let b=s;return ce(b&&er(b,`mouseenter`,c),b&&er(b,`mouseleave`,_),b&&er(b,`pointerdown`,o,!0),()=>{u?.events.off(`floating.closed`,y)})},[n,s,a,l,r,i,h,m,g,f,u,d,p])}var gi=e(Fn(),1);const _i={current:null};function vi(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=_i,externalTree:l,isActiveTrigger:u=!0,getHandleCloseContext:d,isClosing:f,shouldOpen:p,guardStaleOpen:m=!1}=t,h=`rootStore`in e?e.rootStore:e,{dataRef:g,events:_}=h.context,v=Ae(l),y=mi(h),b=Y.useRef(!1),x=Se(i),C=Se(r),w=Se(o),T=Se(n),E=Se(p),D=Se(f),O=q(()=>Yr(g.current.openEvent?.type,y.interactedInside)),k=q(()=>E.current?.()!==!1),A=q((e,t,n)=>{let r=h.context.triggerElements;if(r.hasElement(t))return!e||!U(e,t);if(!nn(n))return!1;let i=n;return r.hasMatchingElement(e=>U(e,i))&&(!e||!U(e,i))}),j=q(()=>{y.handler&&=(ze(h.select(`domReferenceElement`)).removeEventListener(`mousemove`,y.handler),void 0)}),M=q(()=>{fi(y)});return u&&(y.handleCloseOptions=x.current?.__options),Y.useEffect(()=>j,[j]),Y.useEffect(()=>{if(!n)return;function e(e){e.open?b.current=!1:(b.current=e.reason===Cn,j(),y.openChangeTimeout.clear(),y.restTimeout.clear(),y.blockMouseMove=!0,y.restTimeoutPending=!1)}return _.on(`openchange`,e),()=>{_.off(`openchange`,e)}},[n,_,y,j]),Y.useEffect(()=>{if(!n)return;function e(e,t=!0){let n=qr(C.current,`close`,y.pointerType);n?y.openChangeTimeout.start(n,()=>{h.setOpen(!1,J(Cn,e)),v?.events.emit(`floating.closed`,e)}):t&&(y.openChangeTimeout.clear(),h.setOpen(!1,J(Cn,e)),v?.events.emit(`floating.closed`,e))}let t=c.current??(u?h.select(`domReferenceElement`):null);if(!nn(t))return;function r(e){if(y.openChangeTimeout.clear(),y.blockMouseMove=!1,a&&!S(y.pointerType))return;let t=Jr(w.current),n=qr(C.current,`open`,y.pointerType),r=he(e),i=e.currentTarget??null,o=h.select(`domReferenceElement`),s=i;if(nn(r)&&!h.context.triggerElements.hasElement(r)){for(let e of h.context.triggerElements.elements())if(U(e,r)){s=e;break}}nn(i)&&nn(o)&&!h.context.triggerElements.hasElement(i)&&U(i,o)&&(s=o);let c=s!=null&&A(o,s,r),l=h.select(`open`),u=D.current?.()??h.select(`transitionStatus`)===`ending`,d=!l&&u&&b.current,f=!c&&nn(s)&&nn(o)&&U(o,s)&&d,p=t>0&&!n,m=c&&(l||d)||f,g=!l||c;if(m){k()&&h.setOpen(!0,J(Cn,e,s));return}p||(n?y.openChangeTimeout.start(n,()=>{g&&k()&&h.setOpen(!0,J(Cn,e,s))}):g&&k()&&h.setOpen(!0,J(Cn,e,s)))}function i(t){if(O()){M();return}j();let n=ze(h.select(`domReferenceElement`));y.restTimeout.clear(),y.restTimeoutPending=!1;let r=g.current.floatingContext??d?.();if(!Bt(t.relatedTarget,h.context.triggerElements)){if(x.current&&r){h.select(`open`)||y.openChangeTimeout.clear();let i=c.current;y.handler=x.current({...r,tree:v,x:t.clientX,y:t.clientY,onClose(){M(),j(),T.current&&!O()&&i===h.select(`domReferenceElement`)&&e(t,!0)}}),n.addEventListener(`mousemove`,y.handler),y.handler(t);return}(y.pointerType!==`touch`||!U(h.select(`floatingElement`),t.relatedTarget))&&e(t)}}function o(e){U(t,e.relatedTarget)||(y.openChangeTimeout.clear(),y.restTimeout.clear(),y.restTimeoutPending=!1)}let l=m?er(t,`mouseout`,o):void 0;return s?ce(er(t,`mousemove`,r,{once:!0}),er(t,`mouseenter`,r),er(t,`mouseleave`,i),l):ce(er(t,`mouseenter`,r),er(t,`mouseleave`,i),l)},[j,M,g,C,h,n,x,y,u,A,O,a,s,w,c,v,T,d,D,k,m]),Y.useMemo(()=>{if(!n)return;function e(e){y.pointerType=e.pointerType}return{onPointerDown:e,onPointerEnter:e,onMouseMove(e){let{nativeEvent:t}=e,n=e.currentTarget,r=h.select(`domReferenceElement`),i=h.select(`open`),o=A(r,n,e.target);if(a&&!S(y.pointerType))return;if(i&&o&&y.handleCloseOptions?.blockPointerEvents){let e=h.select(`floatingElement`);if(e){let t=y.handleCloseOptions?.getScope?.()??n.ownerDocument.body;pi(y,{scopeElement:t,referenceElement:n,floatingElement:e})}}let s=Jr(w.current);if(i&&!o||s===0||!o&&y.restTimeoutPending&&e.movementX**2+e.movementY**2<2)return;y.restTimeout.clear();function c(){if(y.restTimeoutPending=!1,O())return;let e=h.select(`open`);!y.blockMouseMove&&(!e||o)&&k()&&h.setOpen(!0,J(Cn,t,n))}y.pointerType===`touch`?gi.flushSync(()=>{c()}):o&&i?c():(y.restTimeoutPending=!0,y.restTimeout.start(s,c))}}},[n,y,O,A,a,h,w,k])}const Z=.5;function yi(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function bi(e,t,n,r,i,a,o,s,c,l){let u=!1;return yi(e,t,n,r,i,a)&&(u=!u),yi(e,t,i,a,o,s)&&(u=!u),yi(e,t,o,s,c,l)&&(u=!u),yi(e,t,c,l,n,r)&&(u=!u),u}function xi(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function Si(e,t,n,r,i,a){return e>=Math.min(n,i)&&e<=Math.max(n,i)&&t>=Math.min(r,a)&&t<=Math.max(r,a)}function Ci(e={}){let{blockPointerEvents:t=!1}=e,n=new Yt,r=({x:e,y:t,placement:r,elements:i,onClose:a,nodeId:o,tree:s})=>{let c=r?.split(`-`)[0],l=!1,u=null,d=null,f=typeof performance<`u`?performance.now():0;function p(e,t){let n=performance.now(),r=n-f;if(u===null||d===null||r===0)return u=e,d=t,f=n,!1;let i=e-u,a=t-d,o=i*i+a*a,s=r*r*.010000000000000002;return u=e,d=t,f=n,o<s}function m(){n.clear(),a()}return function(r){n.clear();let a=i.domReference,u=i.floating;if(!a||!u||c==null||e==null||t==null)return;let{clientX:d,clientY:f}=r,h=he(r),g=r.type===`mouseleave`,_=U(u,h),y=U(a,h);if(_&&(l=!0,!g))return;if(y&&(l=!1,!g)){l=!0;return}if(g&&nn(r.relatedTarget)&&U(u,r.relatedTarget))return;function b(){return!!(s&&v(s.nodesRef.current,o).length>0)}function x(){b()||m()}if(b())return;let S=a.getBoundingClientRect(),C=u.getBoundingClientRect(),w=e>C.right-C.width/2,T=t>C.bottom-C.height/2,E=C.width>S.width,D=C.height>S.height,O=(E?S:C).left,k=(E?S:C).right,A=(D?S:C).top,j=(D?S:C).bottom;if(c===`top`&&t>=S.bottom-1||c===`bottom`&&t<=S.top+1||c===`left`&&e>=S.right-1||c===`right`&&e<=S.left+1){x();return}let M=!1;switch(c){case`top`:M=Si(d,f,O,S.top+1,k,C.bottom-1);break;case`bottom`:M=Si(d,f,O,C.top+1,k,S.bottom-1);break;case`left`:M=Si(d,f,C.right-1,j,S.left+1,A);break;case`right`:M=Si(d,f,S.right-1,j,C.left+1,A);break;default:}if(M)return;if(l&&!xi(d,f,S)){x();return}if(!g&&p(d,f)){x();return}let N=!1;switch(c){case`top`:{let n=E?Z/2:Z*4,r=E||w?e+n:e-n,i=E?e-n:w?e+n:e-n,a=t+Z+1,o=w||E?C.bottom-Z:C.top,s=w?E?C.bottom-Z:C.top:C.bottom-Z;N=bi(d,f,r,a,i,a,C.left,o,C.right,s);break}case`bottom`:{let n=E?Z/2:Z*4,r=E||w?e+n:e-n,i=E?e-n:w?e+n:e-n,a=t-Z,o=w||E?C.top+Z:C.bottom,s=w?E?C.top+Z:C.bottom:C.top+Z;N=bi(d,f,r,a,i,a,C.left,o,C.right,s);break}case`left`:{let n=D?Z/2:Z*4,r=D||T?t+n:t-n,i=D?t-n:T?t+n:t-n,a=e+Z+1,o=T||D?C.right-Z:C.left,s=T?D?C.right-Z:C.left:C.right-Z;N=bi(d,f,o,C.top,s,C.bottom,a,r,a,i);break}case`right`:{let n=D?Z/2:Z*4,r=D||T?t+n:t-n,i=D?t-n:T?t+n:t-n,a=e-Z,o=T||D?C.left+Z:C.right,s=T?D?C.left+Z:C.right:C.left+Z;N=bi(d,f,a,r,a,i,o,C.top,s,C.bottom);break}default:}N?l||n.start(40,x):x()}};return r.__options={...e,blockPointerEvents:t},r}const wi=Y.createContext(void 0);function Ti(e){let t=Y.useContext(wi);if(t===void 0&&!e)throw Error(i(69));return t}const Ei=`ArrowUp`,Di=`ArrowDown`,Oi=`ArrowLeft`,ki=`ArrowRight`,Ai=new Set([Ei,Di,Oi,ki,`Home`,`End`]),ji=[`Shift`,`Control`,`Alt`,`Meta`];function Mi(e){return xn(e)&&e.tagName===`INPUT`}function Ni(e){return!!(Mi(e)&&e.selectionStart!=null||xn(e)&&e.tagName===`TEXTAREA`)}function Pi(e,t,n,r){if(!e||!t||!t.scrollTo)return;let i=e.scrollLeft,a=e.scrollTop,o=e.clientWidth<e.scrollWidth,s=e.clientHeight<e.scrollHeight;if(o&&r!==`vertical`){let r=Fi(e,t,`left`),a=Ii(e),o=Ii(t);n===`ltr`&&(r+t.offsetWidth+o.scrollMarginRight>e.scrollLeft+e.clientWidth-a.scrollPaddingRight?i=r+t.offsetWidth+o.scrollMarginRight-e.clientWidth+a.scrollPaddingRight:r-o.scrollMarginLeft<e.scrollLeft+a.scrollPaddingLeft&&(i=r-o.scrollMarginLeft-a.scrollPaddingLeft)),n===`rtl`&&(r-o.scrollMarginLeft<e.scrollLeft+a.scrollPaddingLeft?i=r-o.scrollMarginLeft-a.scrollPaddingLeft:r+t.offsetWidth+o.scrollMarginRight>e.scrollLeft+e.clientWidth-a.scrollPaddingRight&&(i=r+t.offsetWidth+o.scrollMarginRight-e.clientWidth+a.scrollPaddingRight))}if(s&&r!==`horizontal`){let n=Fi(e,t,`top`),r=Ii(e),i=Ii(t);n-i.scrollMarginTop<e.scrollTop+r.scrollPaddingTop?a=n-i.scrollMarginTop-r.scrollPaddingTop:n+t.offsetHeight+i.scrollMarginBottom>e.scrollTop+e.clientHeight-r.scrollPaddingBottom&&(a=n+t.offsetHeight+i.scrollMarginBottom-e.clientHeight+r.scrollPaddingBottom)}e.scrollTo({left:i,top:a,behavior:`auto`})}function Fi(e,t,n){let r=n===`left`?`offsetLeft`:`offsetTop`,i=0;for(;t.offsetParent&&(i+=t[r],t.offsetParent!==e);)t=t.offsetParent;return i}function Ii(e){let t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}const Li=Y.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,...o}=e,{store:s}=zr(),{side:c,align:l}=Lr(),u=Ti(!0)!=null,d=s.useState(`open`),f=s.useState(`transitionStatus`),p=s.useState(`popupProps`),m=s.useState(`mounted`),h=s.useState(`instantType`),g=s.useState(`activeTriggerElement`),_=s.useState(`parent`),v=s.useState(`lastOpenChangeReason`),y=s.useState(`rootId`),b=s.useState(`floatingRootContext`),x=s.useState(`floatingTreeRoot`),S=s.useState(`closeDelay`),C=s.useState(`hoverEnabled`),w=s.useState(`disabled`),T=s.useState(`openMethod`),E=_.type===`context-menu`;xt({open:d,ref:s.context.popupRef,onComplete(){d&&s.context.onOpenChangeComplete?.(!0)}}),Y.useEffect(()=>{function e(e){s.setOpen(!1,J(e.reason,e.domEvent))}return x.events.on(`close`,e),()=>{x.events.off(`close`,e)}},[x.events,s]),hi(b,{enabled:C&&!w&&!E&&_.type!==`menubar`,closeDelay:S});let D=s.useStateSetter(`popupElement`),O=Me(`div`,e,{state:{transitionStatus:f,side:c,align:l,open:d,nested:_.type===`menu`,instant:h},ref:[t,s.context.popupRef,D],stateAttributesMapping:ge,props:[p,{onKeyDown(e){u&&Ai.has(e.key)&&e.stopPropagation()}},On(f),o,{"data-rootownerid":y}]}),k=_.type===void 0||E;return(g||_.type===`menubar`&&v!==`outside-press`)&&(k=!0),(0,X.jsx)(at,{context:b,openInteractionType:T,modal:E,disabled:!m,returnFocus:a===void 0?k:a,initialFocus:_.type!==`menu`,restoreFocus:!0,externalTree:_.type===`menubar`?void 0:x,previousFocusableElement:g,nextFocusableElement:_.type===void 0?s.context.triggerFocusTargetRef:void 0,beforeContentFocusGuardRef:_.type===void 0?s.context.beforeContentFocusGuardRef:void 0,children:O})}),Ri=Y.createContext(void 0);function zi(){let e=Y.useContext(Ri);if(e===void 0)throw Error(i(32));return e}const Bi=Y.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i}=zr();return i.useState(`mounted`)||n?(0,X.jsx)(Ri.Provider,{value:n,children:(0,X.jsx)(y,{ref:t,...r})}):null}),Vi=Y.forwardRef(function(e,t){let{anchor:n,positionMethod:r=`absolute`,className:i,render:a,side:o,align:s,sideOffset:c=0,alignOffset:l=0,collisionBoundary:u=`clipping-ancestors`,collisionPadding:d=5,arrowPadding:f=5,sticky:p=!1,disableAnchorTracking:m=!1,collisionAvoidance:h=fe,style:g,..._}=e,{store:v}=zr(),y=zi(),b=Vr(!0),x=v.useState(`parent`),S=v.useState(`floatingRootContext`),C=v.useState(`floatingTreeRoot`),w=v.useState(`mounted`),T=v.useState(`open`),E=v.useState(`modal`),D=v.useState(`openMethod`),O=v.useState(`activeTriggerElement`),k=v.useState(`transitionStatus`),A=v.useState(`positionerElement`),j=v.useState(`instantType`),M=v.useState(`adaptiveOrigin`),N=v.useState(`lastOpenChangeReason`),P=v.useState(`floatingNodeId`),F=v.useState(`floatingParentNodeId`),I=S.useState(`domReferenceElement`),te=Y.useRef(null),L=un(A),R=n,z=c,B=l,ne=s,V=h;x.type===`context-menu`&&(R=n??x.context?.anchor,ne??=`start`,!o&&ne!==`center`&&(B=e.alignOffset??2,z=e.sideOffset??-5));let re=o,ie=ne;x.type===`menu`?(re??=`inline-end`,ie??=`start`,V=e.collisionAvoidance??Vt):x.type===`menubar`&&(re??=x.context.orientation===`vertical`?`inline-end`:`bottom`,ie??=`start`);let ae=x.type===`context-menu`,oe=_e({anchor:R,floatingRootContext:S,positionMethod:b?`fixed`:r,mounted:w,side:re,sideOffset:z,align:ie,alignOffset:B,arrowPadding:ae?0:f,collisionBoundary:u,collisionPadding:d,sticky:p,nodeId:P,keepMounted:y,disableAnchorTracking:m,collisionAvoidance:V,shift:ae?{crossAxis:!(`side`in V&&V.side===`flip`),rootBoundary:`layoutViewport`}:void 0,externalTree:C,adaptiveOrigin:M});Y.useEffect(()=>{function e(e){e.open&&(e.parentNodeId===P&&v.set(`hoverEnabled`,!1),e.nodeId!==P&&e.parentNodeId===v.select(`floatingParentNodeId`)&&v.setOpen(!1,J(et)))}return C.events.on(`menuopenchange`,e),()=>{C.events.off(`menuopenchange`,e)}},[v,C.events,P]),Y.useEffect(()=>{if(v.select(`floatingParentNodeId`)==null)return;function e(e){if(e.open||e.nodeId!==v.select(`floatingParentNodeId`))return;let t=e.reason??`sibling-open`;v.setOpen(!1,J(t))}return C.events.on(`menuopenchange`,e),()=>{C.events.off(`menuopenchange`,e)}},[C.events,v]);let H=kt();Y.useEffect(()=>{T||H.clear()},[T,H]),Y.useEffect(()=>{function e(e){if(!(!T||e.nodeId!==v.select(`floatingParentNodeId`)))if(e.target&&O&&O!==e.target){let e=v.select(`closeDelay`);e>0?H.isStarted()||H.start(e,()=>{v.setOpen(!1,J(et))}):v.setOpen(!1,J(et))}else H.clear()}return C.events.on(`itemhover`,e),()=>{C.events.off(`itemhover`,e)}},[C.events,T,O,v,H]),Y.useEffect(()=>{let e={open:T,nodeId:P,parentNodeId:F,reason:v.select(`lastOpenChangeReason`)};C.events.emit(`menuopenchange`,e)},[C.events,T,v,P,F]),En(()=>{let e=I,t=te.current;if(e&&(te.current=e),t&&e&&e!==t){v.set(`instantType`,void 0);let e=new AbortController;return L(()=>{v.set(`instantType`,`trigger-change`)},e.signal),()=>{e.abort()}}},[I,L,v]);let se={open:T,side:oe.side,align:oe.align,anchorHidden:oe.anchorHidden,nested:x.type===`menu`,instant:j},ce=x.type===`menubar`&&x.context.modal;ee(T&&(ce||E&&N!==`trigger-hover`),D===`touch`,A,O);let le=Ve(e,se,{styles:oe.positionerStyles,transitionStatus:k,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!w,inert:!T}),U=w&&x.type!==`menu`&&(x.type!==`menubar`&&E&&N!==`trigger-hover`||x.type===`menubar`&&x.context.modal),W=null;return x.type===`menubar`?W=x.context.contentElement:x.type===void 0&&(W=O),(0,X.jsxs)(Ir.Provider,{value:oe,children:[U&&(0,X.jsx)(Re,{ref:x.type===`context-menu`||x.type===`nested-context-menu`?x.context.internalBackdropRef:null,inert:_t(!T),cutout:W}),(0,X.jsx)(Kn,{id:P,children:(0,X.jsx)(We,{elementsRef:v.context.itemDomElements,labelsRef:v.context.itemLabels,children:le})})]})}),Hi=Y.createContext(null);function Ui(e){let t=Y.useContext(Hi);if(t===null&&!e)throw Error(i(5));return t}const Wi={...ai,disabled:e=>e.parent.type===`menubar`&&e.parent.context.disabled||e.disabled,modal:e=>(e.parent.type===void 0||e.parent.type===`context-menu`)&&(e.modal??!0),openMethod:e=>e.openMethod,allowMouseEnter:e=>e.allowMouseEnter,highlightItemOnHover:e=>e.highlightItemOnHover,parent:e=>e.parent,rootId:e=>e.parent.type===`menu`?e.parent.store.select(`rootId`):e.parent.type===void 0?e.rootId:e.parent.context.rootId,activeIndex:e=>e.activeIndex,isActive:(e,t)=>e.activeIndex===t,hoverEnabled:e=>e.hoverEnabled,instantType:e=>e.instantType,lastOpenChangeReason:e=>e.openChangeReason,floatingTreeRoot:e=>e.parent.type===`menu`?e.parent.store.select(`floatingTreeRoot`):e.floatingTreeRoot,floatingNodeId:e=>e.floatingNodeId,floatingParentNodeId:e=>e.floatingParentNodeId,itemProps:e=>e.itemProps,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin,keyboardEventRelay:e=>{if(e.keyboardEventRelay)return e.keyboardEventRelay;if(e.parent.type===`menu`)return e.parent.store.select(`keyboardEventRelay`)}};var Gi=class extends Xt{constructor(e){super({...qi(),...e},Ki(),Wi),this.unsubscribeParentListener=this.observe(`parent`,e=>{if(this.unsubscribeParentListener?.(),e.type===`menu`){let t=e.store.select(`rootId`),n=e.store.select(`floatingTreeRoot`),r=e.store.select(`keyboardEventRelay`);this.unsubscribeParentListener=e.store.subscribe(()=>{let i=e.store.select(`rootId`),a=e.store.select(`floatingTreeRoot`),o=e.store.select(`keyboardEventRelay`);t===i&&n===a&&r===o||(t=i,n=a,r=o,this.notifyAll())}),this.context.allowMouseUpTriggerRef=e.store.context.allowMouseUpTriggerRef;return}e.type!==void 0&&(this.context.allowMouseUpTriggerRef=e.context.allowMouseUpTriggerRef),this.unsubscribeParentListener=null})}setOpen(e,t){this.state.floatingRootContext.context.events.emit(`setOpen`,{open:e,eventDetails:t})}unsubscribeParentListener=null};function Ki(){return{positionerRef:Y.createRef(),popupRef:Y.createRef(),typingRef:{current:!1},itemDomElements:{current:[]},itemLabels:{current:[]},allowMouseUpTriggerRef:{current:!1},triggerFocusTargetRef:Y.createRef(),beforeContentFocusGuardRef:Y.createRef(),onOpenChangeComplete:void 0,triggerElements:new Pt}}function qi(){return{...$r(),disabled:!1,modal:!0,openMethod:null,allowMouseEnter:!1,highlightItemOnHover:!0,parent:{type:void 0},rootId:void 0,activeIndex:null,hoverEnabled:!0,instantType:void 0,openChangeReason:null,floatingTreeRoot:new C,floatingNodeId:void 0,floatingParentNodeId:null,itemProps:k,keyboardEventRelay:void 0,closeDelay:0,adaptiveOrigin:void 0}}const Ji=Y.createContext(void 0);function Yi(){return Y.useContext(Ji)}const Xi=At(function(e){let{children:t,open:r,onOpenChange:i,onOpenChangeComplete:a,defaultOpen:o=!1,disabled:s=!1,modal:c,loopFocus:l=!0,orientation:u=`vertical`,actionsRef:d,closeParentOnEsc:f=!1,handle:p,triggerId:m,defaultTriggerId:g=null,highlightItemOnHover:_=!0}=e,v=Vr(!0),y=zr(!0),b=Ui(!0),x=Yi(),S=Y.useMemo(()=>x&&y?{type:`menu`,store:y.store}:b?{type:`menubar`,context:b}:v&&!y?{type:`context-menu`,context:v}:{type:void 0},[v,y,b,x]),C=Zi({open:o,openProp:r,activeTriggerId:g,triggerIdProp:m,parent:S});C.useControlledProp(`openProp`,r),C.useControlledProp(`triggerIdProp`,m),C.useContextCallback(`onOpenChangeComplete`,a);let w=xe(),T=xe(),E=C.useState(`floatingTreeRoot`),D=h(E),O=Hn(),A=C.useState(`open`),j=C.useState(`activeTriggerElement`),M=C.useState(`positionerElement`),N=C.useState(`hoverEnabled`),P=C.useState(`disabled`),F=C.useState(`lastOpenChangeReason`),I=C.useState(`parent`),ee=C.useState(`activeIndex`),te=C.useState(`payload`),L=C.useState(`floatingParentNodeId`),R=Y.useRef(null),z=Y.useRef(I.type!==`context-menu`),B=kt(),ne=Y.useRef(!0),V=kt(),re=L!=null,{openMethod:ie,triggerProps:ae}=fn(A);C.useSyncedValues({disabled:s,highlightItemOnHover:_,modal:I.type===void 0?c:void 0,openMethod:ie,rootId:w}),Kt(C);let{forceUnmount:oe}=Nn(A,C,()=>{C.set(`allowMouseEnter`,!1)});En(()=>{v&&!y?C.update({parent:{type:`context-menu`,context:v},floatingNodeId:D,floatingParentNodeId:O}):y&&C.update({floatingNodeId:D,floatingParentNodeId:O})},[v,y,D,O,C]),Y.useEffect(()=>{if(A||(R.current=null),I.type===`context-menu`){if(!A){B.clear(),z.current=!1;return}B.start(500,()=>{z.current=!0})}},[B,A,I.type]),En(()=>{!A&&!N&&C.set(`hoverEnabled`,!0)},[A,N,C]);let H=q((e,t)=>{let n=t.reason;if(!e&&!C.select(`open`)||A===e&&t.trigger===j&&F===n)return;let r=wn(t);if(!e&&t.trigger==null&&(t.trigger=j??void 0),i?.(e,t),t.isCanceled)return;C.state.floatingRootContext.dispatchOpenChange(e,t);let a=t.event;if(e===!1&&a?.type===`click`&&a.pointerType===`touch`&&!ne.current)return;e&&n===`trigger-focus`?(ne.current=!1,V.start(300,()=>{ne.current=!0})):(ne.current=!0,V.clear());let o=(n===`trigger-press`||n===`item-press`)&&a.detail===0,s=!e&&(n===`escape-key`||n==null),c={open:e,openChangeReason:n};R.current=t.event,lt(c,e,t.trigger,r()),C.update(c),I.type===`menubar`&&(n===`trigger-focus`||n===`focus-out`||n===`trigger-hover`||n===`list-navigation`||n===`sibling-open`)?C.set(`instantType`,`group`):o||s?C.set(`instantType`,o?`click`:`dismiss`):C.set(`instantType`,void 0)}),se=Zr({popupStore:C,floatingId:T,nested:O!=null,onOpenChange:H}),ce=se.context.events;En(()=>{let e=({open:e,eventDetails:t})=>H(e,t);return ce.on(`setOpen`,e),()=>{ce?.off(`setOpen`,e)}},[ce,H]);let le=Y.useCallback(()=>{C.setOpen(!1,J(ve))},[C]);Y.useImperativeHandle(d,()=>({unmount:oe,close:le}),[oe,le]);let U;I.type===`context-menu`&&(U=I.context),Y.useImperativeHandle(U?.positionerRef,()=>M,[M]),Y.useImperativeHandle(U?.actionsRef,()=>({setOpen:H}),[H]);let W=Rn(se,{enabled:!P,bubbles:{escapeKey:f&&I.type===`menu`},outsidePress(){return I.type!==`context-menu`||R.current?.type===`contextmenu`||z.current},externalTree:re?E:void 0}),G=n(),ue=Y.useCallback(e=>{C.select(`activeIndex`)!==e&&C.set(`activeIndex`,e)},[C]),de=yn(se,{enabled:!P,listRef:C.context.itemDomElements,activeIndex:ee,nested:I.type!==void 0,loopFocus:l,orientation:u,parentOrientation:I.type===`menubar`?I.context.orientation:void 0,rtl:G===`rtl`,disabledIndices:Ie,onNavigate:ue,openOnArrowKeyDown:I.type!==`context-menu`,externalTree:re?E:void 0,focusItemOnHover:_}),fe=Y.useCallback(e=>{C.context.typingRef.current=e},[C]),pe=en(se,{enabled:!P,listRef:C.context.itemLabels,elementsRef:C.context.itemDomElements,activeIndex:ee,resetMs:500,onMatch:e=>{A&&e!==ee&&C.set(`activeIndex`,e)},onTyping:fe});mt(C,{floatingRootContext:se,activeTriggerProps:Y.useMemo(()=>{let e=ht(pe.reference,de.reference,W.reference,{onMouseMove(){C.set(`allowMouseEnter`,!0)}},ae);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=A,e},[C,pe.reference,de.reference,W.reference,ae,A]),inactiveTriggerProps:Y.useMemo(()=>{let e=ht(de.trigger,W.trigger,ae);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=!1,e},[de.trigger,W.trigger,ae]),popupProps:Y.useMemo(()=>ht(tt,{id:T,role:`menu`,"aria-labelledby":j?.id,onMouseMove(){C.set(`allowMouseEnter`,!0),I.type===`menu`&&C.set(`hoverEnabled`,!1)},onClick(){C.select(`hoverEnabled`)&&C.set(`hoverEnabled`,!1)},onKeyDown(e){let t=C.select(`keyboardEventRelay`);t&&!e.isPropagationStopped()&&t(e)}},pe.floating,de.floating,W.floating),[j,T,I.type,C,pe.floating,de.floating,W.floating]),itemProps:de.item??k});let me=Y.useMemo(()=>({store:C,parent:S}),[C,S]),he=(0,X.jsxs)(Rr.Provider,{value:me,children:[p&&(0,X.jsx)(on,{handle:p,store:C}),typeof t==`function`?t({payload:te}):t]});return I.type===void 0||I.type===`context-menu`?(0,X.jsx)(Ee,{externalTree:E,children:he}):he});function Zi(e){return gn(()=>new Gi(e)).current}function Qi(e={}){let{highlightItemOnHover:t,highlightedIndex:n,onHighlightedIndexChange:r}=ye(),{ref:i,index:a}=W(e),o=n===a,s=Y.useRef(null),c=pn(i,s);return{compositeProps:{tabIndex:o?0:-1,onFocus(){r(a)},onMouseMove(){let e=s.current;if(!t||!e)return;let n=e.hasAttribute(`disabled`)||e.ariaDisabled===`true`;!o&&!n&&e.focus()}},compositeRef:c,index:a}}function $i(e){let{render:t,className:n,style:r,state:i=k,props:a=Ie,refs:o=Ie,metadata:s,stateAttributesMapping:c,tag:l=`div`,...u}=e,{compositeProps:d,compositeRef:f}=Qi({metadata:s});return Me(l,e,{state:i,ref:[f,...o],props:[d,...a,u],stateAttributesMapping:c})}function ea(e){if(xn(e)&&e.hasAttribute(`data-rootownerid`))return e.getAttribute(`data-rootownerid`);if(!st(e))return ea(Mt(e))}function ta(e,t){let n=Y.useRef(null);function r(t){gi.flushSync(()=>{e.setOpen(!1,J(Ge,t.nativeEvent,t.currentTarget))}),Xn(n.current)?.focus()}function i(n){let r=e.select(`positionerElement`);if(r&&it(n,r))e.context.beforeContentFocusGuardRef.current?.focus();else{gi.flushSync(()=>{e.setOpen(!1,J(Ge,n.nativeEvent,n.currentTarget))});let i=Ln(e.context.triggerFocusTargetRef.current||t.current);for(;i!==null&&U(r,i);){let e=i;if(i=Ye(i),i===e)break}i?.focus()}}return{preFocusGuardRef:n,handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}function na(e){let{enabled:t=!0,mouseDownAction:n,open:r}=e,i=Y.useRef(!1);return Y.useMemo(()=>t?{onMouseDown:e=>{(n===`open`&&!r||n===`close`&&r)&&(i.current=!0,ze(e.currentTarget).addEventListener(`click`,()=>{i.current=!1},{once:!0}))},onClick:e=>{i.current&&(i.current=!1,e.preventBaseUIHandler())}}:k,[t,n,r])}const ra=Dt(function(e,t){let{render:n,className:r,style:a,disabled:o=!1,nativeButton:s=!0,id:c,openOnHover:l,delay:u=100,closeDelay:d=0,handle:f,payload:p,...m}=e,g=zr(!0),_=si(f)??g?.store;if(!_)throw Error(i(85));let v=ie(c),y=_.useState(`isTriggerActive`,v),b=_.useState(`floatingRootContext`),x=_.useState(`isOpenedByTrigger`,v),S=_.useState(`triggerPopupId`,v),w=Y.useRef(null),T=aa(),D=ye(!0),O=Ae(),A=Y.useMemo(()=>O??new C,[O]),{registerTrigger:j,isMountedByThisTrigger:M}=St(v,w,_,{payload:p,closeDelay:d,parent:T,floatingTreeRoot:A,floatingNodeId:h(A),floatingParentNodeId:Hn(),keyboardEventRelay:D?.relayKeyboardEvent}),N=T.type===`menubar`,P=_.useState(`disabled`),F=o||P||N&&T.context.disabled,{getButtonProps:I,buttonRef:ee}=L({disabled:F,native:s});Y.useEffect(()=>{!x&&T.type===void 0&&(_.context.allowMouseUpTriggerRef.current=!1)},[_,x,T.type]);let z=Y.useRef(null),B=kt(),ne=q(e=>{if(!z.current)return;B.clear(),_.context.allowMouseUpTriggerRef.current=!1;let t=e.target;U(z.current,t)||U(_.select(`positionerElement`),t)||t===z.current||t!=null&&ea(t)===_.select(`rootId`)||R(e,z.current)||A.events.emit(`close`,{domEvent:e,reason:te})});Y.useEffect(()=>{x&&_.select(`lastOpenChangeReason`)===`trigger-hover`&&ze(z.current).addEventListener(`mouseup`,ne,{once:!0})},[x,ne,_]);let V=N&&T.context.hasSubmenuOpen,re=vi(b,{enabled:(l??V)&&!F&&(!N||V&&!M),handleClose:Ci({blockPointerEvents:!N}),mouseOnly:!0,move:!1,restMs:T.type===void 0?u:void 0,delay:{close:d},triggerElementRef:w,externalTree:A,isActiveTrigger:y,isClosing:()=>_.select(`transitionStatus`)===`ending`}),ae=ia(x,_.select(`lastOpenChangeReason`)),oe=Zn(b,{enabled:!F,event:x&&N?`click`:`mousedown`,toggle:!0,ignoreMouse:!1,stickIfOpen:T.type===void 0&&ae}),H=li(b,{enabled:!F&&V}),se=na({open:x,enabled:N,mouseDownAction:`open`}),ce=Y.useMemo(()=>ht(H.reference,oe.reference),[H.reference,oe.reference]),le=_.useState(`triggerProps`,M),{preFocusGuardRef:W,handlePreFocusGuardFocus:G,handleFocusTargetFocus:ue}=ta(_,w),de={disabled:F,open:x},fe=[z,t,ee,j,w],pe=[ce,re??k,le,{"aria-haspopup":`menu`,"aria-controls":S,id:v,onMouseDown:e=>{_.select(`open`)||(B.start(200,()=>{_.context.allowMouseUpTriggerRef.current=!0}),ze(e.currentTarget).addEventListener(`mouseup`,ne,{once:!0}))}},N?{role:`menuitem`}:{},se,m,I],me=Me(`button`,e,{enabled:!N,stateAttributesMapping:E,state:de,ref:fe,props:pe});return N?(0,X.jsx)($i,{tag:`button`,render:n,className:r,style:a,state:de,refs:fe,props:pe,stateAttributesMapping:E}):x?(0,X.jsxs)(Y.Fragment,{children:[(0,X.jsx)(Lt,{ref:W,onFocus:G},`${v}-pre-focus-guard`),(0,X.jsx)(Y.Fragment,{children:me},v),(0,X.jsx)(Lt,{ref:_.context.triggerFocusTargetRef,onFocus:ue},`${v}-post-focus-guard`)]}):(0,X.jsx)(Y.Fragment,{children:me},v)});function ia(e,t){let n=kt(),[r,i]=Y.useState(!1);return En(()=>{e&&t===`trigger-hover`?(i(!0),n.start(500,()=>{i(!1)})):e||(n.clear(),i(!1))},[e,t,n]),r}function aa(){let e=Ui(!0);return Y.useMemo(()=>e?{type:`menubar`,context:e}:{type:void 0},[e])}const oa=Y.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return Me(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})});function sa(e){return e==null||e.hasAttribute(`disabled`)||e.getAttribute(`aria-disabled`)===`true`}function ca({...e}){return(0,X.jsx)(Xi,{"data-slot":`dropdown-menu`,...e})}function la({...e}){return(0,X.jsx)(ra,{"data-slot":`dropdown-menu-trigger`,...e})}function ua({align:e=`start`,alignOffset:t=0,side:n=`bottom`,sideOffset:r=4,className:i,container:a,...o}){return(0,X.jsx)(Bi,{container:a,children:(0,X.jsx)(Vi,{className:`isolate z-50 outline-none`,align:e,alignOffset:t,side:n,sideOffset:r,children:(0,X.jsx)(Li,{"data-slot":`dropdown-menu-content`,className:K(`z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-start-2 data-[side=inline-start]:slide-in-from-end-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95`,i),...o})})})}function da({className:e,inset:t,variant:n=`default`,...r}){return(0,X.jsx)(Gr,{"data-slot":`dropdown-menu-item`,"data-inset":t,"data-variant":n,className:K(`group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:ps-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive`,e),...r})}function fa({className:e,...t}){return(0,X.jsx)(oa,{"data-slot":`dropdown-menu-separator`,className:K(`-mx-1 my-1 h-px bg-border`,e),...t})}function pa({chat:e,state:t,thread:n,onDelete:r}){let i=(0,Y.useRef)(null),a=(0,Y.useRef)(null),[o,s]=(0,Y.useState)(!1),[c,l]=(0,Y.useState)(``),[u,d]=(0,Y.useState)(!1),[f,p]=(0,Y.useState)(!1),m=n.title??``,h=n.role===`manager`&&t.status!==`submitted`&&t.status!==`streaming`;return(0,Y.useEffect)(()=>{o&&requestAnimationFrame(()=>a.current?.select())},[o]),(0,Y.useEffect)(()=>{if(!f)return;let e=setTimeout(()=>p(!1),2e3);return()=>clearTimeout(e)},[f]),(0,X.jsx)(`div`,{ref:i,"data-slot":`conversation-title`,className:`flex h-10 shrink-0 items-center gap-1 border-b px-4`,children:o?(0,X.jsxs)(`form`,{className:`flex min-w-0 flex-1 gap-1`,onSubmit:t=>{t.preventDefault(),c.trim()&&(d(!0),e.renameThread(c.trim()).then(e=>{d(!1),e&&s(!1)}))},children:[(0,X.jsx)(z,{ref:a,"aria-label":`Conversation title`,className:`h-7`,value:c,maxLength:200,disabled:u,onChange:e=>l(e.currentTarget.value),onKeyDown:e=>{e.key===`Escape`&&s(!1)}}),(0,X.jsx)($n,{type:`submit`,size:`sm`,disabled:!c.trim()||u,children:u?`Saving…`:`Save`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,title:m,children:m}),f&&(0,X.jsx)(`span`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Copied`}),(0,X.jsxs)(ca,{children:[(0,X.jsx)(la,{"aria-label":`Conversation actions`,title:`Conversation actions`,render:(0,X.jsx)($n,{variant:`ghost`,size:`icon-sm`}),children:(0,X.jsx)(yr,{})}),(0,X.jsxs)(ua,{container:i,align:`end`,className:`w-40`,children:[(0,X.jsxs)(da,{disabled:!h,onClick:()=>{l(n.title??``),s(!0)},children:[(0,X.jsx)(wr,{}),`Rename`]}),(0,X.jsxs)(da,{disabled:t.messages.length===0,onClick:()=>{navigator.clipboard.writeText(me(m,t.messages)).then(()=>p(!0))},children:[(0,X.jsx)(_r,{}),`Copy Markdown`]}),(0,X.jsx)(fa,{}),(0,X.jsxs)(da,{variant:`destructive`,disabled:!h,onClick:()=>{e.deleteThread().then(e=>{e&&r(n.id)})},children:[(0,X.jsx)(Er,{}),`Delete`]})]})]})]})})}const ma=[];function ha(e){let{loopFocus:t=!0,orientation:n=`both`,grid:r,onLoop:i,direction:a,highlightedIndex:o,onHighlightedIndexChange:s,rootRef:c,enableHomeAndEndKeys:l=!1,stopEventPropagation:u,disabledIndices:d,modifierKeys:f=ma}=e,[p,h]=Y.useState(0),g=r!=null,_=Y.useRef(null),v=pn(_,c),y=Y.useRef([]),b=Y.useRef(!1),x=o??p,S=q((e,t=!1)=>{if((s??h)(e),t){let t=y.current[e];Pi(_.current,t,a,n)}}),C=q(e=>{if(e.size===0||b.current)return;b.current=!0;let t=Array.from(e.keys()),r=t.find(e=>e?.hasAttribute(`data-composite-item-active`))??null,i=r?e.get(r)?.index??-1:-1;if(i!==-1)S(i);else if(ke(t,x,d)){let e=Gn(t,{disabledIndices:d});Vn(t,e)||S(e)}Pi(_.current,r,a,n)});En(()=>{if(d==null||o!=null||!b.current)return;let e=y.current;if(ke(e,x,d)){let t=Gn(e,{disabledIndices:d});Vn(e,t)||S(t)}},[d,o,x,y,S]);let w=q((e,t,n)=>i?i(e,t,n,y):n),T=q(e=>{let o=e.key===`Home`||e.key===`End`;if(!Ai.has(e.key)||!l&&o||ga(e,f)||!_.current)return;let s=a===`rtl`,c=s?Oi:ki,p=s?ki:Oi,h=n===`vertical`?Di:c,v=n===`vertical`?Ei:p,b=he(e.nativeEvent);if(b!=null&&Ni(b)&&!sa(b)){let t=b.selectionStart,n=b.selectionEnd,r=b.value;if(t==null||e.shiftKey||t!==n||e.key!==v&&t<r.length||e.key!==h&&t>0)return}let C=x,T=m(y,d),E=Te(y,d);r!=null&&(C=r({disabledIndices:d,elementsRef:y,event:e,highlightedIndex:x,loopFocus:t,maxIndex:E,minIndex:T,onLoop:w,orientation:n,rtl:s}));let D=n!==`vertical`&&e.key===c||n!==`horizontal`&&e.key===`ArrowDown`,O=n!==`vertical`&&e.key===p||n!==`horizontal`&&e.key===`ArrowUp`;l&&(e.key===`Home`?C=T:e.key===`End`&&(C=E)),C===x&&(D||O)&&(t&&C===E&&D?(C=T,i&&(C=i(e,x,C,y))):t&&C===T&&O?(C=E,i&&(C=i(e,x,C,y))):C=Gn(y.current,{startingIndex:C,decrement:O,disabledIndices:d})),C!==x&&!Vn(y.current,C)&&(u&&e.stopPropagation(),(g||o||D||O)&&e.preventDefault(),S(C,!0),queueMicrotask(()=>{y.current[C]?.focus()}))});return{props:{ref:v,onFocus(e){let t=_.current,n=he(e.nativeEvent);!t||n==null||!Ni(n)||n.setSelectionRange(0,n.value.length)},onKeyDown:T},highlightedIndex:x,onHighlightedIndexChange:S,elementsRef:y,onMapChange:C,relayKeyboardEvent:T}}function ga(e,t){for(let n of ji)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}function _a(e){let{render:t,className:r,style:i,refs:a=Ie,props:o=Ie,state:s=k,stateAttributesMapping:c,highlightedIndex:l,onHighlightedIndexChange:u,orientation:d,grid:f,loopFocus:p,onLoop:m,enableHomeAndEndKeys:h,onMapChange:g,stopEventPropagation:_=!0,rootRef:v,disabledIndices:y,modifierKeys:b,highlightItemOnHover:x=!1,tag:S=`div`,...C}=e,{props:w,highlightedIndex:T,onHighlightedIndexChange:E,elementsRef:D,onMapChange:O,relayKeyboardEvent:A}=ha({grid:f,loopFocus:p,onLoop:m,orientation:d,highlightedIndex:l,onHighlightedIndexChange:u,rootRef:v,stopEventPropagation:_,enableHomeAndEndKeys:h,direction:n(),disabledIndices:y,modifierKeys:b}),j=Me(S,e,{state:s,ref:a,props:[w,...o,C],stateAttributesMapping:c}),M=Y.useMemo(()=>({highlightedIndex:T,onHighlightedIndexChange:E,highlightItemOnHover:x,relayKeyboardEvent:A}),[T,E,x,A]);return(0,X.jsx)(Ke.Provider,{value:M,children:(0,X.jsx)(We,{elementsRef:D,onMapChange:e=>{g?.(e),O(e)},children:j})})}const va=Y.createContext(void 0);function ya(){let e=Y.useContext(va);if(e===void 0)throw Error(i(64));return e}const ba={tabActivationDirection:e=>({"data-activation-direction":e})},xa=Y.forwardRef(function(e,t){let{className:n,defaultValue:i=0,onValueChange:a,orientation:o=`horizontal`,render:s,value:c,style:l,...u}=e,d=e.defaultValue!==void 0,f=Y.useRef([]),[p,m]=Y.useState(()=>new Map),[h,g]=Gt({controlled:c,default:i,name:`Tabs`,state:`value`}),_=c!==void 0,[v,y]=Y.useState(()=>new Map),b=Y.useRef(void 0),x=Y.useCallback(e=>Sa(v,e),[v]),[S,C]=Y.useState(()=>({previousValue:h,tabActivationDirection:`none`})),{previousValue:w,tabActivationDirection:T}=S,E=T,D=!1;w!==h&&(E=Ca(w,h,o,v),D=w!=null&&h!=null&&x(h)==null);let O=D?w:h,k=w!==O||T!==E;En(()=>{k&&C({previousValue:O,tabActivationDirection:E})},[O,k,E]);let A=q((e,t)=>{t.activationDirection=Ca(h,e,o,v),a?.(e,t),!t.isCanceled&&g(e)}),j=q((e,t)=>{a?.(e,J(t,void 0,void 0,{activationDirection:`none`}))}),M=q((e,t)=>(m(n=>{let r=new Map(n);return r.set(e,t),r}),()=>{m(n=>{if(n.get(e)!==t)return n;let r=new Map(n);return r.delete(e),r})})),N=Y.useCallback(e=>p.get(e),[p]),P=Y.useCallback(e=>{for(let t of v.values())if(e===t.value)return t.id},[v]),F=Y.useMemo(()=>({getTabElementBySelectedValue:x,getTabIdByPanelValue:P,getTabPanelIdByValue:N,onValueChange:A,orientation:o,registerMountedTabPanel:M,setTabMap:y,tabActivationDirection:E,value:h}),[x,P,N,A,o,M,y,E,h]),I=Y.useMemo(()=>{for(let e of v.values())if(e.value===h)return e},[v,h]),ee=Y.useMemo(()=>{for(let e of v.values())if(!e.disabled)return e.value},[v]),te=Y.useRef(!d),L=Y.useRef(i),R=Y.useRef(d),z=Y.useRef(!1);En(()=>{if(_)return;function e(e,t){g(e),C({previousValue:e,tabActivationDirection:`none`}),j(e,t),te.current=!1}if(v.size===0){z.current&&h!==null&&!b.current?.isConnected&&e(null,$t);return}z.current=!0,b.current=v.keys().next().value;let t=I?.disabled,n=I==null&&h!==null;if(!t&&h===L.current&&(R.current=!1),R.current&&t&&h===L.current)return;let i=te.current;if(t||n){let n=ee??null;if(h===n){te.current=!1;return}let a=$t;i?a=r:t&&(a=He),e(n,a);return}i&&I!=null&&(j(h,r),te.current=!1)},[ee,_,j,I,g,v,h]);let B=Me(`div`,e,{state:{orientation:o,tabActivationDirection:E},ref:t,props:u,stateAttributesMapping:ba});return(0,X.jsx)(va.Provider,{value:F,children:(0,X.jsx)(We,{elementsRef:f,children:B})})});function Sa(e,t){for(let[n,r]of e.entries())if(t===r.value)return n;return null}function Ca(e,t,n,r){if(e==null||t==null)return`none`;let[i,a,o]=n===`horizontal`?[`left`,`left`,`right`]:[`top`,`up`,`down`],s=Sa(r,e),c=Sa(r,t);if(s==null||c==null)return s!==c&&(typeof e==`number`||typeof e==`string`)&&typeof e==typeof t?t>e?o:a:`none`;let l=s.getBoundingClientRect()[i],u=c.getBoundingClientRect()[i];return u<l?a:u>l?o:`none`}const wa=Y.createContext(void 0);function Ta(){let e=Y.useContext(wa);if(e===void 0)throw Error(i(65));return e}const Ea=Y.forwardRef(function(e,t){let{className:n,disabled:r=!1,render:i,value:a,id:o,nativeButton:s=!0,style:c,...l}=e,{value:u,getTabPanelIdByValue:d,onValueChange:f,orientation:p,tabActivationDirection:m}=ya(),{activateOnFocus:h,registerTabResizeObserverElement:g,tabsListElement:_}=Ta(),{highlightedIndex:v,onHighlightedIndexChange:y}=ye(),b=ie(o),{compositeProps:x,compositeRef:S,index:C}=Qi({metadata:Y.useMemo(()=>({disabled:r,id:b,value:a}),[r,b,a])}),w=a===u,T=Y.useRef(!1),E=Y.useRef(null),D=q(e=>{E.current?.(),E.current=e?g(e):null});En(()=>{if(T.current){T.current=!1;return}if(!(w&&C>-1&&v!==C))return;let e=_;if(e!=null){let t=se(ze(e));if(t&&U(e,t))return}r||y(C)},[w,C,v,y,r,_]);let{getButtonProps:O,buttonRef:k}=L({disabled:r,native:s,focusableWhenDisabled:!0}),A=d(a),j=Y.useRef(!1),M=Y.useRef(!1);function N(e){f(a,J(vn,e.nativeEvent,void 0,{activationDirection:`none`}))}function P(e){w||r||N(e)}function F(e){w||r||h&&(!j.current||M.current)&&N(e)}function I(e){if(w||r)return;j.current=!0,M.current=e.button===0;let t=ze(e.currentTarget);function n(){j.current=!1,M.current=!1,t.removeEventListener(`pointerup`,n),t.removeEventListener(`pointercancel`,n)}t.addEventListener(`pointerup`,n),t.addEventListener(`pointercancel`,n)}return Me(`button`,e,{state:{disabled:r,active:w,orientation:p,tabActivationDirection:m},ref:[t,k,S,D],props:[x,{role:`tab`,"aria-controls":A,"aria-selected":w,id:b,onClick:P,onFocus:F,onPointerDown:I,"data-composite-item-active":w?``:void 0,onKeyDownCapture(){T.current=!0}},l,O],stateAttributesMapping:ba})}),Da={...ba,...pt},Oa=Y.forwardRef(function(e,t){let{className:n,value:r,render:i,keepMounted:a=!1,style:o,...s}=e,{value:c,getTabIdByPanelValue:l,orientation:u,tabActivationDirection:d,registerMountedTabPanel:f}=ya(),p=ie(),{ref:m,index:h}=W(),g=r===c,{mounted:_,transitionStatus:v,setMounted:y}=Mn(g),b=!_,x=l(r),S={hidden:b,orientation:u,tabActivationDirection:d,transitionStatus:v},C=Y.useRef(null),w=Me(`div`,e,{state:S,ref:[t,m,C],props:[{"aria-labelledby":x,hidden:b,id:p,role:`tabpanel`,tabIndex:g?0:-1,inert:_t(!g),"data-index":h},s],stateAttributesMapping:Da});return xt({open:g,ref:C,onComplete(){g||y(!1)}}),En(()=>{if(!(p==null||b&&!a))return f(r,p)},[b,a,r,p,f]),a||_?w:null}),ka=Y.forwardRef(function(e,t){let{activateOnFocus:n=!1,className:r,loopFocus:i=!0,render:a,style:o,...s}=e,{orientation:c,setTabMap:l,tabActivationDirection:u}=ya(),[d,f]=Y.useState(0),[p,m]=Y.useState(null),h=Y.useRef(new Set),g=Y.useRef(new Set),_=Y.useRef(null);En(()=>{if(typeof ResizeObserver>`u`)return;let e=new ResizeObserver(()=>{h.current.forEach(e=>{e()})});return _.current=e,p&&e.observe(p),g.current.forEach(t=>{e.observe(t)}),()=>{e.disconnect(),_.current=null}},[p]);let v=q(e=>(h.current.add(e),()=>{h.current.delete(e)})),y=q(e=>(g.current.add(e),_.current?.observe(e),()=>{g.current.delete(e),_.current?.unobserve(e)})),b={orientation:c,tabActivationDirection:u},x={"aria-orientation":c===`vertical`?`vertical`:void 0,role:`tablist`},S=Y.useMemo(()=>({activateOnFocus:n,registerIndicatorUpdateListener:v,registerTabResizeObserverElement:y,tabsListElement:p}),[n,v,y,p]);return(0,X.jsx)(wa.Provider,{value:S,children:(0,X.jsx)(_a,{render:a,className:r,style:o,state:b,refs:[t,m],props:[x,s],stateAttributesMapping:ba,highlightedIndex:d,enableHomeAndEndKeys:!0,loopFocus:i,orientation:c,onHighlightedIndexChange:f,onMapChange:l,disabledIndices:Ie})})});function Aa(e,t){let n=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),r=Math.round((n(t)-n(new Date(e)))/864e5);return r<=0?`Today`:r===1?`Yesterday`:r<7?`Previous 7 days`:r<30?`Previous 30 days`:`Older`}function ja(e){let t=new Date,n=[];for(let r of e){let e=Aa(r.updatedAt,t),i=n.at(-1);i?.value===e?i.items.push(r):n.push({value:e,items:[r]})}return n}const Ma=e=>e.title||`Untitled`,Na=e=>e.stopPropagation();function Pa({chat:e,state:t,onSelect:n,onDelete:r}){let i=(0,Y.useRef)(null),a=(0,Y.useRef)(null),[o,s]=(0,Y.useState)(``),[l,u]=(0,Y.useState)(!1),[d,p]=(0,Y.useState)(0),[m]=c(o.trim(),{wait:300}),h=(0,Y.useContext)(V),[_]=(0,Y.useState)(()=>new pe),v=oe({queryKey:[`thread-history`,(0,Y.useId)(),d,m],enabled:l,initialPageParam:void 0,queryFn:({signal:t,pageParam:n})=>e.searchThreads(m,n,t),getNextPageParam:e=>e.page_after??void 0,retry:!1,gcTime:0},h??_),y=o.trim()!==m||v.isPending,{hasNextPage:x,isFetching:S,isError:C,fetchNextPage:w}=v;(0,Y.useEffect)(()=>{let e=a.current;if(!l||!e||y||!x||S||C)return;let t=()=>{e.scrollHeight-e.scrollTop-e.clientHeight<48&&w({cancelRefetch:!1})};return t(),e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[l,y,x,S,C,w,v.data]);let T=y?[]:ja(v.data?.pages.flatMap(e=>e.items)??[]),E=t.thread?.id,O=t.status===`submitted`||t.status===`streaming`,k=t=>{e.deleteThread(t).then(e=>{e&&(r(t.id),v.refetch())})};return(0,X.jsx)(`div`,{ref:i,"data-slot":`thread-history`,children:(0,X.jsxs)(nt,{items:T,filteredItems:T,value:null,onValueChange:t=>{!t||t.id===E||e.openThread(t.id).then(n)},itemToStringLabel:Ma,itemToStringValue:e=>e.id,isItemEqualToValue:(e,t)=>e.id===t.id,onInputValueChange:(e,t)=>{s(t.reason===`input-change`?e:``)},onOpenChange:e=>{u(e),e?p(e=>e+1):s(``)},children:[(0,X.jsx)(D,{"aria-label":`Show older chats`,title:`Show older chats`,render:(0,X.jsx)($n,{variant:`ghost`,size:`icon-sm`}),children:(0,X.jsx)(gr,{})}),(0,X.jsxs)(Ce,{container:i,align:`end`,"aria-label":`Chat history`,"aria-busy":y||v.isFetching?!0:void 0,className:`w-80 min-w-0`,children:[(0,X.jsx)(De,{"aria-label":`Search chats`,placeholder:`Search chats…`,maxLength:255,showTrigger:!1}),(0,X.jsx)(Rt,{className:`text-center text-sm text-muted-foreground [&:not(:empty)]:py-2`,children:y||v.isFetchingNextPage?`Loading…`:null}),(0,X.jsx)(f,{children:!y&&!v.isError?`No chats found.`:null}),(0,X.jsx)(G,{ref:a,className:`max-h-[min(24rem,calc(var(--available-height)---spacing(9)))]`,children:e=>(0,X.jsxs)(zn,{items:e.items,children:[(0,X.jsx)(g,{children:e.value}),(0,X.jsx)(Un,{children:e=>{let t=e.id===E;return(0,X.jsxs)(b,{value:e,"aria-label":Ma(e),"aria-current":t?`true`:void 0,className:K(`group/thread ps-2 pe-1`,t&&`bg-muted font-semibold`),children:[(0,X.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:Ma(e)}),e.role===`manager`&&(0,X.jsx)($n,{variant:`ghost`,size:`icon-xs`,"aria-label":`Delete ${Ma(e)}`,title:`Delete`,disabled:t&&O,className:`opacity-0 group-hover/thread:opacity-100 group-data-highlighted/thread:opacity-100 focus-visible:opacity-100`,onPointerDown:Na,onMouseDown:Na,onClick:t=>{t.stopPropagation(),k(e)},children:(0,X.jsx)(Er,{})})]},e.id)}})]},e.value)}),!y&&v.isError&&(0,X.jsxs)(`div`,{className:`p-2 text-xs`,role:`alert`,children:[`Could not load chats.`,(0,X.jsx)($n,{variant:`ghost`,size:`sm`,disabled:v.isFetching,onClick:()=>void(v.isFetchNextPageError?v.fetchNextPage():v.refetch()),children:`Retry`})]})]})]})})}function Fa({className:e,orientation:t=`horizontal`,...n}){return(0,X.jsx)(xa,{"data-slot":`tabs`,"data-orientation":t,className:K(`group/tabs flex gap-2 data-horizontal:flex-col`,e),...n})}const Ia=M(`group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none`,{variants:{variant:{default:`bg-muted`,line:`gap-1 bg-transparent`}},defaultVariants:{variant:`default`}});function La({className:e,variant:t=`default`,...n}){return(0,X.jsx)(ka,{"data-slot":`tabs-list`,"data-variant":t,className:K(Ia({variant:t}),e),...n})}function Ra({className:e,...t}){return(0,X.jsx)(Ea,{"data-slot":`tabs-trigger`,className:K(`relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pe-1 has-data-[icon=inline-start]:ps-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,`group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent`,`data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground`,`after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-end-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100`,e),...t})}function za({className:e,...t}){return(0,X.jsx)(Oa,{"data-slot":`tabs-content`,className:K(`flex-1 text-sm outline-none`,e),...t})}const Ba=new Set([`c`,`cpp`,`css`,`go`,`html`,`js`,`json`,`jsx`,`mjs`,`py`,`rb`,`rs`,`sh`,`sql`,`toml`,`ts`,`tsx`,`yaml`,`yml`]);function Va(e){let t=e.slice(e.lastIndexOf(`.`)+1).toLowerCase();return Ba.has(t)?(0,X.jsx)(br,{}):t===`csv`||t===`tsv`?(0,X.jsx)(xr,{}):(0,X.jsx)(yt,{})}function Ha(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function Ua({file:e}){return(0,X.jsxs)(`div`,{className:`flex items-start gap-1`,children:[(0,X.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,X.jsx)(ae,{icon:Va(e.path),label:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`span`,{className:`font-mono wrap-anywhere`,children:e.label}),(0,X.jsxs)(`span`,{className:`text-muted-foreground`,children:[` · `,e.lines===1?`1 line`:`${e.lines} lines`]})]}),children:(0,X.jsx)(`div`,{className:`mt-1 flex min-w-0 flex-col`,children:(0,X.jsx)(Pe,{emptyLabel:`Empty file`,caption:e.label===e.path?void 0:e.path,children:e.content})})})}),(0,X.jsx)($n,{variant:`ghost`,size:`icon-sm`,"aria-label":`Download ${e.label}`,title:`Download`,onClick:()=>zt(Ha(e.path),e.content),children:(0,X.jsx)(cn,{})})]})}function Wa({run:e}){let t=e.timedOut||e.exitCode!==void 0&&e.exitCode!==0;return(0,X.jsx)(ae,{icon:(0,X.jsx)(dt,{}),running:!e.finished,label:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`span`,{className:`font-mono wrap-anywhere`,children:e.command}),e.finished&&(0,X.jsx)(`span`,{className:K(`ms-1`,t?`text-destructive`:`text-muted-foreground`),children:_n(e)})]}),children:(0,X.jsx)(`div`,{className:`mt-1 flex min-w-0 flex-col`,children:(0,X.jsx)(d,{run:e})})})}function Ga({activity:e}){let[t,n]=(0,Y.useState)(!1),r=e.files.length,i=e.commands.length;return(0,X.jsxs)(`div`,{className:`relative w-full`,children:[t&&(0,X.jsx)(`div`,{className:`absolute inset-x-0 bottom-full z-10 mb-2 flex max-h-80 flex-col overflow-hidden rounded-lg border bg-background shadow-lg`,children:(0,X.jsxs)(Fa,{defaultValue:`files`,className:`flex min-h-0 flex-col gap-0`,children:[(0,X.jsxs)(La,{variant:`line`,className:`w-full shrink-0 px-2`,children:[(0,X.jsxs)(Ra,{value:`files`,children:[(0,X.jsx)(yt,{}),`Files`,r>0&&(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:r})]}),(0,X.jsxs)(Ra,{value:`log`,children:[(0,X.jsx)(dt,{}),`Log`,i>0&&(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:i})]})]}),(0,X.jsx)(za,{value:`files`,className:`min-h-0 overflow-y-auto p-2`,children:r===0?(0,X.jsx)(Ka,{children:`The agent has not written any files yet.`}):e.files.map(e=>(0,X.jsx)(Ua,{file:e},e.toolCallId))}),(0,X.jsx)(za,{value:`log`,className:`min-h-0 overflow-y-auto p-2`,children:i===0?(0,X.jsx)(Ka,{children:`The agent has not run any commands yet.`}):e.commands.map(e=>(0,X.jsx)(Wa,{run:e},e.toolCallId))})]})}),(0,X.jsxs)(`button`,{type:`button`,"aria-expanded":t,onClick:()=>n(e=>!e),className:`flex w-full cursor-pointer items-center gap-2 rounded-full border bg-muted/50 px-3 py-1.5 text-start text-xs text-muted-foreground hover:text-foreground [&_svg:not([class*='size-'])]:size-4`,children:[(0,X.jsx)(vr,{}),(0,X.jsxs)(`span`,{className:`flex-1`,children:[`Sandbox · `,r,` `,r===1?`file`:`files`,` · `,i,` `,i===1?`command`:`commands`]}),(0,X.jsx)(hr,{className:K(`shrink-0 transition-transform`,t&&`rotate-180`)})]})]})}function Ka({children:e}){return(0,X.jsx)(`p`,{className:`px-1 py-2 text-xs text-muted-foreground italic`,children:e})}function qa({status:e}){if(e===`ready`)return null;let t=e===`starting`;return(0,X.jsxs)(Nt,{role:`status`,className:`w-full rounded-full border bg-muted/50 px-3 py-1.5`,children:[(0,X.jsx)(rn,{children:t?(0,X.jsx)(ct,{}):(0,X.jsx)(An,{})}),(0,X.jsx)($e,{className:t?`shimmer`:void 0,children:t?`Starting the sandbox…`:`The sandbox could not be started`})]})}function Ja(e,t,n,r){if(!t)return``;let i=`astralbeam:draft:${JSON.stringify([e.replace(/\/+$/,``),t,n])}`;try{if(r===void 0)return globalThis.localStorage?.getItem(i)??``;r?globalThis.localStorage?.setItem(i,r):globalThis.localStorage?.removeItem(i)}catch{}return``}function Ya(e){if(e)return{onChunk:Za(e),onResponse:t=>e(`run`,t?`endpoint responded with HTTP ${t.status}`:`request sent`),onFinish:t=>e(`run`,`assistant turn finished`,t),onError:t=>e(`error`,t.message,t)}}function Xa(e){try{return JSON.parse(e)}catch{return e}}function Za(e){let t=new Map,n=new Map,r=(e,n)=>{t.set(e,(t.get(e)??``)+n)},i=e=>{let n=t.get(e)??``;return t.delete(e),n};return t=>{let a=t;switch(a.type){case`TEXT_MESSAGE_CONTENT`:case`TEXT_MESSAGE_CHUNK`:r(a.messageId??`text`,a.delta??``);break;case`TEXT_MESSAGE_END`:e(`text`,i(a.messageId??`text`),{messageId:a.messageId});break;case`REASONING_MESSAGE_CONTENT`:case`REASONING_MESSAGE_CHUNK`:case`THINKING_TEXT_MESSAGE_CONTENT`:r(`reasoning:${a.messageId??`thinking`}`,a.delta??``);break;case`REASONING_MESSAGE_END`:case`THINKING_TEXT_MESSAGE_END`:e(`reasoning`,i(`reasoning:${a.messageId??`thinking`}`),{messageId:a.messageId});break;case`TOOL_CALL_START`:e(`tool`,`${a.toolCallName} call started`,t),n.set(a.toolCallId??``,{name:a.toolCallName??``,args:``});break;case`TOOL_CALL_ARGS`:{let e=n.get(a.toolCallId??``);e&&(e.args+=a.delta??``);break}case`TOOL_CALL_END`:{let t=n.get(a.toolCallId??``);n.delete(a.toolCallId??``),e(`tool`,`${t?.name??`tool`} input complete`,{toolCallId:a.toolCallId,input:Xa(t?.args??``)});break}case`TOOL_CALL_RESULT`:e(`tool`,`result for tool call ${a.toolCallId}`,{toolCallId:a.toolCallId,messageId:a.messageId,content:Xa(a.content??``)});break;case`TEXT_MESSAGE_START`:case`REASONING_MESSAGE_START`:case`THINKING_TEXT_MESSAGE_START`:break;case`RUN_STARTED`:e(`run`,`run ${a.runId} started`,t);break;case`RUN_FINISHED`:e(`run`,`run ${a.runId} finished`,t);break;case`RUN_ERROR`:e(`error`,`run failed: ${a.message}`,t);break;default:e(`stream`,a.type,t)}}}var Qa=class extends Error{missingFeature;constructor(e){super($a(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function $a(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function eo(e){if(!e.body)throw new Qa(`Response.body`);if(typeof e.body.getReader!=`function`)throw new Qa(`Response.body.getReader`);return e.body.getReader()}function to(){if(typeof globalThis.TextDecoder!=`function`)throw new Qa(`TextDecoder`);return new globalThis.TextDecoder}function no(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function ro(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!=`string`)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function io(e){let t=ro(e.createdAt),n=e.parts.map(e=>{if(e.type!==`tool-result`)return e;let t=ro(e.createdAt),{createdAt:n,...r}=e;return t?{...r,createdAt:t}:r}),{createdAt:r,...i}=e;return t?{...i,parts:n,createdAt:t}:{...i,parts:n}}function ao(e){return e.map(io)}function oo(e){return Object.keys(e).length>0?e:void 0}function so(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function co(e,t){return so(e)?e:lo(Array.isArray(e)?e:void 0,t)}function lo(e,t){let n=e?.reduce((e,t)=>{for(let n of[`inputTokens`,`outputTokens`,`totalTokens`,`cachedInputTokens`,`cacheWriteInputTokens`,`reasoningTokens`])t[n]!==void 0&&(e[n]=(e[n]??0)+t[n]);return e},{});if((e===void 0||e.length===0)&&t==null)return;let{promptTokensDetails:r,completionTokensDetails:i,...a}=t??{},o=oo({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...n?.cacheWriteInputTokens===void 0?{}:{cacheWriteTokens:n.cacheWriteInputTokens},...r}),s=oo({...n?.reasoningTokens===void 0?{}:{reasoningTokens:n.reasoningTokens},...i});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...a,...o===void 0?{}:{promptTokensDetails:o},...s===void 0?{}:{completionTokensDetails:s}}}function uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fo(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return uo(e.tanstack)&&uo(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function Q(e){if(e==null)return;let t=`metadata`in e?e.metadata:void 0,n=(typeof t==`object`&&t&&!Array.isArray(t)?t:e).tanstack;if(!(typeof n!=`object`||!n||Array.isArray(n)))return n}function po(e,t){let n=e.metadata,r=Q(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}let mo=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e.SUBAGENT_STARTED=`SUBAGENT_STARTED`,e.SUBAGENT_FINISHED=`SUBAGENT_FINISHED`,e.SUBAGENT_ERROR=`SUBAGENT_ERROR`,e}({});var ho=`redacted_thinking-`;function go(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var _o=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function vo(e,t){return e>>>t|e<<32-t}function yo(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=vo(t,7)^vo(t,18)^t>>>3,i=vo(n,17)^vo(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=vo(a,6)^vo(a,11)^vo(a,25),s=a&g^~a&_,c=v+o+s+(_o[e]??0)+(h[e]??0)>>>0,l=(vo(t,2)^vo(t,13)^vo(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function bo(e){return`sha256:${yo(e)}`}function xo(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(xo(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${xo(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function So(e){return xo(e,new WeakSet)}function Co(e,t=bo){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function wo(e){typeof e!=`object`||!e||Object.isFrozen(e)||(Object.values(e).forEach(wo),Object.freeze(e))}function $(e){let t=JSON.parse(So(e));return wo(t),t}function To(e){let t=$([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=So(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:Co(n)})}function Eo(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function Do(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function Oo(e){if(!Do(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function ko(e){return Do(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function Ao(e){return Object.keys(e).length>0?e:void 0}function jo(e){if(Array.isArray(e)){let t=e.map(e=>Mo(e,e.required||[])),n=t.map(e=>e.nullWidening??{});return{schema:t.map(e=>e.schema),itemMap:n.some(e=>Object.keys(e).length>0)?n:void 0}}let t=Mo(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function Mo(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=Mo(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=jo(r.items);e[n]={...r,items:t.schema,...i?{type:[`array`,`null`]}:{}},o=i,s=t.itemMap?{items:t.itemMap}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=jo(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:Ao(r)}}function No(e,t=`input`){if(Oo(e)){let n=Eo(e[`~standard`].jsonSchema[t]({target:`draft-07`}));return`properties`in n&&!n.type&&(n.type=`object`),n.type===`object`&&!(`properties`in n)&&(n.properties={}),n.type===`object`&&!(`required`in n)&&(n.required=[]),n}if(ko(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?Eo(e):e}function Po(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!Oo(e)&&!ko(e))return e;let i=No(e,r);return!i||typeof i!=`object`||!n?i:Mo(i,i.required||[]).schema}async function Fo(e,t){if(!ko(e))return{success:!0,data:t};let n=await e[`~standard`].validate(t);return n.issues?{success:!1,issues:n.issues.map(e=>({message:e.message||`Validation failed`,path:e.path?.map(String)}))}:{success:!0,data:n.value}}var Io=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function Lo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Ro(e){return Lo(e)&&Object.keys(e).some(e=>Io.has(e))}function zo(e){return ko(e)||Oo(e)||Ro(e)}function Bo(e){if(!Lo(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>zo(e[t]))}function Vo(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Ho(e){if(ko(e)){let t=Oo(e)?Vo(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Ro(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Uo(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function Wo(e,t){let n=t===void 0?null:Ho(t),r=null,i=null;if(e!==void 0)if(ko(e)||Ro(e))r=Ho(e),i=r;else if(Bo(e))r=e.approve===void 0?null:Ho(e.approve),i=e.reject===void 0?null:Ho(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`);let a={oneOf:[Uo({approved:!0,payload:r,inputSchema:n}),Uo({approved:!1,payload:i,inputSchema:null})]},o=So(a),s=So({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:Co(o),approvalSchemaHash:Co(s)}}function Go(e){return Co(e===void 0?`undefined`:So(Ho(e).jsonSchema??{standardValidator:`unserialized`}))}var Ko=`tanstack:interruptBinding`,qo=Ko;function Jo(e){return e&&typeof e==`object`?e:null}function Yo(e,t){return typeof e[t]==`string`?e[t]:void 0}function Xo(e){let t=e.v;return t===void 0||t===1}function Zo(e){let t=Jo(e.metadata),n=t?Jo(t[qo]):null;if(!n||Yo(n,`interruptId`)!==e.id||!Xo(n))return;let r=Yo(n,`kind`),i=Yo(n,`interruptId`),a=Yo(n,`responseSchemaHash`),o=Yo(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=Yo(n,`definitionId`),t=Yo(n,`key`),s=n.batchIndex,c=Yo(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=Yo(n,`toolName`),c=Yo(n,`toolCallId`);if(!(!s||!c)){if(r===`client-tool-execution`){let e=Yo(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=Yo(n,`inputSchemaHash`),t=Yo(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Qo(e){let t=Zo(e);if(!t)return;let n=Jo(e.metadata),r=n?Jo(n[qo]):null;if(!r)return;let i=Yo(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var $o=`tanstack:interruptPayload`;function es(e,t){if(!Oo(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:So(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function ts(e){return Co(es(e,`Interrupt schema`).canonicalJson)}var ns=`tanstack:interruptContinuation`;function rs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function is(e){return{[ns]:e}}function as(e){let t=Zo(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=rs(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[$o]}:{}}}function os(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function ss(e){return os(e)!==null}function cs(e,t){return e?.startsWith(`${t}-segment-`)===!0}var ls=new Set([`text`,`image`,`audio`,`video`,`document`]);function us(e){return e===`cancelled`||e===`denied`}function ds(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!ls.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`file`?r.value.length>0&&(r.provider===void 0||typeof r.provider==`string`):r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function fs(e){return Array.isArray(e)&&e.length>0&&e.every(ds)}function ps(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function ms(e){return typeof e==`string`||fs(e)?e:JSON.stringify(e)}function hs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gs(e){if(!hs(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function _s(e){if(!hs(e)||!hs(e.metadata))return;let t=e.metadata.tanstack;if(!hs(t)||!hs(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!vs(r))return;let{description:o,parentSubagentRunId:s,parentToolCallId:c,metadata:l,placeholder:u}=t.subagent;return{name:n,status:r,...typeof o==`string`&&{description:o},...hs(i)&&typeof i.message==`string`&&{error:{message:i.message,...typeof i.code==`string`&&{code:i.code}}},...Array.isArray(a)&&{interruptIds:a.filter(e=>typeof e==`string`)},...typeof s==`string`&&{parentSubagentRunId:s},...typeof c==`string`&&{parentToolCallId:c},...hs(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function vs(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function ys(e){if(!hs(e))return e;let{subagentRunId:t,...n}=e,r=hs(n.metadata)?n.metadata:void 0,i=hs(r?.tanstack)?r.tanstack:void 0;if(!r||!i||!(`subagent`in i))return n;let{subagent:a,...o}=i;return{...n,metadata:{...r,tanstack:o}}}function bs(e){let t=new Map;for(let n of e){let e=gs(n);e!==void 0&&!t.has(e)&&t.set(e,_s(n)?.parentSubagentRunId)}let n=e=>{let n=e;for(let e=0;e<64;e++){let e=t.get(n);if(e===void 0||!t.has(e))return n;n=e}return n},r=[],i=new Map;for(let t of e){let e=gs(t);if(e===void 0){r.push(t);continue}let a=n(e),o=i.get(a);if(o||(o={id:a,info:{name:`subagent`,status:`finished`},messages:[],hostIndex:r.length-1},i.set(a,o)),e!==a){o.messages.push(t);continue}let s=_s(t);s&&(o.info=s),s?.placeholder||o.messages.push(ys(t))}return{top:r,groups:[...i.values()]}}function xs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ss(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function Cs(e){try{return JSON.stringify(e)??``}catch{return``}}function ws(e){return typeof e==`string`&&e!==``?e:void 0}function Ts(e){if(`encryptedValue`in e){let t=ws(e.encryptedValue);if(t!==void 0)return t}return ws(Q(e)?.signature)}function Es(e){return`id`in e&&go(e.id)?{redacted:!0}:{}}function Ds(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function Os(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function ks(e){let t=[];for(let n of e)if(n.type===`text`&&n.content!==``)t.push(n.content);else if(n.type===`structured-output`&&n.status===`complete`&&n.raw!==``)t.push(n.raw);else if(n.type===`subagent`){let e=As(n);e!==``&&t.push(e)}return t.join(`
2
-
3
- `)}function As(e){let t=[];for(let n of e.subagent.messages){if(!(`parts`in n))continue;let e=ks(n.parts).trim();e!==``&&t.push(e)}return t.length===0?``:`${e.subagent.name}:\n${t.join(`
4
-
5
- `)}`}function js(e){return Array.isArray(e)?e:Os(e)}function Ms(e){if(!(`role`in e)||e.role!==`tool`)return e;let t=e,n=Q(t)?.toolResult;if(!xs(n)||`content`in n&&!fs(n.content))return e;let r={...e};if(`id`in n||Reflect.deleteProperty(r,`id`),`createdAt`in n||Reflect.deleteProperty(r,`createdAt`),typeof n.id==`string`&&Reflect.set(r,`id`,n.id),typeof n.createdAt==`string`){let e=Ns(n.createdAt);e&&Reflect.set(r,`createdAt`,e)}fs(n.content)&&Reflect.set(r,`content`,n.content);let i=Reflect.get(t,`metadata`);if(xs(i)){let e=i.tanstack;if(xs(e)){let{toolResult:t,...n}=e,a={...i};Object.keys(n).length?a.tanstack=n:delete a.tanstack,Object.keys(a).length?Reflect.set(r,`metadata`,a):Reflect.deleteProperty(r,`metadata`)}}return r}function Ns(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!=`string`)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function Ps(e){if(e.type!==`tool-result`)return e;let t=Ns(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function Fs(e){return Ns(Q(e)?.createdAt)}function Is(e){let t=Ns(e.createdAt);return t===void 0?{}:{createdAt:t}}function Ls(e){return e.name===void 0?{}:{name:e.name}}function Rs(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`type`in e)||e.type!==`ui-resource`||!(`toolCallId`in e)||typeof e.toolCallId!=`string`||!(`toolName`in e)||typeof e.toolName!=`string`||!(`resource`in e)||e.resource==null||typeof e.resource!=`object`||Array.isArray(e.resource))return!1;let t=e.resource;return`uri`in t&&typeof t.uri==`string`&&`mimeType`in t&&typeof t.mimeType==`string`}function zs(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Bs(e,t){if(t.length===0)return e;let n=new Set(e.parts.filter(Rs).map(e=>zs(e))),r=t.filter(e=>!n.has(zs(e)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function Vs(e){let t=e.parts.filter(Rs),n=e.metadata??{},r=Q(e),i={};r?.model!==void 0&&(i.model=r.model),r?.runId!==void 0&&(i.runId=r.runId),r?.run?.id!==void 0&&(i.run={id:r.run.id}),r?.signature!==void 0&&(i.signature=r.signature),t.length>0&&(i.uiResources=t);let a={...n};return Object.keys(i).length>0?a.tanstack=i:delete a.tanstack,Object.keys(a).length>0?a:void 0}function Hs(e){return e.role===`system`?[]:e.role===`assistant`?Ks(e):[Us(e)]}function Us(e){let t=[];for(let n of e.parts)Ss(n)&&t.push(n);return{id:e.id,role:e.role,content:Ds(t),...Ls(e),...Is(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Ws(){return{contentParts:[],toolCalls:[]}}function Gs(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function Ks(e){let t=[],n=Ws(),r=[],i=new Set,a={id:e.id,...Ls(e),...Is(e)},o=Vs(e),s={...a,...o!==void 0&&{metadata:o}};function c(e=!1){let i=Ds(n.contentParts),a=i!==null,o=n.toolCalls.length>0,c=r.length>0;(e||a||o||c)&&(t.push({...s,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...c&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput}}),r=[]),n=Ws()}for(let a of e.parts)switch(a.type){case`text`:case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(a);break;case`tool-call`:Gs(a)&&n.toolCalls.push({id:a.id,type:`function`,function:{name:a.name,arguments:a.arguments},...a.metadata!==void 0&&{metadata:a.metadata}});break;case`tool-result`:if(c(t.length===0),(a.state===`complete`||a.state===`error`)&&!i.has(a.toolCallId)){let e=a.outcome===void 0?a.metadata:po(a,{toolResultOutcome:a.outcome}).metadata;t.push({...a.id!==void 0&&{id:a.id},...Is(a),role:`tool`,content:a.content,toolCallId:a.toolCallId,...a.name!==void 0&&{name:a.name},...e!==void 0&&{metadata:e},...a.error!==void 0&&{error:a.error}}),i.add(a.toolCallId)}break;case`thinking`:(a.content||a.signature)&&(n.toolCalls.some(ss)&&c(),r.push({content:a.content,...a.signature&&{signature:a.signature},...a.redacted&&{redacted:!0}}));break;case`structured-output`:if(a.status===`complete`){let e=a.raw===``?a.data===void 0?``:Cs(a.data):a.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=a)}break;case`ui-resource`:break;case`subagent`:{let e=a.subagent.parentToolCallId===void 0?As(a):``;if(e!==``){let t=n.contentParts.length>0?`
6
-
7
- `:``;n.contentParts.push({type:`text`,content:`${t}${e}`})}break}}c();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({role:`tool`,content:ms(n.output),toolCallId:n.id}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let e=n.approval.approved;t.push({role:`tool`,content:JSON.stringify({approved:e,...e&&{pendingExecution:!0},message:e?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e===!1&&{metadata:{tanstack:{toolResultOutcome:`denied`}}}}),i.add(n.id)}return t.length===0&&t.push({...s,role:`assistant`,content:null}),t}function qs(e,t){let n=[],r=Ns(e.createdAt);if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)!t.content&&!t.signature||n.push({type:`thinking`,content:t.content,...t.signature&&{signature:t.signature},...t.redacted&&{redacted:!0}});let i=e.structuredOutput??Xs(Q(e)?.structuredOutput);if(e.role===`assistant`&&i){if(typeof e.content==`string`&&e.content&&e.content!==i.raw){let t=i.raw,r=t!==``&&e.content.endsWith(t)?e.content.slice(0,-t.length):e.content;r&&n.push({type:`text`,content:r})}n.push(i)}else if(e.role===`tool`&&e.toolCallId){let t=Q(e)?.toolResultOutcome,i=us(t)?t:void 0,a=e.error===void 0&&i===void 0?`complete`:`error`;n.push({type:`tool-result`,toolCallId:e.toolCallId,content:js(e.content),state:a,...i!==void 0&&{outcome:i},...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...r!==void 0&&{createdAt:r},...e.error!==void 0&&{error:e.error}})}else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=Os(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls){let e;try{e=JSON.parse(t.function.arguments)}catch{e=void 0}n.push({type:`tool-call`,id:t.id,name:t.function.name,arguments:t.function.arguments,state:`input-complete`,...e!==void 0&&{input:e},...t.metadata!==void 0&&{metadata:t.metadata}})}let a={id:t||ec(),role:e.role===`tool`?`assistant`:e.role,parts:n,...Ls(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},o=Q(e)?.uiResources;return Bs(a,Array.isArray(o)?o.filter(Rs):[])}function Js(e){if(`parts`in e)return Ys(e,{...e,id:e.id||ec()});let t=e.id||ec();switch(e.role){case`user`:return Ys(e,{id:t,role:`user`,parts:Zs(e.content)});case`assistant`:{let n=Q(e),r=n?.toolCallMetadata,i=Xs(n?.structuredOutput),a=e.toolCalls?.map(e=>{let t=typeof r==`object`&&r?r[e.id]:void 0;return t===void 0?e:{...e,metadata:t}});return Ys(e,qs({role:`assistant`,content:e.content??null,...Ls(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=Ms(e);let n=Ns(`createdAt`in e?e.createdAt:void 0)??Fs(e);return Ys(e,qs({role:`tool`,content:fs(e.content)?e.content:Qs(e.content),toolCallId:e.toolCallId,...`name`in e&&typeof e.name==`string`?{name:e.name}:{},...`id`in e&&typeof e.id==`string`?{id:e.id}:{},...`metadata`in e&&e.metadata!=null?{metadata:e.metadata}:{},...n===void 0?{}:{createdAt:n},...e.error!==void 0&&{error:e.error}},t))}case`system`:case`developer`:return Ys(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=Ts(e),r=typeof e.content==`string`?e.content:``;return Ys(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n},...Es(e)}]:[]})}default:return Ys(e,{id:t,role:`assistant`,parts:[]})}}function Ys(e,t){let n=t.parts.map(e=>Ps(e));n!==t.parts&&(t={...t,parts:n});let r=`name`in e&&typeof e.name==`string`?e.name:void 0,i=r===void 0?t:{...t,name:r},a;if(`metadata`in e){let t=e.metadata;typeof t==`object`&&t&&!Array.isArray(t)&&(a=t,i={...i,metadata:a})}let o=Ns(i.createdAt)??(a===void 0?void 0:Fs(a));if(o!==void 0&&!Object.is(o,i.createdAt))i={...i,createdAt:o};else if(o===void 0&&i.createdAt!==void 0){let{createdAt:e,...t}=i;i=t}let s=Q(a)?.uiResources,c=Array.isArray(s)?s.filter(Rs):[];return Bs(i,c)}function Xs(e){if(!(e==null||e.status!==`streaming`&&e.status!==`complete`&&e.status!==`error`||typeof e.raw!=`string`))return{type:`structured-output`,status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage}}}function Zs(e){let t=Qs(e);return typeof t==`string`?t?[{type:`text`,content:t}]:[]:t}function Qs(e){return typeof e==`string`?e:e.map(e=>{if(e.type!==`text`)return e;let{text:t,...n}=e;return{...n,content:t}})}function $s(e,t){if(`parts`in e){let n=e.parts.map(e=>Ps(e));return{...e,parts:n,id:e.id||t(),createdAt:Ns(e.createdAt)??new Date}}else return{...qs(e,t()),createdAt:Ns(e.createdAt)??new Date}}function ec(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function tc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nc(e,t,n,r,i=!1,a){let o=tc(e)?e:{},s=tc(o.tanstack)?{...o.tanstack}:{};i&&delete s.uiResources;let c=Ns(t),l={...n===void 0?{}:{id:n},...c&&{createdAt:c.toISOString()},...Array.isArray(r)&&{content:r}},u={...o,tanstack:{...s,...a!==void 0&&{toolResultOutcome:a},toolResult:l}};return Object.keys(u).length?u:void 0}function rc(e,t){let n=[],r=new Set(e.flatMap(e=>`id`in e&&e.id&&e.role!==`tool`?[e.id]:[])),i=t?.includeSnapshotStructuredOutput??!1,a=new Set;for(let t of e)t.role===`assistant`&&t.id!==void 0&&a.add(t.id);for(let o of e){if(!(`parts`in o)&&o.role===`tool`&&o.toolCallId){let e=gc(vc(o.id,o.toolCallId,a),r),t=nc(o.metadata,o.createdAt,o.id,o.content);n.push({role:`tool`,id:e,...o.name!==void 0&&{name:o.name},toolCallId:o.toolCallId,content:typeof o.content==`string`?o.content:JSON.stringify(o.content),...o.error!==void 0&&{error:o.error},...t!==void 0&&{metadata:t}});continue}let e=`parts`in o?o:qs(o,o.id),s=e.parts;if(r.add(e.id),o.role===`system`){n.push(ic(e,`system`,{content:s.length>0?cc(s):o.content??``},s,i));continue}if(o.role===`user`){n.push(ic(e,`user`,{content:s.length>0?dc(s):o.content??``},s,i));continue}let c={thinking:[],parts:[]},l=[c];for(let e of s)e.type===`thinking`?c.parts.some(e=>e.type===`tool-call`&&ss(e))?(c={thinking:[e],parts:[]},l.push(c)):c.thinking.push(e):c.parts.push(e);l.forEach((t,a)=>{for(let i of t.thinking){let t={role:`reasoning`,id:_c(mc(e.id,i),r),content:i.content};i.signature&&(t.encryptedValue=i.signature),n.push(t)}let o=cc(t.parts),s=pc(t.parts),c=a===0?e:{...e,id:_c(`${e.id}-segment-${a}`,r)};n.push(ic(c,`assistant`,{...o!==``&&{content:o},...s&&{toolCalls:s}},t.parts,i))});let u=new Set(s.flatMap(e=>e.type===`tool-result`?[e.toolCallId]:[]));for(let e of s)if(e.type===`tool-result`){let t=gc(e.id??hc(e.toolCallId),r),i=nc(e.metadata,e.createdAt,e.id,e.content,!0,e.outcome);n.push({role:`tool`,id:t,toolCallId:e.toolCallId,...e.name!==void 0&&{name:e.name},content:typeof e.content==`string`?e.content:JSON.stringify(e.content),...e.error!==void 0&&{error:e.error},...i!==void 0&&{metadata:i}})}else if(e.type===`tool-call`){let t=e.approval?.approved;if(u.has(e.id)||e.output===void 0&&(e.state!==`approval-responded`||t===void 0))continue;let i=e.output===void 0?JSON.stringify({approved:t,...t&&{pendingExecution:!0},message:t?`User approved this action`:`User denied this action`}):ms(e.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:gc(hc(e.id),r),toolCallId:e.id,content:a,metadata:nc(void 0,void 0,void 0,i,!1,e.approval?.approved===!1?`denied`:void 0)})}for(let e of s)e.type===`subagent`&&n.push(...lc(e,t))}return n}function ic(e,t,n,r,i){let a=ac(e,r,i),o={id:e.id,...e.name!==void 0&&{name:e.name},...a!==void 0&&{metadata:a}};return t===`system`?{...o,role:t,content:String(n.content??``)}:t===`user`?{...o,role:t,content:n.content??``}:{...o,role:t,...typeof n.content==`string`&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function ac(e,t,n){let r={...e.metadata??{}},i=Q(e),a={};i?.model!==void 0&&(a.model=i.model),i?.runId!==void 0&&(a.runId=i.runId),i?.run?.id!==void 0&&(a.run={id:i.run.id}),i?.signature!==void 0&&(a.signature=i.signature);let o=Ns(e.createdAt);o!==void 0&&(a.createdAt=o.toISOString());let s=oc(t,n);s&&(a.structuredOutput=s);let c={};for(let e of t)e.type===`tool-call`&&e.metadata!==void 0&&(c[e.id]=e.metadata);Object.keys(c).length>0&&(a.toolCallMetadata=c);let l=t.filter(e=>e.type===`ui-resource`);return l.length>0&&(a.uiResources=l),Object.keys(a).length>0?r.tanstack=a:delete r.tanstack,Object.keys(r).length>0?r:void 0}function oc(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return sc(n,t)}function sc(e,t){return{status:e.status,raw:e.raw,...t&&e.partial!==void 0?{partial:e.partial}:{},...t&&e.data!==void 0?{data:e.data}:{},...t&&e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function cc(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function lc(e,t){let{subagent:n}=e,r={name:n.name,status:n.status,...n.description!==void 0&&{description:n.description},...n.error!==void 0&&{error:n.error},...n.interruptIds!==void 0&&{interruptIds:n.interruptIds},...n.parentSubagentRunId!==void 0&&{parentSubagentRunId:n.parentSubagentRunId},...n.parentToolCallId!==void 0&&{parentToolCallId:n.parentToolCallId},...n.metadata!==void 0&&{metadata:n.metadata}},i=rc(n.messages,t),a=i.some(e=>gs(e)===void 0);return(a?i:[{id:`subagent:${n.id}`,role:`assistant`},...i]).map((e,t)=>{let i=gs(e);if(i!==void 0){let t=_s(e);return!t||t.parentSubagentRunId!==void 0?e:uc(e,i,{...t,parentSubagentRunId:n.id})}return uc(e,n.id,!a&&t===0?{...r,placeholder:!0}:r)})}function uc(e,t,n){let r=tc(e.metadata)?e.metadata:{},i=tc(r.tanstack)?r.tanstack:{};return{...e,subagentRunId:t,metadata:{...r,tanstack:{...i,subagent:n}}}}function dc(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return cc(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function fc(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`thoughtSignature`in e))return;let t=e.thoughtSignature;return typeof t==`string`&&t!==``?t:void 0}function pc(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=fc(n.metadata);t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...e===void 0?{}:{encryptedValue:e}})}return t.length>0?t:void 0}function mc(e,t){let n=`${e}-reasoning-${t.id??yc(t.content)}`;return t.type===`thinking`&&t.redacted?`${ho}${n}`:n}function hc(e){return`tool-${e}`}function gc(e,t){return _c(e,t)}function _c(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;let r=`${e}-${n}`;return t.add(r),r}function vc(e,t,n){let r=hc(t);return e===void 0||n.has(e)?r:e}function yc(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function bc(e){if((e.type===mo.RUN_FINISHED||e.type===mo.RUN_ERROR)&&(Array.isArray(e.usage)||so(e.usage))){let t=co(e.usage,Q(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===mo.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===mo.TOOL_CALL_END&&e.input===void 0){let t=Q(e)?.input;t!==void 0&&(e.input=t)}return e}function xc(e){bc(e);let t=Q(e),n=e;if(t==null)return n;for(let[e,r]of Object.entries(t))e===`usage`||e===`interruptErrors`||n[e]===void 0&&r!==void 0&&(n[e]=r);return t.interruptErrors!==void 0&&(n[`tanstack:interruptErrors`]=t.interruptErrors),n}function Sc(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval,a=e.execution;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,server(o){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,execute:o}},client(o){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execution:a,...o!==void 0&&{execute:o}}}}}function Cc(e){return typeof e==`string`&&e!==``?e:void 0}function wc(e){if(`runId`in e){let t=Cc(e.runId);if(t!==void 0)return t}return Cc(Q(e)?.runId)}var Tc=class{shouldEmit(e,t){return!0}};function Ec(e){let t=Error(e.message||e.error?.message||`An error occurred`),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}function Dc(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function Oc(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function kc(e,t,n,r,i,a,o){return e.map(e=>{if(e.id!==t)return e;let s=[...e.parts],c=s.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),l={type:`tool-result`,toolCallId:n,content:r,state:i,...o!==void 0&&{outcome:o},...a&&{error:a}};return c>=0?s[c]=l:s.push(l),{...e,parts:s}})}function Ac(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function jc(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function Mc(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function Nc(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=qn(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function Pc(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function Fc(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function Ic(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s;if(o<0){o=a.findIndex(e=>e.type===`thinking`&&e.stepId===void 0);let e=a[o];e?.type===`thinking`&&(s=e)}let c=i??s?.signature,l=go(n)||s?.redacted===!0,u={type:`thinking`,content:r,stepId:n,...c&&{signature:c},...l&&{redacted:!0}};return o>=0?a[o]=u:a.push(u),{...e,parts:a}})}var Lc=12;function Rc(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[Ko];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}function zc(e){if(e!=null)try{let t=JSON.stringify(e);return typeof t==`string`?t:void 0}catch{return}}var Bc=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;childProcessors=new Map;childToolCalls=new Map;finishReason=null;hasError=!1;isDone=!1;streamEndEmitted=!1;recording=null;recordingStartTime=0;subagentRunId;constructor(e={}){this.subagentRunId=e.subagentRunId,this.chunkStrategy=e.chunkStrategy||new Tc,this.events=e.events||{},this.jsonParser=e.jsonParser||Pn,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}prependMessages(e){let t=new Set(this.messages.map(e=>e.id)),n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));this.messages=[...n,...this.messages],this.emitMessagesChange()}addUserMessage(e,t,n){let r=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),i={id:t??ec(),role:`user`,parts:r,createdAt:new Date,...n==null?{}:{metadata:n}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(e){this.prepareAssistantMessage();let{messageId:t}=this.ensureAssistantMessage(e);return this.pendingManualMessageId=t,t}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){let r=this.childOwningToolCall(t=>t.id===e);if(r!==void 0){this.updateChild(r,r=>r.addToolResult(e,t,n));return}console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=jc(this.messages,e,t,n?`error`:void 0,n),a=ms(t),o=n?`error`:`complete`;i=kc(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){let n=this.childOwningToolCall(t=>t.approval?.id===e);if(n!==void 0){this.updateChild(n,n=>n.addToolApprovalResponse(e,t));return}this.messages=Mc(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...Hs(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||ss(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.childProcessors.clear(),this.childToolCalls.clear(),this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){if(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),!this.routeToChild(e))switch(e.type){case`SUBAGENT_STARTED`:this.handleSubagentStartedEvent(e);break;case`SUBAGENT_FINISHED`:this.handleSubagentFinishedEvent(e);break;case`SUBAGENT_ERROR`:this.handleSubagentErrorEvent(e);break;case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`STEP_FINISHED`:this.handleStepFinishedEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`REASONING_ENCRYPTED_VALUE`:this.handleReasoningEncryptedValueEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`STEP_STARTED`:this.handleStepStartedEvent(e)}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}consumePendingThinkingStep(e){if(!this.pendingThinkingStepId)return;let t=this.pendingThinkingStepId;e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){let e=Array.from(this.activeMessageIds).reverse();for(let t of e){let e=this.messageStates.get(t);if(e&&e.role===`assistant`)return t}for(let[e,t]of[...this.messageStates].reverse())if(t.role===`assistant`)return e;return null}resumeAssistantState(e,t){this.activeMessageIds.add(e),(t.isComplete||this.isDone)&&(t.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(e){if(e){let t=this.getMessageState(e);if(t)return this.resumeAssistantState(e,t),{messageId:e,state:t}}let t=this.getActiveAssistantMessageId();if(t){let e=this.getMessageState(t);if(e)return this.resumeAssistantState(t,e),{messageId:t,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let n=e||ec(),r={id:n,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,r];let i=this.createMessageState(n,`assistant`);return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}mergeMessageMetadata(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n=this.messages.find(t=>t.id===e);if(!n)return;let r=t,i=Q(r),a=i!=null&&(`content`in i||`args`in i)?{...r,tanstack:Object.fromEntries(Object.entries(i).filter(([e])=>e!==`content`&&e!==`args`))}:r,o=fo(n.metadata,a),s=Ns(Q(r)?.createdAt),c=s!==void 0;this.messages=this.messages.map(t=>t.id===e?{...t,...o===void 0?{}:{metadata:o},...c?{createdAt:s}:{}}:t),this.emitMessagesChange()}findSubagentPart(e){for(let t of this.messages)for(let n of t.parts)if(n.type===`subagent`&&n.subagent.id===e)return{message:t,part:n}}childOwning(e){let t=n=>n.some(n=>n.parts.some(n=>n.type===`subagent`&&(n.subagent.id===e||t(n.subagent.messages))));for(let n of this.messages)for(let r of n.parts)if(r.type===`subagent`&&(r.subagent.id===e||t(r.subagent.messages)))return r.subagent.id}childOwningToolCall(e){let t=n=>n.some(n=>n.parts.some(n=>n.type===`tool-call`&&e(n)||n.type===`subagent`&&t(n.subagent.messages)));for(let e of this.messages)for(let n of e.parts)if(n.type===`subagent`&&t(n.subagent.messages))return n.subagent.id}childProcessor(t){let n=this.findSubagentPart(t);if(!n)return;let r=n.part.subagent.messages,i=this.childProcessors.get(t);if(i)return i.getMessages()!==r&&(i.messages=r),i;let a=new e({subagentRunId:t,initialMessages:r,events:{onToolCall:e=>this.events.onToolCall?.(e),onApprovalRequest:e=>this.events.onApprovalRequest?.(e),onCustomEvent:(e,t,n)=>this.events.onCustomEvent?.(e,t,n)}});return this.childProcessors.set(t,a),a}updateChild(e,t){let n=this.childProcessor(e);if(!n)return;t(n);let r=n.getMessages();this.patchSubagent(e,e=>{e.messages=r})}handleSubagentStartedEvent(e){if(e.type!==`SUBAGENT_STARTED`)return;if(this.findSubagentPart(e.subagentRunId)){this.childProcessors.delete(e.subagentRunId),this.patchSubagent(e.subagentRunId,t=>{t.status=`running`,delete t.interruptIds,delete t.error,e.metadata!==void 0&&(t.metadata=e.metadata)});return}let{messageId:t}=this.ensureAssistantMessage(),n={type:`subagent`,subagent:{id:e.subagentRunId,name:e.name,...e.description!==void 0&&{description:e.description},status:`running`,...e.parentSubagentRunId!==void 0&&{parentSubagentRunId:e.parentSubagentRunId},...e.parentToolCallId!==void 0&&{parentToolCallId:e.parentToolCallId},...e.metadata!==void 0&&{metadata:e.metadata},messages:[]}};this.messages=this.messages.map(e=>e.id===t?{...e,parts:[...e.parts,n]}:e),this.emitMessagesChange()}handleSubagentFinishedEvent(e){e.type===`SUBAGENT_FINISHED`&&(this.updateChild(e.subagentRunId,e=>e.finalizeStream()),this.patchSubagent(e.subagentRunId,t=>{if(t.status!==`error`){if(e.outcome?.type===`suspended`){t.status=`suspended`,t.interruptIds=e.outcome.interruptIds??[];return}t.status=`finished`}}))}handleSubagentErrorEvent(e){e.type===`SUBAGENT_ERROR`&&(this.updateChild(e.subagentRunId,e=>e.finalizeStream()),this.patchSubagent(e.subagentRunId,t=>{t.status=`error`,t.error={message:e.message,...e.code!==void 0&&{code:e.code}}}))}patchSubagent(e,t){this.messages=this.messages.map(n=>{let r=n.parts.findIndex(t=>t.type===`subagent`&&t.subagent.id===e);if(r===-1)return n;let i=n.parts[r];if(!i||i.type!==`subagent`)return n;let a={type:`subagent`,subagent:{...i.subagent}};t(a.subagent);let o=[...n.parts];return o[r]=a,{...n,parts:o}}),this.emitMessagesChange()}routeToChild(e){let t;if(e.type===`SUBAGENT_STARTED`)t=e.parentSubagentRunId;else if(e.type===`SUBAGENT_FINISHED`||e.type===`SUBAGENT_ERROR`){if(this.findSubagentPart(e.subagentRunId))return!1;t=e.subagentRunId}else`subagentRunId`in e&&e.subagentRunId?t=e.subagentRunId:`toolCallId`in e&&typeof e.toolCallId==`string`&&(t=this.childToolCalls.get(e.toolCallId));if(t===void 0)return!1;let n=this.childOwning(t);return n===void 0?t===this.subagentRunId?!1:(console.warn(`[StreamProcessor] Dropped a chunk for unknown subagent ${t}`),!0):this.findSubagentPart(n)?.part.subagent.status===`error`?!0:(e.type===`TOOL_CALL_START`&&this.childToolCalls.set(e.toolCallId,n),this.updateChild(n,t=>t.processChunk(e)),!0)}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e,r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let n=this.pendingManualMessageId;if(this.pendingManualMessageId=null,n!==t){this.messages=this.messages.map(e=>e.id===n?{...e,id:t}:e);let e=this.messageStates.get(n);e&&(e.id=t,this.messageStates.delete(n),this.messageStates.set(t,e)),this.activeMessageIds.delete(n),this.activeMessageIds.add(t);for(let[e,r]of this.toolCallToMessage)r===n&&this.toolCallToMessage.set(e,t)}let i=this.messageStates.get(t);i?i.hasToolCallsSinceTextStart&&(i.currentSegmentText!==i.lastEmittedText&&this.emitTextUpdateForMessage(t),i.currentSegmentText=``,i.lastEmittedText=``,i.hasToolCallsSinceTextStart=!1):(i=this.createMessageState(t,r),this.activeMessageIds.add(t)),this.mergeMessageMetadata(t,e.metadata),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&=(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,!1):this.createMessageState(t,r),this.mergeMessageMetadata(t,e.metadata);return}let i={id:t,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(t,r),this.activeMessageIds.add(t),this.mergeMessageMetadata(t,e.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(e){let{messageId:t}=e;this.mergeMessageMetadata(t,e.metadata);let n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=new Map(t.map(e=>[e.id,e])),{top:r,groups:i}=bs(e.messages),a=this.mergeReasoningFanOut(r.map(Js)),o=this.reconcileSnapshotToolCalls(a,t).map(e=>{if(e.metadata!=null)return e;let t=n.get(e.id);return t?.metadata==null?e:{...e,metadata:t.metadata}});this.messages=this.attachSnapshotSubagents(o,r,i,t),this.emitMessagesChange()}attachSnapshotSubagents(t,n,r,i){let a=[],o=new Map;for(let t of r){let r=new e({subagentRunId:t.id});r.processChunk({type:mo.MESSAGES_SNAPSHOT,messages:t.messages,timestamp:Date.now()}),o.set(t.id,r);let{placeholder:i,...s}=t.info;a.push({hostId:n.slice(0,t.hostIndex+1).findLast(e=>e.role===`assistant`)?.id,part:{type:`subagent`,subagent:{...s,id:t.id,messages:r.getMessages()}},carried:!1})}let s=new Set(r.map(e=>e.id));for(let e of i)for(let t of e.parts){if(t.type!==`subagent`||s.has(t.subagent.id))continue;a.push({hostId:e.id,...t.subagent.parentToolCallId!==void 0&&{toolCallId:t.subagent.parentToolCallId},part:t,carried:!0});let n=this.childProcessors.get(t.subagent.id);n&&o.set(t.subagent.id,n)}this.childProcessors.clear();for(let[e,t]of o)this.childProcessors.set(e,t);let c=t;for(let e of a){let t=c.findIndex(t=>t.id===e.hostId);if(t===-1&&e.toolCallId!==void 0&&(t=c.findIndex(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))),t===-1&&!e.carried&&(t=c.findLastIndex(e=>e.role===`assistant`)),t===-1){e.carried||(c=[...c,{id:ec(),role:`assistant`,parts:[e.part]}]);continue}c=c.map((n,r)=>r!==t||n.parts.some(t=>t.type===`subagent`&&t.subagent.id===e.part.subagent.id)?n:{...n,parts:[...n.parts,e.part]})}return c}mergeReasoningFanOut(e){let t=[],n=[],r=e=>e.parts.filter(e=>e.type===`thinking`),i=e=>e.role===`assistant`&&e.parts.length>0&&e.parts.every(e=>e.type===`thinking`),a=e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-result`)&&e.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`),o=()=>{t.push(...n),n=[]};for(let s of e){if(i(s)){n.push(s);continue}let e=s;s.role===`assistant`&&n.length>0&&!a(s)?(e={...s,parts:[...n.flatMap(r),...s.parts]},n=[]):o();let c=t.at(-1);if(c?.role===`assistant`&&e.role===`assistant`&&cs(e.id,c.id)){t[t.length-1]={...c,parts:[...c.parts,...e.parts]};continue}t.push(e)}return o(),t}reconcileSnapshotToolCalls(e,t){let n=new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.parts.filter(e=>e.type===`tool-result`),a=t.role===`assistant`&&e.length===1&&t.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`)?e[0]:void 0;if(!a){i.push(t);continue}let o=i.findLast(e=>e.parts.some(e=>e.type===`tool-call`&&e.id===a.toolCallId))??i.findLast(e=>e.role===`assistant`&&!(e.parts.length===1&&e.parts[0]?.type===`tool-result`));if(!o){r.has(a.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${a.toolCallId}") will not be able to locate this call`),i.push(t);continue}let s=[...o.parts];if(!r.has(a.toolCallId)&&!s.some(e=>e.type===`tool-call`&&e.id===a.toolCallId)){let e=n.get(a.toolCallId);e?(s.push({...e}),r.add(e.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${a.toolCallId}") will not be able to locate this call`)}s.push(...t.parts),o.parts=s}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?ps(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.mergeMessageMetadata(t,e.metadata),this.structuredMessageIds.has(t)){let r=e.delta||``;r!==``&&(this.messages=Nc(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1),n.hasToolCallsSinceTextStart=!1;let i=n.currentSegmentText,a=e.delta||``,o=a===``?i:i+a,s=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=s;let c=e.delta||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(t??void 0);r.hasToolCallsSinceTextStart=!0;let i=e.toolCallId;if(!r.toolCalls.get(i)){let t=`awaiting-input`,a=e.toolCallName,o=e.metadata,s={id:e.toolCallId,name:a,arguments:``,state:t,parsedArguments:void 0,index:r.toolCalls.size,...o!==void 0&&{metadata:o}};r.toolCalls.set(i,s),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=Oc(this.messages,n,{id:e.toolCallId,name:a,arguments:``,state:t,...o!==void 0&&{metadata:o}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Oc(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=e.input===void 0?Q(e)?.input:e.input,i=n.toolCalls.get(e.toolCallId);if(i&&i.state!==`input-complete`){let a=zc(r);a!==void 0&&(i.arguments=a);let o=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,o,i),a!==void 0&&(i.parsedArguments=r,this.messages=Oc(this.messages,t,{id:i.id,name:i.name,arguments:i.arguments,state:`input-complete`,input:r,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange())}}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId)??this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))?.id;if(!t)return;let n=e,r=Q(e)?.toolResultOutcome,i=us(r)?r:void 0,a=n.state===`output-error`||Q(e)?.state===`output-error`||i!==void 0,o;try{o=typeof e.content==`string`?JSON.parse(e.content):e.content}catch{o=e.content}this.messages=jc(this.messages,e.toolCallId,o,a?`error`:void 0);let s=a?`error`:`complete`;this.messages=kc(this.messages,t,e.toolCallId,fs(o)?o:Qs(e.content),s,s===`error`?ps(o):void 0,i),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e;if(this.finishReason=t.finishReason===void 0?Q(e)?.finishReason??null:t.finishReason,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason===`tool_calls`&&e.outcome?.type!==`interrupt`)return;this.isDone=!0,this.finalizeStream()}}handleInterrupts(e,t=!0){let n=Rc(e);for(let r of e){let e=r.metadata&&typeof r.metadata==`object`?r.metadata:{},i=typeof e.kind==`string`?e.kind:void 0,a=r.toolCallId;if(!a)continue;let o=r.subagentRunId===void 0?this.childOwningToolCall(e=>e.id===a):this.childOwning(r.subagentRunId);o!==void 0&&this.updateChild(o,e=>e.handleInterrupts([r],!1));let s=typeof e.toolName==`string`?e.toolName:this.findToolCallName(a),c=Object.hasOwn(e,`input`)?e.input:{};if(i===`approval`||r.reason===`approval_required`){if(o!==void 0){t&&this.events.onApprovalRequest?.({toolCallId:a,toolName:s,input:c,approvalId:r.id});continue}let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(a)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===a))?.id;if(e&&(this.messages=Ac(this.messages,e,a,r.id),this.emitMessagesChange()),!t)continue;this.events.onApprovalRequest?.({toolCallId:a,toolName:s,input:c,approvalId:r.id});continue}if(i===`client_tool`||r.reason===`client_tool_input`){if(n||!t)continue;this.events.onToolCall?.({toolCallId:a,toolName:s,input:c})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=wc(e);t?this.activeRuns.delete(t):this.activeRuns.clear();let{messageId:n}=this.ensureAssistantMessage(),r=e.message||`An error occurred`;e.message||console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=Fc(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(Ec(e))}handleStepStartedEvent(e){let t=e.stepName||ec(),n=this.getActiveAssistantMessageId();if(n){let e=this.getMessageState(n);if(e){e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=t}handleStepFinishedEvent(e){let t=e,n=t.signature;if(!n)return;let{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),a=i.currentThinkingStepId??t.stepId;if(!a)return;let o=i.thinkingSteps.get(a);o!==void 0&&(i.thinkingStepSignatures.set(a,n),this.messages=Ic(this.messages,r,a,o,n),this.emitMessagesChange())}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;let r=e.delta||``;this.consumePendingThinkingStep(n);let i=n.currentThinkingStepId??e.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,``),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);let a=(n.thinkingSteps.get(i)??``)+r;n.thinkingSteps.set(i,a),this.messages=Ic(this.messages,t,i,a,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,i,a)}handleReasoningEncryptedValueEvent(e){let t=e.encryptedValue;if(typeof t!=`string`||t===``)return;if(e.subtype===`tool-call`){this.attachToolCallSignature(e.entityId,t);return}let{messageId:n,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??e.entityId;r.thinkingStepSignatures.set(i,t);let a=r.thinkingSteps.get(i)??``;r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,a),r.thinkingStepOrder.push(i)),this.messages=Ic(this.messages,n,i,a,t),this.emitMessagesChange()}attachToolCallSignature(e,t){this.messages=this.messages.map(n=>{let r=!1,i=n.parts.map(n=>n.type!==`tool-call`||n.id!==e?n:(r=!0,{...n,metadata:{...n.metadata!=null&&typeof n.metadata==`object`?n.metadata:{},thoughtSignature:t}}));return r?{...n,parts:i}:n});for(let n of this.messageStates.values()){let r=n.toolCalls.get(e);r&&(r.metadata={...r.metadata??{},thoughtSignature:t})}this.emitMessagesChange()}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}));return}if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=Pc(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`tool-input-available`&&e.value){let{toolCallId:t,toolName:n,input:r}=e.value;this.events.onToolCall?.({toolCallId:t,toolName:n,input:r});return}if(e.name===`approval-requested`&&e.value){let{toolCallId:n,toolName:r,input:i,approval:a}=e.value,o=t??this.toolCallToMessage.get(n);o&&(this.messages=Ac(this.messages,o,n,a.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:a.id});return}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}isNewTextSegment(e,t){return!0}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartTerminal(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=Oc(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartTerminal(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`error`||t.state===`complete`)))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=Dc(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=Lc&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);!t||t.chunkCount===0||(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=Fc(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)){this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange();return}e&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(e))}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[],this.childProcessors.clear(),this.childToolCalls.clear()}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(Vc(t))}};function Vc(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var Hc=/^[a-z][a-z0-9-]{0,63}$/;function Uc(e){return typeof e==`string`&&Hc.test(e)}function Wc(e){if(typeof e!=`object`||!e||!(`error`in e))return!1;let t=e.error;return!(typeof t!=`object`||!t||!(`type`in t)||t.type!==`byok_missing`||!(`provider`in t)||typeof t.provider!=`string`||!Uc(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Gc=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},Kc=class extends Error{provider;reason;constructor(e,t){super(t===`locked`?`${e} key is locked`:`Missing ${e} API key`),this.name=`ByokBlockedError`,this.provider=e,this.reason=t}},qc=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},Jc=new WeakMap;function Yc(e){return Jc.get(e)??wc(e)}var Xc=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Zc=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Qc=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},$c=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function el(e){let t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function tl(e){let t=el(e),n=new Set,r,i=0;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n){if(e)i=0;else if(i+=1,i>t.maxAttempts)throw new $c(t.maxAttempts);await nl(t.delayMs,n)}}}function nl(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function rl(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function il(e,t){if(!e)throw Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function al(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var ol=`X-Run-Id`;function sl(e){return e===void 0?{}:{[ol]:e}}function cl(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*ll(e,t){try{let n=to(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Zc(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
8
- `);r=s.pop()||``;for(let e of s){let t=e.endsWith(`\r`)?e.slice(0,-1):e;t.trim()&&(yield t)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new Xc}finally{e.releaseLock()}}function ul(e){return xc(e)}function dl(e){let t=Q(e)?.model;if(typeof t==`string`)return t;let n=`usage`in e?e.usage:void 0;if(Array.isArray(n)){let e=n[0]?.model;if(typeof e==`string`)return e}}async function*fl(e,t){let n,r,i,a;for await(let o of e){if(o===`id`||o.startsWith(`id:`)){let e=o===`id`?``:o.slice(3);a=e.startsWith(` `)?e.slice(1):e;continue}if(o.startsWith(`:`)||o.startsWith(`event:`)||o.startsWith(`retry:`))continue;let e=no(o);if(e===`[DONE]`){yield{chunk:po({type:mo.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,timestamp:Date.now()},{finishReason:`stop`,...i===void 0?{}:{model:i}})};return}let s=ul(JSON.parse(e));`threadId`in s&&typeof s.threadId==`string`&&(n=s.threadId),`runId`in s&&typeof s.runId==`string`&&(r=s.runId);let c=dl(s);c!==void 0&&(i=c);let l=a;a=void 0,yield{chunk:s,...l===void 0?{}:{id:l}}}}async function pl(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Wc(t))throw new Gc(t.error.provider)}throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}function ml(e,t){let n={threadId:e};return t?.limit!==void 0&&(n.limit=String(t.limit)),t?.before!==void 0&&(n.before=t.before),n}function hl(e){return typeof e!=`object`||!e||!(`truncated`in e)||e.truncated!==!0||!(`cursor`in e)||typeof e.cursor!=`string`||e.cursor===``?{truncated:!1}:{truncated:!0,cursor:e.cursor}}async function gl(e,t,n,r,i,a){let o=await e(cl(t,ml(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await pl(o);let s=await o.json(),c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null,l=s.interrupts&&typeof s.interrupts.runId==`string`&&Array.isArray(s.interrupts.pending)&&s.interrupts.pending.length>0?{runId:s.interrupts.runId,pending:s.interrupts.pending}:null;return{messages:Array.isArray(s.messages)?ao(s.messages):[],activeRun:c,interrupts:l,page:hl(s.page)}}async function _l(e,t,n,r,i){let a=await e(cl(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await pl(a);let o=await a.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!=`object`||Array.isArray(o))throw Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?`an array`:typeof o}.`);let s=o,c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null;return{resumeSnapshot:s.resumeSnapshot??null,activeRun:c}}async function*vl(e,t,n){await pl(e),yield*fl(ll(eo(e),t),n)}async function*yl(e,t){for await(let{chunk:n}of vl(e,t))yield n}function bl(e,t,n,r){return async function*(i,a){let o;try{o=await e(t,{...n,headers:{...n.headers,...i},...a?{signal:a}:{}})}catch(e){throw new Zc(e)}yield*r(o,a)}}async function*xl(e,t,n){let r=tl(n);for(;;){if(t?.aborted)return;let n=r.lastEventId===void 0?{}:{"Last-Event-ID":r.lastEventId},i=!1,a=!1;try{for await(let{chunk:o,id:s}of e(n,t))r.note(s)!==`duplicate`&&(a=!0,(o.type===`RUN_FINISHED`||o.type===`RUN_ERROR`)&&(i=!0),yield o)}catch(e){if(t?.aborted)return;if((e instanceof Xc||e instanceof Zc)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new Qc}return}}function Sl(e){if(!e)throw Error(`Connection adapter is required`);let t=`connect`in e,n=`subscribe`in e,r=`send`in e;if(t&&(n||r))throw Error(`Connection adapter must provide either connect or both subscribe and send, not both modes`);if(n&&r){let t=e.joinRun?.bind(e),n=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[],o;function s(e,t){t&&Jc.set(e,t);let n=a.shift();n?n(e):i.push(e)}async function c(e){let t=()=>o!==a||i.length===0&&(a.length>0||e?.aborted);for(let n=0;n<16&&!e?.aborted;n++){if(t())return;await Promise.resolve()}for(;!e?.aborted;){if(t())return;await new Promise(e=>setTimeout(e,0))}}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){o=n;try{for(;!e?.aborted;){let r,i=t.shift();r=i===void 0?await new Promise(t=>{let r=()=>t(null);n.push(n=>{e?.removeEventListener(`abort`,r),t(n)}),e?.addEventListener(`abort`,r,{once:!0})}):i,r!==null&&(yield r)}}finally{o===n&&(o=void 0)}})()},async send(t,n,r,i){let a=!1,o,l;try{let c=e.connect(t,n,r,i);for await(let e of c)`threadId`in e&&typeof e.threadId==`string`&&(o=e.threadId),`runId`in e&&typeof e.runId==`string`&&(l=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),s(e,i?.runId);!r?.aborted&&!a&&s(po({type:mo.RUN_FINISHED,threadId:il(o??i?.threadId,`threadId`),runId:il(l??i?.runId,`runId`),timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i?.runId)}catch(e){if(!r?.aborted&&!a)try{let t=e instanceof Error?e.message:`Unknown error in connect()`;s({type:mo.RUN_ERROR,threadId:il(o??i?.threadId,`threadId`),runId:il(l??i?.runId,`runId`),timestamp:Date.now(),message:t},i?.runId)}catch{}throw e}await c(r)},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:(e,n)=>t(e,n)}:{}})()}}function Cl(e,t,n,r){let i=rc(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??rl(`thread`),runId:n?.runId??rl(`run`),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n?.clientTools??[],context:[],forwardedProps:a,data:{...a}}}function wl(e,t={}){return{async*connect(n,r,i,a){let o=typeof e==`function`?e():e,s=typeof t==`function`?await t():t,c={"Content-Type":`application/json`,...al(s.headers),...al(a?.headers),...sl(a?.runId)},l=Cl(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*xl(bl(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>vl(e,t,{...a?.threadId===void 0?{}:{threadId:a.threadId},...a?.runId===void 0?{}:{runId:a.runId}})),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=cl(i,{offset:`-1`,runId:n}),s={...al(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*xl(bl(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>vl(e,t,{runId:n})),l,a.reconnect)},async hydrate(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t;return gl(a.fetchClient??fetch,i,al(a.headers),a.credentials||`same-origin`,n,r)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return _l(i.fetchClient??fetch,r,al(i.headers),i.credentials||`same-origin`,n)}}}function Tl(e){return{async*connect(t,n,r,i){if(!r)throw Error(`fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.`);if(!i)throw Error(`fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.`);let a=await e({messages:t,data:n,threadId:i.threadId,runId:i.runId,...i.parentRunId===void 0?{}:{parentRunId:i.parentRunId},...i.resume===void 0?{}:{resume:i.resume}},{signal:r,headers:i.headers});a instanceof Response?yield*yl(a,r):yield*El(a,r)}}}async function*El(e,t){if(t.aborted)return;let n=e[Symbol.asyncIterator](),r=new Promise(e=>{t.addEventListener(`abort`,()=>e({done:!0,value:void 0}),{once:!0})});try{for(;;){let e=await Promise.race([n.next(),r]);if(e.done)return;yield e.value}}finally{await n.return?.()}}function Dl(e){return e.resumable}function Ol(e,t){let n=as(e.descriptor);return n?{...t,metadata:is(n)}:t}function kl(e){return`cancel`in e&&`clearResolution`in e}var Al=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),jl=new Set([`incomplete-batch`,`item-validation-failed`,`unsupported-bulk-operation`,`async-resolver`,`inactive-transaction`,`mixed-provenance`,`transport`,`server`,`protocol`,`invalid-response-schema`,`expired`,`stale`,`conflict`,`legacy-submit-failed`]);function Ml(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nl(e){return Ml(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function Pl(e){return Ml(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function Fl(e){return Nl(e.metadata)||Pl(e.metadata)}function Il(e){return Qo(e)}function Ll(e){if(!Ml(e.metadata))return!1;let t=e.metadata[Ko];return!Ml(t)||t.v!==void 0&&t.v!==1?!1:t.kind===`generic`||t.kind===`tool-approval`||t.kind===`client-tool-execution`||`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function Rl(e){if(!Ml(e.metadata))return!1;let t=e.metadata[Ko];return!Ml(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function zl(e){return e.metadata?.[`tanstack:interruptPayload`]}function Bl(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function Vl(e){if(e.responseSchema!==void 0)try{return Co(So(e.responseSchema))}catch{return}}function Hl(e){if(e!==void 0)try{return ts(e)}catch{return}}function Ul(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Wl(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(ko(e)){let r=e[`~standard`].validate(t),i=e=>e.issues?{code:n,message:e.issues[0]?.message??`Schema validation failed.`}:{valid:!0,payload:e.value};return Ul(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function Gl(e){for(let t of Al)if(t===e)return!0;return!1}function Kl(e){for(let t of jl)if(t===e)return!0;return!1}function ql(e){if(!Ml(e))return!1;let t=e.scope,n=e.code;return typeof n==`string`&&typeof e.message==`string`&&typeof e.retryable==`boolean`&&typeof e.threadId==`string`&&typeof e.interruptedRunId==`string`&&typeof e.generation==`number`?t===`item`?Gl(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&Kl(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`):!1}function Jl(e){return ql(e)?[e]:!Ml(e)||!Array.isArray(e.errors)?[]:e.errors.every(ql)?e.errors:[]}function Yl(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function Xl(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Yl(e.interruptIds,t.interruptIds)}function Zl(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Xl(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Xl(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Ql(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;let n=t.resolutions.map(e=>e.interruptId);return e.scope===`item`?n.includes(e.interruptId):Yl(e.interruptIds,n)}function $l(e,t,n){let r=Vl(e)??n?.responseSchemaHash;return $({v:1,kind:`generic`,interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r===void 0?{}:{responseSchemaHash:r},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}})}function eu(e,t){let n=$(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([$(e.error)]),i=r[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message===void 0?{}:{message:n.message},...n.responseSchema===void 0?{}:{responseSchema:n.responseSchema},...n.expiresAt===void 0?{}:{expiresAt:n.expiresAt},...n.metadata===void 0?{}:{metadata:n.metadata},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,...i===void 0?{}:{error:i},canResolve:e.canResolve}}var tu=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=new Map;for(let n of e.interrupts??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t=`live`){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:$(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=Il(t);e?.kind===`generic`&&e.definitionId!==void 0&&e.key!==void 0&&e.batchIndex!==void 0&&n.set(e.batchIndex,(n.get(e.batchIndex)??0)+1)}this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind===`generic`&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e==`boolean`){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)Dl(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Ol(e,{interruptId:e.descriptor.id,status:`cancelled`})),e.status=`staged`,e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw Error(`Interrupt submission is already active.`);let e=this.retrySubmission;if(!e){this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){return this.resolveClientToolResult(e,{state:`output-available`,output:t})}resolveClientToolError(e,t){return this.resolveClientToolResult(e,{state:`output-error`,errorText:t})}resolveClientToolResult(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e||t.kind===`generic`&&Bl(t.descriptor.reason)&&t.descriptor.toolCallId===e&&Pl(t.descriptor.metadata));return n?n.kind===`client-tool-execution`?t.state===`output-available`?(this.resolveItem(n.descriptor.id,t.output),!0):(this.stageClientToolError(n,t.errorText),!0):(this.resolveItem(n.descriptor.id,t.state===`output-error`?{error:t.errorText}:t.output),!0):!1}stageClientToolError(e,t){if(this.assertItemMutable(),this.invalidateRetry(),!e.canResolve){e.status=`error`,e.error=this.itemError(e.descriptor.id,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),this.publish();return}e.validationGeneration++,e.resolution=$(po(Ol(e,{interruptId:e.descriptor.id,status:`resolved`,payload:{error:t}}),{state:`output-error`})),e.status=`staged`,e.error=void 0,this.publish(),this.maybeSubmit()}resolveToolApprovalDecision(e,t){let n=this.items.find(t=>t.descriptor.id===e&&(t.kind===`tool-approval`||t.kind===`generic`&&t.descriptor.reason===`approval_required`&&Nl(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=$(e),i=Il(r),a=i===void 0&&Fl(r);if(i===void 0&&!a)return Ll(r)?{descriptor:r,binding:$l(r,t,void 0),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding is invalid or incomplete.`),validationGeneration:0}:{descriptor:r,binding:void 0,kind:`unbound`,status:`pending`,canResolve:!1,resumable:!1,validationGeneration:0};let o=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&Vl(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(Vl(r)??i.responseSchemaHash);if(i!==void 0&&Rl(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:$l(r,t,i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding does not match this interrupted run.`),validationGeneration:0};if(s&&i.kind===`tool-approval`){let e=this.tools?.find(e=>e.name===i.toolName);if(e?.needsApproval===!0&&r.toolCallId===i.toolCallId)try{let t=Wo(e.approvalSchema,e.inputSchema);if(Go(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:$(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}catch{}}if(s&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId&&Go(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:$(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}if(i!==void 0&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)!==1)return{descriptor:r,binding:$(i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`Generic interrupt batch contains a duplicate batchIndex.`),validationGeneration:0};if(o&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)===1){let e=this.interruptDefinitions.get(i.definitionId);if(e!==void 0&&Hl(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===Hl(e.payloadSchema))){let t=zl(r);return{descriptor:r,binding:$(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:$(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||Vl(r)===void 0||i.responseSchemaHash===Vl(r));return{descriptor:r,binding:$l(r,t,i),kind:`generic`,status:`pending`,canResolve:c,resumable:c,validationGeneration:0}}buildSnapshot(e){let t=this.requireHydration(),n=this.items.filter(e=>e.kind!==`client-tool-execution`&&e.status!==`submitting`).map(n=>{let r=eu(n,t);if(n.kind===`unbound`||n.binding===void 0){let e={...r,kind:`unbound`,canResolve:!1};return Object.freeze(e)}if(n.kind===`tool-approval`&&n.binding.kind===`tool-approval`){let t=$(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:$(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=Ml(r)?r:void 0;this.resolveItem(n.descriptor.id,{approved:t,...t&&i?.editedArgs!==void 0?{editedArgs:i.editedArgs}:{},...i?.payload===void 0?{}:{payload:i.payload}},e)}};return Object.freeze(i)}let i=n.binding.kind===`generic`?$(n.binding):$({v:1,kind:`generic`,interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash==`string`?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind===`generic`){let t={...r,kind:`generic`,definitionId:n.definition.id,key:n.binding.key??``,payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(t)}let a={...r,kind:`generic`,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(a)});return Object.freeze(n)}publish(e=`live`){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);let r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status=`error`,r.error=this.itemError(e,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),n||this.publish();return}let i=++r.validationGeneration,a=this.validateCandidate(r,t);if(Ul(a)){r.status=`validating`,r.error=void 0,n||this.publish(),Promise.resolve(a).then(e=>{i===r.validationGeneration&&this.applyValidation(r,e,n)}).catch(e=>{i===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:e instanceof Error?e.message:String(e)},n)});return}this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(Ol(n,{interruptId:e,status:`cancelled`})),n.status=`staged`,n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status=`pending`,t||this.publish()}maybeSubmit(){let e=this.items.some(e=>e.kind===`generic`),t=this.items.filter(t=>Dl(t)&&!(e&&t.kind===`client-tool-execution`));if(t.length===0||t.some(e=>e.resolution===void 0||e.status!==`staged`))return;let n=this.requireHydration(),r=To(t.map(e=>e.resolution).filter(e=>e!==void 0)),i=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(i)}applyValidation(e,t,n){if(!(`valid`in t)){e.status=`error`;let r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind===`client-tool-execution`&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(t=>!(t.code===`item-validation-failed`&&t.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:`batch`,code:`item-validation-failed`,message:r.message,source:`client`,retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish();return}e.resolution=$(Ol(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind===`generic`){let n=Wl(e.definition?.responseSchema??e.descriptor.responseSchema,t,`invalid-payload`);if(e.definition===void 0)return n;let r=e=>`valid`in e?{valid:!0,payload:t}:e;return Ul(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=Wl(e.tool?.outputSchema,t,`invalid-tool-output`),r=e=>{if(!(`valid`in e))return e;try{return{valid:!0,payload:$(e.payload)}}catch(e){return{code:`invalid-tool-output`,message:e instanceof Error?e.message:String(e)}}};return Ul(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!Ml(t)||typeof t.approved!=`boolean`)return{code:`invalid-payload`,message:`Tool approval resolutions require an approved boolean.`};let n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:`invalid-edited-args`,message:`Rejected tool approvals cannot edit tool arguments.`};if(n&&r!==void 0){let n=Wl(e.tool?.inputSchema,r,`invalid-edited-args`);return Ul(n)?Promise.resolve(n).then(n=>`valid`in n?this.validateApprovalPayload(e,t,n.payload):n):`valid`in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){let r=t.approved===!0,i=this.approvalBranchSchema(e.tool,r),a=t.payload;if(i===void 0&&a!==void 0)return{code:`invalid-payload`,message:`This approval branch does not accept a payload.`};if(i!==void 0&&a===void 0)return{code:`invalid-payload`,message:`This approval branch requires a payload.`};let o=Wl(i,a,`invalid-payload`),s=e=>`valid`in e?{valid:!0,payload:{approved:r,...n===void 0?{}:{editedArgs:n},...i===void 0?{}:{payload:e.payload}}}:e;return Ul(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!Ml(n)||!(`approve`in n||`reject`in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind===`client-tool-execution`?`invalid-tool-output`:`invalid-payload`}resolveBooleanBulk(e){let t=this.items.filter(e=>Dl(e)&&e.kind!==`client-tool-execution`);if(!t.every(t=>t.kind===`tool-approval`&&this.approvalBranchSchema(t.tool,e)===void 0)||t.length===0){this.addRootError(`unsupported-bulk-operation`,`Boolean bulk resolution requires payloadless tool approvals.`,!1);return}this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=$({interruptId:n.descriptor.id,status:`resolved`,payload:{approved:e}}),n.status=`staged`,n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){let t=this.items.map(e=>({status:e.status,...e.resolution===void 0?{}:{resolution:e.resolution},...e.error===void 0?{}:{error:e.error},validationGeneration:e.validationGeneration})),n={active:!0};this.activeTransaction=n;let r=this.buildSnapshot(n).filter(kl),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:Ul(n)?`async-resolver`:`inactive-transaction`,message:Ul(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>Dl(e)&&e.kind!==`client-tool-execution`&&(e.resolution===void 0||e.status!==`staged`))&&(i={code:`incomplete-batch`,message:`Interrupt transaction did not resolve every item.`})}catch(e){i={code:`item-validation-failed`,message:e instanceof Error?e.message:String(e)}}finally{n.active=!1,this.activeTransaction=void 0}if(i){this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{let r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active||this.activeTransaction&&e!==this.activeTransaction)throw Error(`Interrupt transaction is inactive.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}assertRootMutable(){if(this.activeTransaction)throw Error(`Interrupt transaction is already active.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){let t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(let e of this.items)Dl(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){let n=Jl(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)Dl(e)&&(e.status=`error`);return}let r=n.filter(e=>Ql(e,t));r.length!==n.length&&this.addRootError(`protocol`,`Interrupt submission errors did not match the active batch.`,!1);let i=!1,a=!1,o=[];for(let e of r)if((e.code===`stale`||e.code===`expired`||e.code===`conflict`)&&(i=!0),a||=e.retryable,e.scope===`item`){let t=this.items.find(t=>Dl(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=$(e))}else o.push($(e));let s=Zl(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)Dl(e)&&e.status===`submitting`&&(e.status=`error`);this.retrySubmission=a&&!i?t:void 0}addRootError(e,t,n,r=`client`){let i=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:`batch`,code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(Dl).map(e=>e.descriptor.id)),threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})]),this.publish()}findItem(e){let t=this.items.find(t=>t.descriptor.id===e);if(!t)throw Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw Error(`InterruptManager is not hydrated.`);return this.hydration}itemError(e,t,n,r){let i=this.requireHydration();return Object.freeze({scope:`item`,interruptId:e,code:t,message:n,...r===void 0?{}:{path:Object.freeze([...r])},source:`client`,retryable:!1,threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})}},nu=new WeakMap;function ru(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(Uc);if(t.length===1)return t[0];let n=nu.get(e)??[];if(n.length===1)return n[0]}function iu(e,...t){let n=e?.();if(Uc(n))return n;for(let e of t)if(Uc(e))return e}async function au(e,t){if(!t)throw new qc;return await e.prepare(t),e.headers(t)}var ou=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent(`client:created`,{initialMessageCount:e})}loadingChanged(e){this.emitEvent(`client:loading:changed`,{isLoading:e})}errorChanged(e){this.emitEvent(`client:error:changed`,{error:e})}textUpdated(e,t,n,r){this.emitEvent(`text:chunk:content`,{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,i,a,o){this.emitEvent(`tools:call:updated`,{streamId:e,messageId:t,toolCallId:n,toolName:r,state:i,arguments:a,...o})}thinkingUpdated(e,t,n,r,i){this.emitEvent(`text:chunk:thinking`,{streamId:e,messageId:t,content:n,delta:r,...i})}structuredOutputChanged(e,t,n,r,i){this.emitEvent(e,{streamId:t,messageId:n,...r,...i})}approvalRequested(e,t,n,r,i,a,o){this.emitEvent(`tools:approval:requested`,{streamId:e,messageId:t,toolCallId:n,toolName:r,input:i,approvalId:a,...o})}messageAppended(e,t,n){let r=e.parts.filter(e=>e.type===`text`).map(e=>e.content).join(` `);this.emitEvent(`text:message:created`,{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){let n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content).join(``);this.emitEvent(`text:message:created`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent(`text:message:user`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent(`client:reloaded`,{fromMessageIndex:e})}stopped(){this.emitEvent(`client:stopped`)}messagesCleared(){this.emitEvent(`client:messages:cleared`)}toolResultAdded(e,t,n,r,i){this.emitEvent(`tools:result:added`,{toolCallId:e,toolName:t,output:n,state:r,...i})}toolApprovalResponded(e,t,n,r){this.emitEvent(`tools:approval:responded`,{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},su=class extends ou{emitEvent(){}},cu=class{events;constructor(e){this.events=new su(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return``}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},lu=e=>new cu(e);function uu(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function du(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function fu(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function pu(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var mu=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){let e=[...this.lastMessages];if(e.length===0&&!this.lastResume){let e=this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)});return}let t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(uu).catch(()=>void 0);let t=uu(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;let t=this.messagesGeneration;e.then(e=>{!e||this.messagesGeneration!==t||(this.lastResume=e.resume??null,this.lastMessages=e.messages,this.applyMessages(e.messages),e.resume&&this.applyResume&&this.applyResume(e.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;let e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){let t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{let t=e();if(t instanceof Promise){this.queuePending=!0;let e=t.catch(()=>{});this.queue=e,e.finally(()=>{this.queue===e&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){let t=Yc(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=du(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=pu(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=fu(e);return i?!!this.clearedMessageIds.has(i):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=fu(e);t&&this.clearedMessageIds.add(t);let n=du(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Yc(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function hu(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function gu(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function _u(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var vu=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){let t=Yc(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=hu(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=_u(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=gu(e);return!!(i&&this.clearedMessageIds.has(i))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=gu(e);t&&this.clearedMessageIds.add(t);let n=hu(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Yc(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}},yu=8;function bu(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function xu(e){let t=new Set;for(let n of e??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function Su(e){let{connection:t,fetcher:n}=e;if(t&&n)throw Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return Tl(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function Cu(e){return`connect`in e}function wu(e){if(e.type!==`RUN_FINISHED`||e.outcome?.type===`interrupt`)return!1;let t=e;return t.finishReason===void 0?Q(e)?.finishReason===`tool_calls`:t.finishReason===`tool_calls`}function Tu(e){let t={whenBusy:`queue`,drain:`fifo`,onOverflow:`reject`};if(!e)return t;if(typeof e==`string`)return{...t,whenBusy:e};if(typeof e==`function`)return{...t,strategy:e};let n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`ChatClient: queue.maxSize must be a non-negative integer`);return{whenBusy:e.whenBusy??`queue`,drain:e.drain??`fifo`,onOverflow:e.onOverflow??`reject`,...n===void 0?{}:{maxSize:n}}}function Eu(e){let t=e.at(-1)?.body,n=[];for(let t of e){if(typeof t.content!=`string`)break;n.push(t.content)}if(n.length===e.length)return{content:n.join(`
9
- `),...t===void 0?{}:{body:t}};let r=[],i;for(let t of e){if(typeof t.content==`string`){r.push({type:`text`,content:t.content});continue}typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content),i=fo(i,t.content.metadata)}return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function Du(e){if(!(typeof e!=`object`||!e||Array.isArray(e))&&!(!(`approved`in e)||typeof e.approved!=`boolean`))return e.approved}function Ou(e){let t=e;if(typeof t!=`object`||!t||!(`resumeState`in t))return;let n=t.resumeState;if(!(typeof n!=`object`||!n||!(`threadId`in n)||typeof n.threadId!=`string`||n.threadId.length===0||!(`runId`in n)||typeof n.runId!=`string`||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var ku=2e3,Au=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`REASONING_MESSAGE_CONTENT`,`TOOL_CALL_START`,`MESSAGES_SNAPSHOT`,`SUBAGENT_STARTED`]);function ju(e){return e.type===`REASONING_ENCRYPTED_VALUE`?e.subtype===`message`&&typeof e.encryptedValue==`string`&&e.encryptedValue.length>0:e.type===`STEP_FINISHED`?`signature`in e&&!!e.signature:Au.has(e.type)}function Mu(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...Mu(e.subagent.messages)));return t}function Nu(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var Pu=64;function Fu(e){if(Array.isArray(e))return e.map(Fu);if(e instanceof Date)return new Date(e.getTime());if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e))typeof r!=`function`&&(t[n]=Fu(r));return t}var Iu=class{processor;subagentHandles=new Map;stoppedSubagentIds=new Set;connection;uniqueId;threadId;persistor;clearedStreamTracker=new vu;currentRunId=null;lastResume=null;runParents=new Map;supersededInterruptRunIds=new Set;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status=`ready`;connectionStatus=`disconnected`;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;hydrationError;tailing=!1;rejoinRunId;cachesMessages;historyPageSize;hasOlderMessages=!1;olderMessagesCursor;knownServerMessageIds=new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){xu(e.interrupts),this.threadId=e.threadId||``,this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1,this.historyPageSize=e.history?.pageSize}else if(e.persistence){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new mu(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e)),this.historyPageSize=void 0}else this.historyPageSize=void 0;this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=Tu(e.queue);let n=Su(e);if(this.connectionDrainsOnSend=Cu(n),this.connection=Sl(n),this.clientToolsRef={current:new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??lu)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new tu({...e.tools===void 0?{}:{tools:e.tools},...e.interrupts===void 0?{}:{interrupts:e.interrupts},submit:e=>this.submitInterruptBatch(e),onChange:e=>this.notifyResumeStateChange(e)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);let r=this.persistor?.readInitial(),i=r instanceof Promise?void 0:r,a=i?i.messages:e.initialMessages,o=null;if(i?.resume){let e=i.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(o=e.resumeState.runId)}if(!o&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(o=t.resumeState.runId)}this.processor=new Bc({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.syncSubagentHandles(),this.persistor?.notifyMessagesChanged(e),this.callbacksRef.current.onMessagesChange(e),this.queueDevtoolsSnapshot()},onStreamStart:()=>{this.setStatus(`streaming`);let e=this.processor.getCurrentAssistantMessageId();if(!e)return;let t=this.processor.getMessages().find(t=>t.id===e);t&&(this.currentMessageId=t.id,this.events.messageAppended(t,this.currentStreamId||void 0))},onStreamEnd:e=>{this.callbacksRef.current.onFinish(e),this.setStatus(`ready`),this.resolveProcessing()},onError:e=>{this.reportStreamError(e)},onTextUpdate:(e,t)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,e,t)},onThinkingUpdate:(e,t)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,t,void 0)},onStructuredOutputChange:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=e.phase===`start`?`structured-output:started`:e.phase===`complete`?`structured-output:completed`:e.phase===`error`?`structured-output:errored`:`structured-output:updated`;this.currentMessageId=e.messageId,this.events.structuredOutputChanged(n,t,e.messageId,{status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning===void 0?{}:{reasoning:e.reasoning},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage},...e.delta===void 0?{}:{delta:e.delta}})},onToolCallStateChange:(e,t,n,r)=>{let i=this.processor.getMessages().find(t=>t.id===e)?.parts.find(e=>e.type===`tool-call`&&e.id===t)?.name||`unknown`;this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,e,t,i,n,r)},onToolCall:e=>{let t=(this.activeClientTools??this.clientToolsRef.current).get(e.toolName),n=t?.execute;if(n){let r=this.continuationGeneration,i=this.devtoolsBridge.getCurrentRunEventContext(),a=(async()=>{try{let a=this.activeClientTools===null?this.context:this.activeContext,o=await n(e.input,{toolCallId:e.toolCallId,context:a,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:o,state:`output-available`},t,r,i)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r,i)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,a)}},onApprovalRequest:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=this.findMessageIdForToolCall(e.toolCallId)??this.currentMessageId??``;this.events.approvalRequested(t,n,e.toolCallId,e.toolName,e.input,e.approvalId)},onCustomEvent:(e,t,n)=>{e===`memory:state`&&this.devtoolsBridge.recordMemoryState(t),(e===`compaction:started`||e===`compaction:state`||e===`compaction:ended`)&&this.devtoolsBridge.recordCompactionEvent(e,t),e===`skills:state`&&this.devtoolsBridge.recordSkillsState(t),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.syncSubagentHandles(),this.persistor?.hydrateAsync(r),this.rejoinRunId=o,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){let t=Ou(e);if(t===void 0){this.interruptManager.reset({source:`hydrate`});return}this.lastResume=t;let n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:`hydrate`});return}let r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},`hydrate`)}applyPersistedResume(e){this.applyResumeSnapshot(e);let t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){let e=this.connection.hydrate;if(!e||this.isLoading||this.abortController||this.disposed)return;let t=this.historyPageSize,n=t===void 0?void 0:{limit:t};(async()=>{let t,r=this.historyGeneration;try{t=await e(this.threadId,n)}catch(e){r===this.historyGeneration&&this.failHydration(e);return}if(r===this.historyGeneration&&!(this.disposed||!this.tailing)&&!(this.isLoading||this.abortController)){if(this.hydrationError&&this.error===this.hydrationError&&(this.setError(void 0),this.setStatus(`ready`)),this.hydrationError=void 0,this.applyHydrationPage(t.page),t.messages.length>0){let e=ao(t.messages);this.processor.setMessages(e),this.rememberServerMessageIds(e)}t.interrupts&&t.interrupts.pending.length>0&&(!t.activeRun?.runId||t.activeRun.runId===t.interrupts.runId)?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId)}})()}failHydration(e){if(this.disposed||!this.tailing||this.isLoading||this.abortController)return;let t=e instanceof Error?e:Error(String(e));t instanceof Gc&&this.byok?.request(t.provider,`missing`),t instanceof Kc&&t.reason===`locked`&&this.byok?.request(t.provider,`locked`),this.hydrationError=t,this.setStatus(`error`),this.setError(t),this.callbacksRef.current.onError(t)}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||=this.generateUniqueId(`thread`),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!==`RUN_ERROR`)return;let t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Yc(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Yc(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=Yc(e)??e.runId,n=`parentRunId`in e&&typeof e.parentRunId==`string`?e.parentRunId:void 0;n&&(this.runParents.set(t,n),this.supersededInterruptRunIds.has(t)&&this.markLineageAnswered(n)),this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t;let r=this.supersededInterruptRunIds.has(t)&&!this.isLoading;r||(this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0)),this.persistor&&this.connection.joinRun&&!this.lastResume&&!r&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t}),this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId)&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset());return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=Yc(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type===`RUN_ERROR`&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);let r=e.type===`RUN_FINISHED`&&wu(e);t?.resolveProcessing!==!1&&!r&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=Yc(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!wu(e)&&(e.type===`RUN_ERROR`||e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`)&&this.markLineageAnswered(t),e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;if(r&&this.supersededInterruptRunIds.has(r))return;this.lastResume={threadId:n??this.threadId,runId:r},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:r,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},`live`);return}let r=e.type===`RUN_ERROR`&&!t,i=!!(t&&this.lastResume?.runId===t),a=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),s=this.isLoading&&e.type===`RUN_FINISHED`&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`),l=!!(this.lastResume&&this.supersededInterruptRunIds.has(this.lastResume.runId));if(r||i||a||o||s||c||l){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange(`live`)}markLineageAnswered(e){let t=e,n=0;for(;t!==void 0&&n<Pu;){if(this.supersededInterruptRunIds.has(t))return;this.supersededInterruptRunIds.add(t),t=this.runParents.get(t),n++}}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e==`boolean`){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n===this.continuationGeneration?this.isLoading?new Promise((r,i)=>{this.queuePostStreamAction(async()=>{try{r(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(e){i(e)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){let t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=Du(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;let r=this.takeInterruptSubmissionFailure();if(r!==void 0)throw{errors:r.errors};if(!n)throw Error(`Interrupt continuation could not be started.`);this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){let e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(let n of e){let e=n.metadata?.[`tanstack:interruptBinding`];if(typeof e!=`object`||!e||!(`generation`in e)||typeof e.generation!=`number`||!Number.isInteger(e.generation)||e.generation<0||t!==void 0&&t!==e.generation)return 0;t=e.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}let t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){let t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??`useChat`,outputKind:e?.outputKind??`chat`,...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:e=>{this.processor.setMessages(e)},addToolResult:(e,t,n)=>{this.processor.addToolResult(e,t,n)},generateId:e=>this.generateUniqueId(e)}}getDevtoolsSnapshot(){return{messages:Fu(this.processor.getMessages()),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){let t=this.processor.getMessages();for(let n of t)if(n.parts.find(t=>t.type===`tool-call`&&t.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus(`ready`)}reportStreamError(e){let t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status===`submitted`||this.status===`streaming`)&&this.setStatus(`error`),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;let e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(e=>{e instanceof Error&&e.name!==`AbortError`&&(this.setConnectionStatus(`error`),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(e)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!==`error`&&this.setConnectionStatus(`disconnected`)))})}async consumeSubscription(e){let t=this.connection.subscribe(e),n=0;for await(let r of t){if(e.aborted)break;let t=performance.now();this.processIncomingChunk(r),n+=performance.now()-t,!(n<yu)&&(n=0,!(typeof document<`u`&&document.hidden)&&await bu())}}resumeInFlightRun(e){let t=this.connection.joinRun;if(!t)return;let n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},ku);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&ju(a)&&(r=!0,this.dropTrailingInFlightAssistant()),this.processIncomingChunk(a)}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(e){let t=e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`);!i&&!t&&(a=!0),i&&!t&&this.reportStreamError(e instanceof Error?e:Error(String(e)))}finally{clearTimeout(o),!i&&a&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status===`streaming`&&this.setStatus(`ready`),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){let e=this.processor.getMessages(),t=e[e.length-1];t&&t.role===`assistant`&&this.processor.setMessages(e.slice(0,-1))}processIncomingChunk(e){if(e=xc(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=Q(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(t)?t:[]}}if(this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(Yc(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e);let t=Nu(e);if(t&&e.type===mo.SUBAGENT_STARTED&&this.stoppedSubagentIds.delete(t),t&&this.stoppedSubagentIds.has(t)){this.updateRunLifecycle(e),this.resolveJoinedRun(e);return}this.processor.processChunk(e),this.syncSubagentHandles(),this.updateRunLifecycle(e),this.observeInterruptState(e),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=Q(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=Yc(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId==`string`&&e.threadId!==t.threadId?!1:n.every(e=>typeof e!=`object`||!e||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation)}resolveJoinedRun(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Yc(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e==`string`&&!e.trim())return;if(this.hasPendingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let r={...t,...n?.body};if(this.isSendBusy()){let{action:t,id:i}=this.decideWhenBusy(e,n);if(t===`drop`)return;if(t===`queue`){this.enqueueMessage(e,r,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,r)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?`streaming`:this.messageQueueDraining?`draining`:`sendInFlight`}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{let n=this.normalizeMessageInput(e);this.pendingMessageBody=t;let r=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){let n=this.generateUniqueId(`queued`);if(t?.whenBusy)return{action:t.whenBusy,id:n};let{strategy:r,whenBusy:i}=this.queueConfig;if(r){let{action:t}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:t,id:n}}return{action:i,id:n}}enqueueMessage(e,t,n){let{maxSize:r,onOverflow:i}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(i===`reject`||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId(`queued`),content:e,createdAt:Date.now(),...t===void 0?{}:{body:t}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e==`string`?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata===void 0?{}:{metadata:e.metadata}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let t=$s(e,ec);if(t.role===`system`)return;let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;let t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;let i=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(i),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=i,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus(`submitted`),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;let a=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,s=null,c=!1;try{let l=this.messagesForSend(this.processor.getMessages()),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId(`stream`),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();let p=this.waitForProcessing(),m;if(this.byok){let e=iu(this.byokProvider,f.provider,ru(this.byok));m=await au(this.byok,e)}let h={threadId:t??this.threadId,runId:i,...n===null?{}:{parentRunId:n},clientTools:Array.from(u.values()).map(e=>({name:e.name,description:e.description,parameters:e.inputSchema?Po(e.inputSchema):{type:`object`}})),forwardedProps:{...f},...r?{resume:r}:{},...m?{headers:m}:{}};if(this.devtoolsBridge.beginRun(h.runId,h.threadId),s=h.runId,this.devtoolsBridge.emitRunLifecycle(`run:created`,h.runId,`created`),this.devtoolsBridge.emitRunLifecycle(`run:started`,h.runId,`started`),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,f,a,h),e!==this.streamGeneration||a.aborted||(this.connectionDrainsOnSend&&this.resolveProcessing(),await p,e!==this.streamGeneration))return!1;if(this.status===`error`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(t){let n=t instanceof Error?t:Error(String(t));if(n.name===`AbortError`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`),c=!0),!1;if(n instanceof Gc&&this.byok?.request(n.provider,`missing`),n instanceof Kc&&n.reason===`locked`&&this.byok?.request(n.provider,`locked`),e===this.streamGeneration&&(this.reportStreamError(n),s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,{error:n.message}),c=!0)),e===this.streamGeneration&&(n instanceof Gc||n instanceof Kc||n instanceof qc))throw n}finally{e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,s&&!c&&(o?this.devtoolsBridge.emitRunLifecycle(`run:completed`,s,`completed`):a.aborted&&this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`)),await this.drainPostStreamActions(),o?(this.rememberProcessorMessageIds(),this.status!==`ready`&&this.setStatus(`ready`),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return o}subscribe(e){let t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus(`connecting`),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`)}async reload(){let e=this.processor.getMessages();if(e.length===0)return;let t=e.findLastIndex(e=>e.role===`user`);t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){let e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.resetHistoryPaging(),this.discardPendingSends(),this.persistor?.remove(),this.stoppedSubagentIds.clear(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){let t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,r){if(e.state!==`output-error`)try{let n=t?.outputSchema&&ko(t.outputSchema)?await this.validateClientToolOutput(t,e.output):e.output;this.interruptManager.getDescriptors().some(t=>t.toolCallId===e.toolCallId)&&(n=$(n)),e={...e,output:n}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,r),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!(e.state===`output-error`?this.interruptManager.resolveClientToolError(e.toolCallId,e.errorText||`Tool execution failed`):this.interruptManager.resolveClientToolOutput(e.toolCallId,e.output)))){if(this.isLoading){this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}async validateClientToolOutput(e,t){let n=await Fo(e.outputSchema,t);if(!n.success)throw Error(n.issues.map(e=>e.message).join(`, `));return n.data}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;let t=this.processor.getMessages(),n;for(let r of t){let t=r.parts.find(t=>t.type===`tool-call`&&t.approval?.id===e.id);if(t){n=t.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){let t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;let e=this.processor.getMessages().findLast(e=>e.role===`assistant`);return!e||!e.parts.some(e=>e.type===`tool-call`)?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}getSubagents(){return[...this.subagentHandles.values()]}devtoolsSnapshotQueued=!1;queueDevtoolsSnapshot(){this.devtoolsSnapshotQueued||(this.devtoolsSnapshotQueued=!0,queueMicrotask(()=>{this.devtoolsSnapshotQueued=!1,this.devtoolsBridge.emitSnapshot()}))}syncSubagentHandles(){let e=Mu(this.processor.getMessages()),t=new Set(e.map(e=>e.subagent.id));for(let e of this.subagentHandles.keys())t.has(e)||this.subagentHandles.delete(e);for(let t of e){let e=t.subagent.id,n=this.subagentHandles.get(e);if(n){if(t.subagent===n)continue;let{stop:e}=n;for(let e of Object.keys(n))Reflect.deleteProperty(n,e);Object.assign(n,t.subagent,{stop:e}),t.subagent=n;continue}let r={...t.subagent,stop:()=>{this.stopSubagent(e)}};this.subagentHandles.set(e,r),t.subagent=r}}stopSubagent(e){let t=this.subagentHandles.get(e);!t||t.status!==`running`||(this.stoppedSubagentIds.add(e),this.processor.processChunk({type:mo.SUBAGENT_ERROR,subagentRunId:e,message:`Stopped`,timestamp:Date.now()}),this.syncSubagentHandles(),t.status=`error`,t.error={message:`Stopped`},this.abortController?.abort())}getHasOlderMessages(){return this.hasOlderMessages}async loadOlderMessages(){let e=this.connection.hydrate;if(e===void 0||this.disposed||!this.hasOlderMessages)return;let t=this.olderMessagesCursor;if(t===void 0||this.loadOlderMessagesInFlight)return;let n={before:t};this.historyPageSize!==void 0&&(n.limit=this.historyPageSize),this.loadOlderMessagesInFlight=!0;let r=this.historyGeneration;try{let t=await e(this.threadId,n);if(this.disposed||r!==this.historyGeneration)return;let i=ao(t.messages);if(i.length===0)throw Error(`Older page was empty`);this.applyHydrationPage(t.page),this.processor.prependMessages(i),this.rememberServerMessageIds(i)}finally{this.loadOlderMessagesInFlight=!1}}resetHistoryPaging(){this.hasOlderMessages=!1,this.olderMessagesCursor=void 0,this.knownServerMessageIds.clear(),this.historyGeneration++}applyHydrationPage(e){if(e?.truncated===!0){this.hasOlderMessages=!0,this.olderMessagesCursor=e.cursor;return}this.hasOlderMessages=!1,this.olderMessagesCursor=void 0}rememberServerMessageIds(e){let t=e.map(e=>e.id);for(let e of t)this.knownServerMessageIds.add(e)}rememberProcessorMessageIds(){this.historyPageSize!==void 0&&this.rememberServerMessageIds(this.processor.getMessages())}messagesForSend(e){if(this.historyPageSize===void 0)return e;let t=[];for(let n of e)this.knownServerMessageIds.has(n.id)||t.push(n);if(t.length>0)return t;let n=e.findLastIndex(e=>e.role===`user`);return n===-1?[]:e.slice(n)}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain===`batch`){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.splice(0);this.emitQueueChange();let t=Eu(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){let t=this.messageQueue.findIndex(t=>t.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){let t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`);let n=Su({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=Cu(n),this.connection=Sl(n),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),`context`in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=Tu(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function Lu(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?Po(e):{type:`object`}:e:{type:`object`,properties:{}}}async function Ru(e,t){let n=await Fo(e,t);return n.success?n.data??{}:null}function zu(e,t,n,r){return[...Object.keys(e).length>0?[Bu(e,n)]:[],Vu(),...Hu(t,r)]}function Bu(e,t){return Sc({name:l,description:`Render one of the host application's own UI widgets inline in the conversation. The widget appears in the transcript at the point of the call, so prefer it over describing the same information in text. Available widgets:
10
- `+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(Lu(n))}`).join(`
11
- `),inputSchema:{type:`object`,properties:{widget:{type:`string`,enum:Object.keys(e),description:`Name of the widget to render.`},props:{type:`object`,description:`Props for the widget, matching its props schema.`}},required:[`widget`]}}).client((e,n)=>t(e,n?.toolCallId??``))}function Vu(){return Sc({name:Qn,description:`Ask the user a short structured questionnaire rendered inline in the chat. Use it when the next step genuinely depends on their choices instead of asking in prose. The call stays pending until the user submits; their answers arrive as the tool output. Skipped optional questions come back with an empty answers array. An output with skipped: true means the user dismissed the questionnaire by continuing the conversation instead — do not re-ask; address their next message.`,inputSchema:{type:`object`,properties:{items:{type:`array`,minItems:1,description:`Questions shown one at a time, in order.`,items:{type:`object`,properties:{name:{type:`string`,description:`Unique key identifying the question.`},title:{type:`string`,description:`The question itself.`},description:{type:`string`,description:`Optional helper text.`},required:{type:`boolean`,description:`Whether an answer is mandatory.`},multiple:{type:`boolean`,description:`Whether several choices may be selected.`},choices:{type:`array`,minItems:1,items:{type:`object`,properties:{value:{type:`string`},label:{type:`string`},description:{type:`string`}},required:[`value`,`label`]}},input:{type:`object`,description:`Optional free-form alternative to the fixed choices.`,properties:{label:{type:`string`},placeholder:{type:`string`}},required:[`label`,`placeholder`]}},required:[`name`,`title`,`choices`]}}},required:[`items`]}}).client()}function Hu(e,t){return Object.entries(e).map(([e,n])=>Sc({name:e,description:n.description,inputSchema:Lu(n.parameters),...n.metadata?{metadata:n.metadata}:{}}).client(async r=>{t?.(`tool`,`executing host tool "${e}"`,{input:r});let i=await Ru(n.parameters,r??{});if(i==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:r}),Error(`Input for tool "${e}" failed schema validation`);try{let r=await n.execute(i);try{So(r)}catch{throw Error(`Tool "${e}" ran, but its result is not JSON-compatible. Its changes may already be applied. Read current state before retrying. Return plain JSON values and omit undefined fields.`)}return t?.(`tool`,`host tool "${e}" returned`,{output:r}),r}catch(n){throw t?.(`error`,`host tool "${e}" threw`,{error:n}),n}}))}function Uu(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function Wu(e,n=!1){let r={...e},i=t(r.debug),a=new Set,o={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,sandbox:{files:[],commands:[]},thread:void 0,threadLoading:!1,threadLoadFailed:!1,messagesCursor:void 0,olderMessagesLoading:!1,unsentMessage:void 0,activeToolCallIds:[],pendingInteractions:[]},s=e=>{o={...o,...e};for(let e of a)e()},c=ut({apiUrl:r.apiUrl,scope:`tenant`,fetchAstralBeamToken:r.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),l,u,d,f=!1,p=0,m=0,h=0,g=Promise.resolve(),_=new AbortController,v,y=!1,b=[],x=hn(),S,C=!1,w=new Map,T=()=>{!S||S.accepted||(S.accepted=!0,o.thread&&s({thread:{...o.thread,hasMessages:!0}}),S.callbacks?.onAccepted?.())},E=new Set,D=new Map,O=new Map,k=new Map,j=new Map,M=e=>{let t=D.get(e);return t?`live:${t}:${e}`:e},P=e=>{let t=new Map;for(let n of e.pending_interactions){let e=`live:${n.source_message_id}:${n.tool_call_id}`,r=Ze(n.source_message_id,n.source_part_id,n.response_target_id),i=k.get(e)??k.get(r);i&&(t.set(r,i),D.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}k.clear();for(let[e,n]of t)k.set(e,n)},F=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));s({error:t,status:`error`}),r.streamCallbacks?.onError?.(t)},I=async()=>{let e=p,t=await qt(c);if(e!==p)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:c.apiUrl,astralBeamToken:t,cache:`no-store`,signal:AbortSignal.any([_.signal,c.session.abortController.signal]),fetchClient:(e,t)=>sn({...c,input:e,init:t})}},ee=0,te,L=async()=>{let e=++ee,t=p;if(o.thread?.agentId===null){s({capabilities:{attachments:!1}});return}let n=o.thread?o.thread.agentId:r.agentId;try{let r=await I();if(e!==ee||t!==p)return;let a=await A(n?{agentId:n}:{},r);if(e!==ee||t!==p)return;let o=a.capabilities?.attachments!==!1;s({capabilities:{attachments:o}}),i?.(`mount`,`agent capabilities resolved`,{attachments:o})}catch(e){i?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},R=new Map,z=new Set,B=new Set,V=()=>{for(let e of R.values())e();R.clear(),z.clear(),B.clear()},ie=async(e,t)=>{let n=p,i=r.widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],s=await Ru(a?.parameters,e.props??{});if(n!==p||o.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==r.widgets?.[e.widget])return ie(e,t);if(s==null)throw Error(`Props for widget "${e.widget}" failed validation`);let c=r.onRenderWidget;if(!c)return{widget:e.widget,rendered:!1};R.get(t)?.(),R.delete(t);let l,u=c({widget:e.widget,props:s,toolCallId:t,release:()=>{R.get(t)===l&&R.delete(t)}});return u&&(l=u,R.set(t,u)),z.add(t),{widget:e.widget,rendered:!0}},ae=e=>{if(o.thread?.role===`viewer`)return;let t=new Map;for(let e of o.messages)for(let n of e.parts){if(n.type!==`tool-call`||n.name!==`render_widget`)continue;let r=n;r.widgetRenderId&&(t.set(Ze(e.id,n.id),r.widgetRenderId),r.applicationPartId&&t.set(Ze(e.id,r.applicationPartId,r.responseTargetId),r.widgetRenderId))}for(let n of e)for(let e of n.parts){if(e.type!==`tool-call`||e.name!==`render_widget`||e.state!==`complete`||!e.input)continue;let a=e,s=a.upstreamToolCallId,c=a.widgetRenderId??t.get(Ze(n.id,e.id))??(a.applicationPartId?t.get(Ze(n.id,a.applicationPartId,a.responseTargetId)):void 0)??(s&&D.get(s)===n.id&&z.has(s)?s:e.id);if(a.widgetRenderId=c,z.has(c)||B.has(c))continue;B.add(c);let l=p,{widgets:u,onRenderWidget:d}=r;ie(e.input,c).catch(e=>i?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{l===p&&(B.delete(c),(u!==r.widgets||d!==r.onRenderWidget)&&ae(o.messages))})}},oe=()=>zu(r.widgets??{},r.tools??{},ie,i).map(e=>{if(!e.execute)return e;let t=e.execute;return{...e,execute:async(e,n)=>{let r=n?.toolCallId;if(!r||!E.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=k,a=M(r),o=d,s=c.apiUrl;try{let r=await t(e,n);return d===o&&c.apiUrl===s&&i.set(a,{outcome:`succeeded`,output:r??null}),r}catch(e){throw d===o&&c.apiUrl===s&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)}}),e}}}}),H=()=>{let e=oe(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return Uu(o.agentTools,t)||s({agentTools:t}),e},se=()=>r.debug?{debug:!0}:{},ce=async(e,t)=>{let n=o.thread;if(!n||typeof e.body!=`string`)throw Error(`Open a conversation before sending.`);let r=p,i=JSON.parse(e.body),a=mn(),c,l=i.messages.at(-1)?.role===`user`?S:void 0,u=l?.tools!==void 0;if(l)c={...i,threadId:n.id,resume:void 0,parentRunId:void 0,messages:[i.messages.at(-1)],tools:l.tools??=i.tools,forwardedProps:{...i.forwardedProps,clientId:x}};else{de();let e=await Zt(n.id,t,void 0,D);if(r!==p)throw new DOMException(`Conversation changed`,`AbortError`);s({thread:bn(e.thread,e.messages.length>0)}),P(e);let o=e.pendingInteractions.filter(e=>k.has(M(e.toolCallId))),l=o.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??o[0],u=e.pendingInteractions.flatMap(e=>{let t=k.get(M(e.toolCallId));return t&&e.sourceMessageId===l?.sourceMessageId?[{source_message_id:e.sourceMessageId,source_part_id:e.sourcePartId,response_target_id:e.responseTargetId,...t}]:[]});if(u.length===0)return new Response(``,{headers:{"Content-Type":`text/event-stream`}});a=ne(n.id),c={client_id:x,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:u}}E.clear(),s({activeToolCallIds:[]});let d=new Headers(e.headers);l&&d.set(`Idempotency-Key`,l.key);let f=await In(a,{...t,...e,headers:d,body:JSON.stringify(c)}).catch(e=>{throw l&&!u&&Yn(e)&&(e.status===400||e.status===413||e.status===429)&&delete l.tools,e});if(r!==p)throw new DOMException(`Conversation changed`,`AbortError`);if(f.headers.get(`Content-Type`)?.includes(`application/json`)){let e=await f.json();if(r!==p)throw new DOMException(`Conversation changed`,`AbortError`);return s({thread:{...o.thread,version:e.thread_version}}),l&&T(),new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return f},le=wl(()=>rt(mn(),c.apiUrl),async()=>{let e=d,t=await qt(c);if(e!==void 0&&e!==d)throw new DOMException(`Identity changed`,`AbortError`);return{fetchClient:(e,n)=>{let r={apiUrl:c.apiUrl,astralBeamToken:t,...n?.signal?{signal:n.signal}:{},cache:`no-store`,fetchClient:(e,t)=>sn({...c,input:e,init:t})};return ce(n??{},r)}}}),U=le.connect;le.connect=async function*(...e){try{for await(let t of U(...e)){if(t.type===mo.TOOL_CALL_START&&t.parentMessageId&&D.set(t.toolCallId,t.parentMessageId),t.type!==mo.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=O.get(t.id),e&&t.toolCalls?{...t,toolCalls:t.toolCalls.map(t=>({...t,id:e?.get(t.id)??t.id}))}:t):t.role===`tool`?{...t,toolCallId:e?.get(t.toolCallId)??t.toolCallId}:(e=void 0,t))}}}catch(e){throw e instanceof Error&&Yn(e.cause)?e.cause:e}};let W=(e=o.thread?.id)=>{let t=p,n={...le};delete n.hydrate,e&&(n.hydrate=(n,r)=>{let i=++h;r?.before||s({threadLoading:!0});let c=(async()=>{let n=await Zt(e,await I(),r?.before,D);for(;r?.before&&n.messages.every(e=>e.role===`tool`)&&n.page_after;){let t=await Zt(e,await I(),n.page_after,D);n={...t,messages:[...t.messages,...n.messages]}}if(t!==p||i!==h)throw new DOMException(`Conversation changed`,`AbortError`);P(n),b=r?.before?[...n.messages,...b]:n.messages;let c=new Set(n.messages.map(e=>e.id)),l=jt(b,n.pendingInteractions,D).filter(e=>c.has(e.id));n.thread.role===`viewer`&&V();let u=o.thread?.agentId!==n.thread.agent_id;return s({thread:bn(n.thread,n.messages.length>0),messagesCursor:n.page_after??void 0,pendingInteractions:n.pendingInteractions,threadLoadFailed:!1}),ae(l),!r?.before&&u&&L(),!r?.before&&l.length===0&&a.setMessagesManually([]),{messages:l,activeRun:null,interrupts:null,page:n.page_after?{truncated:!0,cursor:n.page_after}:{truncated:!1}}})();if(!r?.before){g=c;let e=e=>queueMicrotask(()=>{t===p&&i===h&&s({threadLoading:!1,threadLoadFailed:e})});c.then(()=>e(!1),()=>e(!0))}return c});let a=new Iu({connection:n,threadId:e??x,persistence:!0,history:{pageSize:100},queue:`drop`,tools:H(),forwardedProps:se(),onMessagesChange:e=>{G!==a||t!==p||(ae(e),s({messages:e,sandbox:Qt(e),error:a.getError()}))},onStatusChange:e=>{G===a&&t===p&&s({status:e,error:a.getError()})},onInterruptStateChange:e=>{G===a&&i?.(`tool`,`interrupt state changed`,e)},onCustomEvent:(e,t)=>{if(G!==a)return;if(e===`astralbeam_thread`){let e=t;if(o.thread?.id===e.threadId){if(e.acceptedMessageId&&T(),e.saved)for(let t of e.executableToolCallIds??[])E.has(t)||k.delete(M(t)),E.add(t);s({thread:{...o.thread,version:e.version},activeToolCallIds:[...E],...e.acceptedMessageId?{unsentMessage:void 0}:{}})}return}let n=t?.state;if(e===`astralbeam.sandbox.status`&&(n===`starting`||n===`ready`||n===`error`)){i?.(`sandbox`,`sandbox ${n}`),s({sandboxStatus:n});return}i?.(`stream`,`custom event "${e}"`,t)},onChunk:e=>{G===a&&r.streamCallbacks?.onChunk?.(e)},onResponse:e=>{G===a&&r.streamCallbacks?.onResponse?.(e)},onFinish:e=>{G===a&&r.streamCallbacks?.onFinish?.(e)},onError:e=>{G===a&&r.streamCallbacks?.onError?.(e)}});return a},G=W(),ue=(e=o.thread?.id)=>{G.stop();let t=G;t.detach(),E.clear(),D.clear(),s({activeToolCallIds:[]}),G=W(e),f&&G.attach(),t.dispose()},de=()=>{O.clear(),G.setMessagesManually(o.messages.map(e=>{let t=new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`)return n;let r=n,i=r.upstreamToolCallId??n.id;if(D.get(i)===e.id&&!re(n))return n;let a=Ze(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`&&D.get(i)===e.id?{widgetRenderId:r.widgetRenderId??n.id}:{}}});return t.size&&O.set(e.id,t),{...e,parts:n}}))},fe=e=>{let t=o.thread?.id;t&&(S&&!S.accepted?w.set(t,S):w.delete(t),j.set(t,k)),p++,h++,C=!1,_.abort(),_=new AbortController,S=void 0,k=j.get(e??``)??new Map,O.clear(),b=[],V(),s({thread:void 0,messages:[],unsentMessage:void 0,error:void 0,status:`ready`,sandbox:{files:[],commands:[]},sandboxStatus:void 0,pendingInteractions:[],threadLoadFailed:!1,messagesCursor:void 0,olderMessagesLoading:!1}),ue(e)},pe=async(e,t=!1)=>{t||m++,fe(e);let n=p;s({threadLoading:!0});try{if(S=w.get(e),s({unsentMessage:S?.content}),f||G.attach(),await g,n!==p)return;v&&tn(v,e)}catch(e){if(n===p){if(t&&(r.threadId===void 0||r.threadId===`auto`)&&Yn(e)&&e.status===404){me();return}s({threadLoadFailed:!0}),F(e)}}finally{n===p&&s({threadLoading:!1})}},me=()=>{m++,fe(),s({threadLoading:!1}),f&&L(),v?tn(v,null):y=!0},he=(e=!1)=>{let t=r.threadId;if(t===void 0||t===`auto`){if(!v)return;t=tn(v)}t&&t!==`new`?pe(t,e):e||me()},ge=async()=>{if(o.thread)return;let e=p,t=await I(),n=await N(r.agentId?{agent_id:r.agentId}:{},t);if(e!==p)throw new DOMException(`Conversation changed`,`AbortError`);let i=bn(n,!1);s({thread:i}),ue(),await g,L(),v&&tn(v,i.id)},_e=async(e=!1,t=!0)=>{if(!o.thread?.id)return;let n=p,r=o.error;s({threadLoading:!0,olderMessagesLoading:!1});try{if(t?ue():(G.detach(),G.attach()),await g,n!==p)return;e&&r&&s({error:r,status:`error`})}catch(e){if(n===p){if(Yn(e)&&e.status===404){me();return}F(e)}}finally{n===p&&s({threadLoading:!1})}},ve=async()=>{if(!G.getHasOlderMessages()||o.olderMessagesLoading||o.threadLoading||C)return;let e=p;s({olderMessagesLoading:!0});try{await G.loadOlderMessages()}catch(t){e===p&&F(t)}finally{e===p&&s({olderMessagesLoading:!1})}},ye=async e=>{let t=o.thread;if(!t||t.role!==`manager`)return!1;let n=p;try{let r=await Dn(t.id,{title:e,expected_version:t.version},await I());if(n!==p)return!1;let i=bn(r,t.hasMessages);return s({thread:i,error:G.getError(),status:G.getStatus()}),!0}catch(e){return n===p&&F(e),!1}},be=async(e=o.thread)=>{if(!e||e.role!==`manager`)return!1;let t=p;try{return await Ne(e.id,{expected_version:String(e.version)},await I()),t===p&&o.thread?.id===e.id&&me(),!0}catch(e){return t===p&&F(e),!1}},xe=async e=>{let t=p;if(C||G.getIsLoading()){F(Error(`Wait for this client's current request to finish before responding.`));return}let n=kn(c),r=o.pendingInteractions.find(t=>t.toolCallId===e.toolCallId),i=!(`tool`in e)&&r&&(o.thread?.role===`manager`||n.status===`ready`&&r.targetTenantUserId===n.currentUser.user.id),a=`tool`in e&&e.tool===`ask_questionnaire`&&n.status===`ready`&&r?.targetTenantUserId===n.currentUser.user.id;if(o.thread?.role===`viewer`||!E.has(e.toolCallId)&&!a&&!i&&!k.has(M(e.toolCallId))){F(Error(`This tool call belongs to another session and cannot be executed here.`));return}if(i&&!k.has(M(e.toolCallId)))k.set(M(e.toolCallId),{outcome:`unknown`,output:null});else if(!k.has(M(e.toolCallId))&&`tool`in e){let t=e.output;k.set(M(e.toolCallId),{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}if(de(),r&&(!(`tool`in e)||e.toolCallId===Ze(r.sourceMessageId,r.sourcePartId,r.responseTargetId))){if(ue(),await g,t!==p)return;s({threadLoading:!1}),await G.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(k.get(M(e.toolCallId)))})}else`tool`in e&&await G.addToolResult(e);t===p&&await _e(G.getError()!==void 0,!1)},Se=e=>xe({toolCallId:e}),Ce=async(e,t)=>{let n=m;try{await qt(c)}catch(t){if(n!==m)return;s({unsentMessage:e}),F(t);return}if(n!==m)return;if(C||o.threadLoading||o.status===`streaming`){F(Error(`Wait for this client's current request to finish before sending.`));return}if(o.threadLoadFailed){F(Error(`Reopen this conversation or start a new one before sending.`));return}let r=S!==void 0&&JSON.stringify(S.content)===JSON.stringify(e),i=S?.tools!==void 0&&!S.accepted?S:void 0,a=i!==void 0&&r;if(o.thread?.agentId===null&&!a){F(Error(`This conversation’s agent is unavailable. Start a new conversation to continue.`));return}if(o.thread?.role===`viewer`&&!a){F(Error(`You have read-only access to this conversation.`));return}if(i&&!r){s({unsentMessage:i.content}),F(Error(`The previous message’s acceptance is unconfirmed. Retry that message before sending different text, or start a new conversation.`));return}let l=p;h++,s({olderMessagesLoading:!1}),C=!0,(!S||S.accepted||!r)&&(S={content:e,accepted:!1,key:hn(),callbacks:t},G.stop(),E.clear(),de(),D.clear(),s({activeToolCallIds:[]})),S.callbacks??=t,s({unsentMessage:e,error:void 0,status:`submitted`});try{if(await ge(),l!==p||(S.callbacks?.onThreadReady?.(o.thread.id),l!==p)||(de(),await G.sendMessage(e),l!==p))return;let t=G.getError()!==void 0;S?.accepted&&(S=void 0,s({unsentMessage:void 0})),await _e(t,!1)}catch(e){l===p&&F(e)}finally{l===p&&(C=!1)}},we=()=>{let e=kn(c);if(e.status===`ready`){let t=Ht(e.currentUser);d!==void 0&&d!==t&&(m++,w.clear(),j.clear(),k.clear(),S=void 0),d=t;let n=`astralbeam:thread:${r.apiUrl??`https://astralbeam.ai/api`}:${t}`;v!==n&&(fe(),v=n,y?(tn(n,null),y=!1):he(!0)),te!==t&&(te=t,L())}s({auth:e})},Te=()=>{f||(f=!0,G.attach(),_.signal.aborted&&(_=new AbortController),u=Ct(c,we),we(),l=ot(c))};return n||Te(),{start:Te,getState:()=>o,subscribe:e=>(a.add(e),()=>a.delete(e)),updateOptions:e=>{let n=r.agentId,a=r.apiUrl,l=r.threadId,{widgets:u,onRenderWidget:d}=r;r={...r,...e},i=t(r.debug),qe(c,{apiUrl:r.apiUrl,fetchAstralBeamToken:r.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),c.debug=i,G.updateOptions({tools:H(),forwardedProps:se()}),r.apiUrl===a?r.threadId!==l&&he():(m++,w.clear(),j.clear(),k.clear(),S=void 0,fe(),v=void 0,s({threadLoading:!1}),we()),(u!==r.widgets||d!==r.onRenderWidget)&&ae(o.messages),f&&(r.agentId!==n||r.apiUrl!==a)&&L()},sendMessage:Ce,addToolResult:xe,stop:()=>G.stop(),retryAuthentication:()=>{qt({...c,force:!0}).catch(()=>void 0)},reload:async()=>{let e=p;if(await _e(),e!==p||o.error)return;let t=new Set;for(;e===p;){let e=o.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&k.has(M(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await xe({toolCallId:e.toolCallId}),o.error))return}},searchThreads:async(e=``,t,n)=>{let r=await I(),i=await Be({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>bn(e)),page_after:i.page_after}},openThread:pe,renameThread:ye,deleteThread:be,refreshThread:_e,loadOlderMessages:ve,getAttachment:async(e,t)=>{let n=o.thread;if(!n)throw Error(`Open a conversation before downloading attachments.`);return(await Le(n.id,e,t,await I())).blob()},abandonToolCall:Se,reset:()=>{i?.(`status`,`conversation reset`),me()},dispose:()=>{G.detach(),V(),G.stop(),_.abort(),p++,v=void 0,ee++,te=void 0,l?.(),u?.(),vt(c),f=!1,queueMicrotask(()=>{f||G.dispose()}),a.clear()}}}const Gu=[`header`,`headerActions`,`empty`,`composerActions`];function Ku(e){return`${w}${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}function qu(e,t,n){let[r,i]=(0,Y.useState)(new Set),a=(0,Y.useRef)(new Map);return(0,Y.useEffect)(()=>{for(let r of Gu){let i=e?.[r],o=a.current.get(r);if(o?.renderer===i||(o&&(o.cleanup?.(),o.container.remove(),a.current.delete(r),n?.(`mount`,`host slot "${r}" disposed`)),!i))continue;let s=document.createElement(`div`);s.slot=Ku(r),t.append(s);let c=i(s);a.current.set(r,{renderer:i,container:s,cleanup:c??void 0}),n?.(`mount`,`host slot "${r}" rendered`)}i(e=>{let t=new Set(a.current.keys());return t.size===e.size&&[...t].every(t=>e.has(t))?e:t})},[e,t,n]),(0,Y.useEffect)(()=>()=>{for(let e of a.current.values())e.cleanup?.(),e.container.remove();a.current.clear()},[]),r}function Ju(e,t,n){let[r,i]=(0,Y.useState)(new Map),a=(0,Y.useRef)(new Map),o=(0,Y.useCallback)(e=>{let t=[];for(let[n,r]of a.current)e(r)&&(r.cleanup?.(),r.container.remove(),r.release(),a.current.delete(n),t.push(le(n)));return t},[]),s=(0,Y.useCallback)(e=>{let t=o(e);return t.length>0&&i(e=>{let n=new Map(e);for(let e of t)n.delete(e);return n}),t.length},[o]),c=(0,Y.useRef)(!0);(0,Y.useEffect)(()=>(c.current=!0,()=>{c.current=!1,s(()=>!0)}),[s]);let l=(0,Y.useRef)(e),u=(0,Y.useRef)(n);(0,Y.useEffect)(()=>{l.current=e,u.current=n});let d=(0,Y.useCallback)(({widget:e,props:n,toolCallId:r,release:o})=>{let d=u.current;d?.(`widget`,`agent requested widget "${e}"`,{toolCallId:r,props:n});let f=Ft(l.current,e);if(!f)throw Error(`Unknown widget "${e}"`);if(!c.current)throw Error(`The chat is no longer mounted`);let p=le(r),m=document.createElement(`div`);m.slot=p,t.append(m);let h;try{h=f.render(n,m)}catch(e){throw m.remove(),e}let g={widget:e,container:m,cleanup:h??void 0,release:o};a.current.set(r,g);let _=s(()=>a.current.size>20);return _>0&&d?.(`widget`,`evicted ${_} widget render(s) past the active cap`,{cap:20}),i(t=>new Map(t).set(p,e)),d?.(`widget`,`widget "${e}" rendered`,{slotName:p}),()=>s(e=>e===g)},[t,s]),[f,p]=(0,Y.useState)(e);return f!==e&&(p(e),i(t=>{let n=new Map([...t].filter(([,t])=>Ft(e,t)));return n.size===t.size?t:n})),(0,Y.useEffect)(()=>{let t=o(t=>!Ft(e,t.widget)).length;t>0&&n?.(`widget`,`disposed ${t} render(s) of widgets no longer registered`)},[e,n,o]),{activeSlots:r,renderWidget:d}}const Yu={},Xu={text:``,attachments:[]};function Zu({options:e,host:n,controller:r}){let i=e.widgets??Yu,a=(0,Y.useMemo)(()=>t(e.debug),[e.debug]),{activeSlots:o,renderWidget:s}=Ju(i,n,a),c=qu(e.slots,n,a),l=(0,Y.useMemo)(()=>Ya(a),[a]),u=(0,Y.useMemo)(()=>({agentId:e.agentId,threadId:e.threadId,apiUrl:e.apiUrl,fetchAstralBeamToken:e.fetchAstralBeamToken,tools:e.tools,widgets:i,onRenderWidget:s,streamCallbacks:l,debug:e.debug}),[e.agentId,e.threadId,e.apiUrl,e.fetchAstralBeamToken,e.tools,e.debug,i,s,l]),[d]=(0,Y.useState)(()=>Wu(u,!0));(0,Y.useEffect)(()=>{d.updateOptions(u)},[d,u]),(0,Y.useEffect)(()=>(d.start(),()=>d.dispose()),[d]);let f=(0,Y.useSyncExternalStore)(d.subscribe,d.getState,d.getState),{messages:m,status:h,error:g,auth:_,capabilities:v,sandbox:y,sandboxStatus:b,agentTools:S}=f,C=(0,Y.useMemo)(()=>new Set(S.map(e=>e.name)),[S]),w=(0,Y.useMemo)(()=>{let e=new Set(f.activeToolCallIds);if(_.status===`ready`&&f.thread?.role!==`viewer`)for(let t of f.pendingInteractions)t.targetTenantUserId===_.currentUser.user.id&&m.some(e=>e.parts.some(e=>e.type===`tool-call`&&e.id===t.toolCallId&&e.name===`ask_questionnaire`))&&e.add(t.toolCallId);return e},[f.activeToolCallIds,f.pendingInteractions,f.thread?.role,_,m]),T=(0,Y.useMemo)(()=>{let e={};for(let t of S)t.title!==void 0&&(e[t.name]=t.title);return e},[S]);(0,Y.useEffect)(()=>{a?.(`mount`,`tool set declared to the agent`,{tools:[...C],widgets:Object.keys(i)})},[a,C,i]);let E=e.apiUrl??`https://astralbeam.ai/api`,D=y.files.length>0||y.commands.length>0;(0,Y.useEffect)(()=>{a?.(`status`,`chat status is "${h}"`)},[a,h]);let[O,k]=(0,Y.useState)({apiUrl:E,identity:``,threads:new Map}),A=_.status===`ready`?Ht(_.currentUser):O.identity;(O.apiUrl!==E||O.identity!==A)&&k({apiUrl:E,identity:A,threads:new Map});let j=f.thread?.id??``,M=O.threads.get(j)??{...Xu,text:Ja(E,A,j)},N=M.text,F=e=>k(t=>t.apiUrl!==E||t.identity!==A?t:{...t,threads:new Map(t.threads).set(j,e(t.threads.get(j)??M))}),ee=e=>{Ja(E,A,j,e),F(t=>({...t,text:e}))},te=e=>F(t=>({...t,attachments:typeof e==`function`?e(t.attachments):e})),L=(0,Y.useMemo)(()=>x(v.attachments?e.attachments:!1),[e.attachments,v.attachments]),R=L.enabled?M.attachments:Xu.attachments,z=(0,Y.useRef)(0),B=h===`submitted`||h===`streaming`,ne=B&&!be(m),V=_.status===`loading`,re=_.status===`error`?_.error:void 0,ie=V||re!==void 0||B||f.threadLoading||f.threadLoadFailed||f.thread?.role===`viewer`||f.thread?.agentId===null||P(m.map(e=>({...e,parts:e.parts.filter(e=>e.type!==`tool-call`||w.has(e.id))})),C),ae=e=>{let t=Wn({files:e,existing:R,limits:L,createId:()=>`attachment-${z.current++}`});te(e=>[...e,...t.map(({draft:e})=>e)]);let n=(e,t)=>te(n=>n.map(n=>n.id===e?{...n,...t}:n));for(let{draft:e,file:r}of t){if(e.status===`error`){a?.(`attachment`,`rejected "${e.name}"`,{reason:e.error,size:e.size,type:r.type});continue}a?.(`attachment`,`attached "${e.name}"`,{kind:e.kind,mimeType:e.mimeType,size:e.size}),Oe(r).then(t=>n(e.id,{status:`ready`,data:t}),t=>{a?.(`error`,`attachment "${e.name}" could not be read`,t),n(e.id,{status:`error`,error:`The file could not be read`})})}},oe=e=>{a?.(`attachment`,`attachment removed`,{id:e}),te(t=>t.filter(t=>t.id!==e))},H=()=>{let e=N.trim(),t=p(R),n=R.some(e=>e.status===`reading`);if(ie||n||e.length===0&&t.length===0)return;a?.(`send`,e.length>0?e:`${t.length} attachment(s), no message text`,t.length===0?void 0:{attachments:R.filter(e=>e.status===`ready`).map(e=>({name:e.name,kind:e.kind,size:e.size}))});let r=N,i=R,o=j;d.sendMessage(t.length===0?e:{content:[...t,...e.length>0?[{type:`text`,content:e}]:[]]},{onThreadReady:e=>{if(o!==``)return;o=e;let t=Ja(E,A,``);t&&Ja(E,A,e,t),Ja(E,A,``,``),k(t=>{if(t.apiUrl!==E||t.identity!==A)return t;let n=t.threads.get(``);if(!n||t.threads.has(e))return t;let r=new Map(t.threads);return r.set(e,n),r.delete(``),{...t,threads:r}})},onAccepted:()=>{Ja(E,A,o)===r&&Ja(E,A,o,``),k(e=>{if(e.apiUrl!==E||e.identity!==A)return e;let t=e.threads.get(o);return t?{...e,threads:new Map(e.threads).set(o,{text:t.text===r?``:t.text,attachments:t.attachments===i?[]:t.attachments})}:e})}})},se=(e,t)=>{a?.(`questionnaire`,`answers submitted`,{toolCallId:e,answers:t}),d.addToolResult({toolCallId:e,tool:Qn,output:{answers:t}})},ce=()=>{d.reset(),Ja(E,A,``,``),k(e=>{let t=new Map(e.threads);return t.delete(``),{...e,threads:t}})},le=()=>requestAnimationFrame(()=>n.shadowRoot?.querySelector(`textarea`)?.focus()),U=e=>{Ja(E,A,e,``),k(t=>{if(t.apiUrl!==E||t.identity!==A)return t;let n=new Map(t.threads);return n.delete(e),{...t,threads:n}})};return(0,Y.useImperativeHandle)(r,()=>({reset:ce,stop:d.stop})),(0,X.jsxs)(Or,{className:`h-full w-full gap-0 rounded-none bg-background pt-0 text-foreground ring-0`,children:[e.showHeader!==!1&&(0,X.jsxs)(kr,{className:`flex h-14 shrink-0 items-center gap-1 border-b py-0 [.border-b]:pb-0`,children:[(0,X.jsx)(`div`,{className:`min-w-0 flex-1`,children:c.has(`header`)?(0,X.jsx)(`slot`,{name:Ku(`header`)}):(0,X.jsx)(Ar,{className:`truncate`,children:e.title??`AstralBeam`})}),(0,X.jsx)(Pa,{chat:d,state:f,onDelete:U,onSelect:le},`${E}:${A}`),(0,X.jsx)($n,{variant:`ghost`,size:`icon-sm`,"aria-label":`New chat`,title:`New chat`,disabled:!f.thread&&m.length===0,onClick:()=>{ce(),le()},children:(0,X.jsx)(Sr,{})}),c.has(`headerActions`)&&(0,X.jsx)(`slot`,{name:Ku(`headerActions`)})]}),e.showConversationTitle===!0&&f.thread?.title&&(0,X.jsx)(pa,{chat:d,state:f,thread:f.thread,onDelete:U},`${E}:${A}:${f.thread.id}`),(0,X.jsx)(jr,{className:`min-h-0 flex-1 overflow-hidden p-0`,children:(0,X.jsx)(I,{readOnly:f.thread?.role===`viewer`,messages:m,getAttachment:d.getAttachment,currentTenantUserId:_.status===`ready`?_.currentUser.user.id:void 0,hasOlder:f.messagesCursor!==void 0,loadingHistory:f.threadLoading,loadingOlder:f.olderMessagesLoading,onLoadOlder:d.loadOlderMessages,apiUrl:E,emptySlot:c.has(`empty`)?Ku(`empty`):void 0,emptyHeadline:e.emptyHeadline,emptyDescription:e.emptyDescription,widgets:i,toolTitles:T,activeSlots:o,interactiveToolIds:w,isBusy:ie,awaitingReply:ne,onQuestionnaireAnswers:se})}),(0,X.jsxs)(Mr,{className:`flex-col gap-2 rounded-none border-t-0 bg-transparent pt-1`,children:[f.threadLoading?(0,X.jsx)(`span`,{role:`status`,className:`w-full text-xs text-muted-foreground`,children:`Loading conversation…`}):f.thread?.role===`viewer`?(0,X.jsx)(`span`,{className:`w-full text-xs text-muted-foreground`,children:`You can read this conversation.`}):f.thread?.writerActive&&!B?(0,X.jsx)(`span`,{role:`status`,className:`w-full text-xs text-muted-foreground`,children:`A turn is unfinished. Reopen the conversation to see updates.`}):null,f.thread?.role!==`viewer`&&f.pendingInteractions.filter(e=>!w.has(e.toolCallId)&&(f.thread?.role===`manager`||_.status===`ready`&&e.targetTenantUserId===_.currentUser.user.id)).map(e=>(0,X.jsxs)(`div`,{className:`flex w-full items-center gap-2 text-xs`,children:[(0,X.jsx)(`span`,{className:`min-w-0 flex-1`,children:`An earlier action has no confirmed result.`}),(0,X.jsx)($n,{variant:`outline`,size:`sm`,onClick:()=>void d.abandonToolCall(e.toolCallId),children:`Continue with unknown outcome`})]},e.responseTargetId)),b!==void 0&&(0,X.jsx)(qa,{status:b}),e.sandboxPanel===!0&&D&&(0,X.jsx)(Ga,{activity:y}),(0,X.jsx)(Fr,{title:e.title??`AstralBeam`,actionsSlot:c.has(`composerActions`)?Ku(`composerActions`):void 0,draft:N,onDraftChange:ee,onSend:H,onStop:()=>{a?.(`status`,`generation stopped by user`),d.stop()},onRetry:f.unsentMessage===void 0?m.length>0?()=>void d.reload():void 0:()=>void d.sendMessage(f.unsentMessage),retryLabel:f.unsentMessage===void 0?`Refresh`:`Retry`,showError:h===`error`,error:g,streamBusy:B,isBusy:ie,authPending:V,authError:re,onAuthRetry:d.retryAuthentication,attachments:R,attachmentLimits:L,onAddFiles:ae,onRemoveAttachment:oe})]})]})}function Qu(e,t){let n=e.host.parentElement??document.body,r=_(),i=document.createElement(`style`);e.append(i);let a=()=>{i.textContent=H(n,r),t()?.(`theme`,`host style bridged onto widget slots`,{rule:i.textContent})};a();let o=0,s=()=>{cancelAnimationFrame(o),o=requestAnimationFrame(a)},c=[];for(let e=n;e;e=e.parentElement){let t=new MutationObserver(s);t.observe(e,{attributeFilter:[`class`,`style`]}),c.push(t)}return()=>{cancelAnimationFrame(o);for(let e of c)e.disconnect();i.remove()}}function $u(e,n,r){let i=document.createElement(`style`);i.textContent=Tn+(r.customCss??``),e.append(i);let a=r,o=Qu(e,()=>t(a.debug)),s=(0,Dr.createRoot)(n),c=(0,Y.createRef)(),l=t=>{a.customCss!==t.customCss&&(i.textContent=Tn+(t.customCss??``)),a=t,s.render((0,X.jsx)(Zu,{options:t,host:e.host,controller:c}))};return l(r),{update:l,reset:()=>c.current?.reset(),stop:()=>c.current?.stop(),dispose:()=>{s.unmount(),o(),i.remove()}}}export{$u as renderChat};