@astralbeam/sdk 0.17.0 → 0.19.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.
Files changed (50) hide show
  1. package/README.md +8 -1
  2. package/dist/{api-BaIPbj-Q.js → api-B3UxSTtl.js} +135 -1
  3. package/dist/api.d.ts +2 -2
  4. package/dist/api.js +1 -2
  5. package/dist/auth-lifecycle-B0BXyDr7.js +25 -0
  6. package/dist/badge-B9WuChHI.js +1 -0
  7. package/dist/client.d.ts +57 -8
  8. package/dist/client.js +1 -1
  9. package/dist/constants-C-Yp0Vhg.js +1 -0
  10. package/dist/{core-DeMY6_wQ.js → core-CLWlvgYl.js} +203 -72
  11. package/dist/core.d.ts +2 -2
  12. package/dist/core.js +1 -2
  13. package/dist/css-BGIxQoYs.js +1 -0
  14. package/dist/css-DgaLhXQH.js +1 -0
  15. package/dist/{debug-qLts7gEt.js → debug-DLDY8CZb.js} +1 -1
  16. package/dist/diff-woXpYk--.js +1 -0
  17. package/dist/github-dark-C-LZuMrd.js +1 -0
  18. package/dist/github-light-EUqPIrTm.js +1 -0
  19. package/dist/highlighter-Bd_oZUcA.js +152 -0
  20. package/dist/html-B3xvRgDO.js +1 -0
  21. package/dist/{index-NT05_Yw_.d.ts → index-DDfmeUeU.d.ts} +76 -50
  22. package/dist/{index-CfGnT6Od.d.ts → index-DFxtXIXy.d.ts} +104 -3
  23. package/dist/item-a9y_9nk7.js +1 -0
  24. package/dist/javascript-BzbQS41l.js +1 -0
  25. package/dist/javascript-CpIGwZ_Y.js +1 -0
  26. package/dist/json-qhed-kSA.js +1 -0
  27. package/dist/jsx-Bz0zcwM4.js +1 -0
  28. package/dist/listings-DzxJtGCD.js +1 -0
  29. package/dist/markdown-BYOwaDjH.js +1 -0
  30. package/dist/mcp-servers-ESbOt00F.js +1 -0
  31. package/dist/python-gzcpVVnB.js +1 -0
  32. package/dist/react.d.ts +23 -16
  33. package/dist/react.js +46 -8
  34. package/dist/server.d.ts +14 -26
  35. package/dist/server.js +190 -347
  36. package/dist/shellscript-CLZ0U2zV.js +1 -0
  37. package/dist/sql-CEbI0hMM.js +1 -0
  38. package/dist/styles.generated-D4k7izMB.js +80 -0
  39. package/dist/tsx-udAQXfEw.js +1 -0
  40. package/dist/typescript-bsJCZSQ-.js +1 -0
  41. package/dist/validate-BOw-BAyv.js +140 -0
  42. package/dist/widget-DGmCPqzk.js +24 -0
  43. package/dist/yaml-rwi0_p6S.js +1 -0
  44. package/package.json +18 -15
  45. package/dist/constants-enyqxaJi.js +0 -1
  46. package/dist/listings-BH_hPkxx.js +0 -1
  47. package/dist/rolldown-runtime-QTnfLwEv.js +0 -1
  48. package/dist/styles.generated-D8sDOLu3.js +0 -98
  49. package/dist/type_checks-C-WTHaWs.js +0 -117
  50. package/dist/widget-BdiuWvPf.js +0 -24
@@ -1,24 +0,0 @@
1
- import{n as e,r as t}from"./rolldown-runtime-QTnfLwEv.js";import"./constants-enyqxaJi.js";import{t as n}from"./debug-qLts7gEt.js";import{$ as r,$n as i,$r as a,$t as o,An as s,Ar as c,At as l,B as u,Bn as d,Br as f,Bt as p,C as m,Ci as h,Cn as g,Cr as _,Ct as v,Dn as y,Dr as b,Dt as x,E as S,En as C,Er as w,Et as T,F as E,Fn as D,Fr as O,Ft as k,G as A,Gn as j,Gr as M,Gt as ee,H as N,Hr as P,Ht as F,I,In as L,Ir as R,It as te,J as ne,Jn as z,Jr as B,Jt as V,Kn as re,Kr as H,Kt as ie,L as ae,Ln as oe,Lr as se,Lt as ce,Mn as le,Mr as ue,Mt as de,Nn as fe,Nr as pe,Nt as me,On as U,Or as he,Ot as ge,P as _e,Pn as ve,Pr as ye,Pt as be,Qn as W,Qr as xe,Qt as Se,R as Ce,Rn as we,Rr as G,Rt as Te,S as Ee,Si as De,Sn as Oe,Sr as ke,St as Ae,T as je,Tn as Me,Tr as Ne,Tt as Pe,U as Fe,Un as Ie,Ur as Le,Ut as Re,V as ze,Vr as Be,Vt as Ve,W as He,Wn as Ue,Wr as We,Wt as Ge,X as Ke,Xn as qe,Xr as Je,Xt as Ye,Yn as Xe,Yr as Ze,Yt as Qe,Zn as $e,Zr as et,Zt as tt,_ as nt,_i as rt,_n as it,_r as at,_t as ot,a as st,ai as ct,an as lt,ar as ut,b as dt,bi as ft,bn as pt,br as mt,bt as ht,c as gt,ci as _t,cn as vt,cr as yt,ct as bt,d as xt,di as St,dn as Ct,dr as wt,dt as Tt,ei as Et,en as Dt,er as Ot,f as kt,fi as At,fn as jt,fr as Mt,ft as Nt,g as Pt,gi as Ft,gn as It,gr as Lt,gt as Rt,h as zt,hi as Bt,hn as Vt,hr as Ht,ht as Ut,i as Wt,ii as Gt,in as Kt,ir as qt,jn as Jt,jr as Yt,jt as Xt,k as Zt,kn as Qt,kr as $t,kt as en,li as tn,ln as nn,lt as rn,m as an,mi as on,mn as sn,mr as cn,mt as ln,n as un,ni as dn,nn as fn,nr as pn,nt as mn,o as hn,oi as gn,on as _n,p as vn,pi as yn,pn as bn,pt as xn,qn as Sn,qr as Cn,qt as wn,r as Tn,ri as En,rn as Dn,rr as On,s as kn,si as K,sn as An,sr as jn,st as Mn,t as Nn,ti as Pn,tn as Fn,u as In,ui as Ln,un as Rn,ur as zn,ut as Bn,v as Vn,vn as Hn,vr as Un,vt as Wn,w as Gn,wn as Kn,wr as qn,wt as Jn,x as Yn,xi as Xn,xn as Zn,xr as Qn,xt as $n,y as er,yr as tr,yt as nr,z as rr,zn as ir,zr as ar,zt as or}from"./styles.generated-D8sDOLu3.js";var q=t(h(),1);const sr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M200,112H56l72-72Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),cr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M208,160H48l80-80Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),lr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),ur=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M216,40V168H168V88H88V40Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),dr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),fr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),pr=new Map([[`bold`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M228,144v64a12,12,0,0,1-12,12H40a12,12,0,0,1-12-12V144a12,12,0,0,1,24,0v52H204V144a12,12,0,0,1,24,0Zm-108.49,8.49a12,12,0,0,0,17,0l40-40a12,12,0,0,0-17-17L140,115V32a12,12,0,0,0-24,0v83L96.49,95.51a12,12,0,0,0-17,17Z`}))],[`duotone`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M216,48V208H40V48A16,16,0,0,1,56,32H200A16,16,0,0,1,216,48Z`,opacity:`0.2`}),q.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40a8,8,0,0,0-11.32-11.32L136,124.69V32a8,8,0,0,0-16,0v92.69L93.66,98.34a8,8,0,0,0-11.32,11.32Z`}))],[`fill`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40A8,8,0,0,0,168,96H136V32a8,8,0,0,0-16,0V96H88a8,8,0,0,0-5.66,13.66Z`}))],[`light`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M222,144v64a6,6,0,0,1-6,6H40a6,6,0,0,1-6-6V144a6,6,0,0,1,12,0v58H210V144a6,6,0,0,1,12,0Zm-98.24,4.24a6,6,0,0,0,8.48,0l40-40a6,6,0,0,0-8.48-8.48L134,129.51V32a6,6,0,0,0-12,0v97.51L92.24,99.76a6,6,0,0,0-8.48,8.48Z`}))],[`regular`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M224,144v64a8,8,0,0,1-8,8H40a8,8,0,0,1-8-8V144a8,8,0,0,1,16,0v56H208V144a8,8,0,0,1,16,0Zm-101.66,5.66a8,8,0,0,0,11.32,0l40-40a8,8,0,0,0-11.32-11.32L136,124.69V32a8,8,0,0,0-16,0v92.69L93.66,98.34a8,8,0,0,0-11.32,11.32Z`}))],[`thin`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M220,144v64a4,4,0,0,1-4,4H40a4,4,0,0,1-4-4V144a4,4,0,0,1,8,0v60H212V144a4,4,0,0,1,8,0Zm-94.83,2.83a4,4,0,0,0,5.66,0l40-40a4,4,0,1,0-5.66-5.66L132,134.34V32a4,4,0,0,0-8,0V134.34L90.83,101.17a4,4,0,0,0-5.66,5.66Z`}))]]),mr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M208,88H152V32Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),hr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M208,88H152V32Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),gr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M200,88l-72,72H96V128l72-72Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),_r=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),vr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),yr=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),br=new Map([[`bold`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.createElement(`path`,{d:`M200,56V208a8,8,0,0,1-8,8H64a8,8,0,0,1-8-8V56Z`,opacity:`0.2`}),q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`,q.createElement(q.Fragment,null,q.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`}))]]),xr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:sr}));xr.displayName=`ArrowUpIcon`;const Sr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:cr}));Sr.displayName=`CaretUpIcon`;const Cr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:lr}));Cr.displayName=`ClockCounterClockwiseIcon`;const wr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:ur}));wr.displayName=`CopyIcon`;const Tr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:dr}));Tr.displayName=`CubeIcon`;const Er=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:fr}));Er.displayName=`DotsThreeIcon`;const Dr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:pr}));Dr.displayName=`DownloadSimpleIcon`;const Or=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:mr}));Or.displayName=`FileCodeIcon`;const kr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:hr}));kr.displayName=`FileCsvIcon`;const Ar=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:gr}));Ar.displayName=`NotePencilIcon`;const jr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:_r}));jr.displayName=`PaperclipIcon`;const Mr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:vr}));Mr.displayName=`PencilSimpleIcon`;const Nr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:yr}));Nr.displayName=`StopIcon`;const Pr=q.forwardRef((e,t)=>q.createElement(ft,{ref:t,...e,weights:br}));Pr.displayName=`TrashIcon`;var Fr=Xn(),J=M();function Ir({className:e,size:t=`default`,...n}){return(0,J.jsx)(`div`,{"data-slot":`card`,"data-size":t,className:H(`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 Lr({className:e,...t}){return(0,J.jsx)(`div`,{"data-slot":`card-header`,className:H(`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 Rr({className:e,...t}){return(0,J.jsx)(`div`,{"data-slot":`card-title`,className:H(`font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm`,e),...t})}function zr({className:e,...t}){return(0,J.jsx)(`div`,{"data-slot":`card-content`,className:H(`px-(--card-spacing)`,e),...t})}function Br({className:e,...t}){return(0,J.jsx)(`div`,{"data-slot":`card-footer`,className:H(`flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)`,e),...t})}const Vr={reading:`uploading`,ready:`done`,error:`error`};function Hr({attachments:e,onRemove:t}){let n=(0,q.useRef)(null),r=e.at(-1)?.id;return(0,q.useEffect)(()=>{let e=n.current;e&&(e.scrollLeft=e.scrollWidth)},[r]),e.length===0?null:(0,J.jsx)(It,{ref:n,className:`w-full`,children:e.map(e=>{let n=e.kind===`image`&&e.data!==void 0?g(e.mimeType,e.data):void 0;return(0,J.jsxs)(Ct,{size:`sm`,state:Vr[e.status],role:e.status===`error`?`alert`:void 0,children:[(0,J.jsx)(it,{variant:n?`image`:`icon`,children:n?(0,J.jsx)(`img`,{src:n,alt:``}):e.status===`reading`?(0,J.jsx)(Rn,{}):(0,J.jsx)(nn,{kind:e.kind,mimeType:e.mimeType})}),(0,J.jsxs)(sn,{children:[(0,J.jsx)(Hn,{children:e.name}),(0,J.jsx)(Vt,{children:e.error??s(e.size)})]}),(0,J.jsx)(bn,{children:(0,J.jsx)(jt,{type:`button`,"aria-label":`Remove ${e.name}`,title:`Remove`,onClick:()=>t(e.id),children:(0,J.jsx)(on,{})})})]},e.id)})})}function Ur({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 b=(0,q.useRef)(null),[x,S]=(0,q.useState)(!1),C=f||p!==void 0,w=h.some(e=>e.status===`reading`),T=h.some(e=>e.status===`ready`),E=h.filter(e=>e.status!==`error`).length>=g.maxFiles,D=g.enabled&&!C,O=d||C||w||n.trim().length===0&&!T,k=e=>{!D||!e||e.length===0||_([...e])},A=e=>D&&(e?.types.includes(`Files`)??!1);return(0,J.jsxs)(`form`,{className:`w-full`,onSubmit:e=>{e.preventDefault(),i()},onDragOver:e=>{A(e.dataTransfer)&&(e.preventDefault(),S(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||S(!1)},onDrop:e=>{A(e.dataTransfer)&&(e.preventDefault(),S(!1),k(e.dataTransfer.files))},children:[c&&(0,J.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,J.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,J.jsx)(`div`,{className:`break-words`,children:y(l)}),Ue(l)&&l.body?.reference&&(0,J.jsxs)(`div`,{className:`mt-0.5 text-muted-foreground`,children:[`Support reference: `,l.body.reference]})]}),o&&(0,J.jsx)(We,{type:`button`,variant:`outline`,size:`sm`,onClick:o,children:s})]}),p&&(0,J.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,J.jsx)(`div`,{className:`min-w-0 flex-1`,children:Ue(p)&&p.status===401?`The assistant's connection was rejected. Contact this app's support team.`:`The assistant could not verify your session. Retry or contact this app's support team.`}),m&&(0,J.jsx)(We,{type:`button`,variant:`outline`,size:`sm`,onClick:m,children:`Retry`})]}),g.enabled&&(0,J.jsx)(`input`,{ref:b,type:`file`,multiple:!0,className:`sr-only`,accept:Zn(g),onChange:e=>{k(e.currentTarget.files),e.currentTarget.value=``}}),(0,J.jsxs)(Sn,{className:H(`cursor-text`,x&&`border-ring ring-3 ring-ring/50`),children:[h.length>0&&(0,J.jsx)(z,{align:`block-start`,children:(0,J.jsx)(Hr,{attachments:h,onRemove:v})}),(0,J.jsx)(qe,{"aria-label":`Message`,className:`max-h-24 min-h-9`,placeholder:f?`Verifying your session…`:x?`Drop files to attach…`:`Message ${e}…`,disabled:C,value:n,onChange:e=>r(e.currentTarget.value),onPaste:e=>{!D||e.clipboardData.files.length===0||(e.preventDefault(),k(e.clipboardData.files))},onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),i())}}),(0,J.jsxs)(z,{align:`block-end`,children:[g.enabled&&(0,J.jsx)(Xe,{type:`button`,size:`icon-sm`,"aria-label":`Attach files`,title:E?`Up to ${g.maxFiles} files per message`:`Attach images, PDFs, documents, spreadsheets, data, or text files`,disabled:C||E,onClick:()=>b.current?.click(),children:(0,J.jsx)(jr,{})}),t&&(0,J.jsx)(`slot`,{name:t}),u?(0,J.jsxs)(Xe,{type:`button`,variant:`default`,size:`icon-sm`,className:`ml-auto`,onClick:a,children:[(0,J.jsx)(Nr,{}),(0,J.jsx)(`span`,{className:`sr-only`,children:`Stop`})]}):(0,J.jsxs)(Xe,{type:`submit`,variant:`default`,size:`icon-sm`,className:`ml-auto`,disabled:O,children:[(0,J.jsx)(xr,{}),(0,J.jsx)(`span`,{className:`sr-only`,children:`Send`})]})]})]})]})}const Wr=q.createContext(void 0);function Gr(e){let t=q.useContext(Wr);if(t===void 0&&!e)throw Error(Gt(33));return t}const Kr=q.createContext(void 0);function qr(e){let t=q.useContext(Kr);if(t===void 0&&!e)throw Error(Gt(36));return t}const Jr=q.createContext(void 0);function Yr(e=!0){let t=q.useContext(Jr);if(t===void 0&&!e)throw Error(Gt(25));return t}function Xr(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=Yr(!0),f=d!==void 0;return q.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:ut})},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&&!Be&&e.button===2)return}s.current&&a.context.allowMouseUpTriggerRef.current&&(!f||e.button===2)&&c.type===`regular-item`&&Et(s.current,e,{detail:1})}}),[t,n,r,l,i,u,a,o,s,d,f,c])}const Zr={type:`regular-item`};function Qr(e){let{closeOnClick:t,disabled:n,highlighted:r,id:i,store:o,typingRef:s=o.context.typingRef,nativeButton:c,itemMetadata:l,nodeId:u}=e,d=q.useRef(null),{getButtonProps:f,buttonRef:p}=a({disabled:n,focusableWhenDisabled:!0,native:c,composite:!0}),m=Xr({closeOnClick:t,highlighted:r,id:i,nodeId:u,store:o,typingRef:s,itemRef:d,itemMetadata:l}),h=q.useCallback(e=>ct(m,{onMouseEnter(){l.type===`submenu-trigger`&&l.setActive()}},e,f),[m,f,l]),g=xe(d,p);return q.useMemo(()=>({getItemProps:h,itemRef:g}),[h,g])}const $r=q.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=Qe({guess:!0,label:a}),f=Gr(!0),p=P(i),{store:m}=qr(),h=m.useState(`disabled`),g=s||h,_=m.useState(`isActive`,d.index),v=m.useState(`itemProps`),{getItemProps:y,itemRef:b}=Qr({closeOnClick:c,disabled:g,highlighted:_,id:p,store:m,nativeButton:o,nodeId:f?.context.nodeId,itemMetadata:Zr});return B(`div`,e,{state:{disabled:g,highlighted:_},props:[v,u,y],ref:[b,t,d.ref]})});function ei(e,t){return t!=null&&!Yt(t)?0:typeof e==`function`?e():e}function ti(e,t,n){let r=ei(e,n);return typeof r==`number`?r:r?.[t]}function ni(e){return typeof e==`function`?e():e}function ri(e,t){return t||e===`click`||e===`mousedown`}function ii(e){return e?.includes(`mouse`)&&e!==`mousedown`}function ai(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=q.useRef(null);r===void 0&&f.current===null&&(f.current=new en({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),gn(()=>{let e={open:s,floatingId:i,referenceElement:c,floatingElement:l};St(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 oi(){return new en({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:new ht,floatingId:void 0,syncOnly:!1,nested:!1,onOpenChange:void 0})}function si(){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:oi(),floatingId:void 0,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:Je,inactiveTriggerProps:Je,popupProps:Je}}const ci=e=>e.triggerIdProp??e.activeTriggerId,li=e=>e.openProp??e.open,ui=e=>(e.popupElement?.id??e.floatingId)||void 0;function di(e,t){return t!==void 0&&li(e)&&ci(e)===t}function fi(e,t){return di(e,t)?!0:t!==void 0&&li(e)&&ci(e)==null&&e.triggerCount===1}const pi={open:li,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:ci,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:ui,isTriggerActive:(e,t)=>t!==void 0&&ci(e)===t,isOpenedByTrigger:(e,t)=>di(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&ci(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>fi(e,t)?ui(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};var mi=me();function hi(e){return(0,mi.useSyncExternalStore)(q.useCallback(t=>e===void 0?et:e.subscribeStore(t),[e]),q.useCallback(()=>e===void 0?void 0:e.store,[e]),()=>e?.serverStore)}const gi=Be&&f;function _i(e,t={}){let{enabled:n=!0,delay:r}=t,i=`rootStore`in e?e.rootStore:e,{events:a,dataRef:o}=i.context,s=q.useRef(!1),c=q.useRef(null),l=q.useRef(!0),u=mt();q.useEffect(()=>{let e=i.select(`domReferenceElement`);if(!n)return;let t=Ln(e);function r(){let e=i.select(`domReferenceElement`);!i.select(`open`)&&At(e)&&e===se(Pn(e))&&(s.current=!0)}function a(){l.current=!0}function o(){l.current=!1}return V(Fn(t,`blur`,r),gi&&Fn(t,`keydown`,a,!0),gi&&Fn(t,`pointerdown`,o,!0))},[i,n]),q.useEffect(()=>{if(!n)return;function e(e){if(e.reason===`trigger-press`||e.reason===`escape-key`){let e=i.select(`domReferenceElement`);St(e)&&(c.current=e,s.current=!0)}}return a.on(`openchange`,e),()=>{a.off(`openchange`,e)}},[a,n,i]);let d=q.useMemo(()=>{function e(){s.current=!1,c.current=null}return{onMouseLeave(){e()},onFocus(t){let n=t.currentTarget;if(s.current){if(c.current===n)return;e()}let a=ar(t.nativeEvent);if(St(a)){if(gi&&!t.relatedTarget){if(!l.current&&!O(a))return}else if(!R(a))return}let o=ye(t.relatedTarget,i.context.triggerElements),{nativeEvent:d,currentTarget:f}=t,p=typeof r==`function`?r():r;if(i.select(`open`)&&o||p===0||p===void 0){i.setOpen(!0,W(wt,d,f));return}u.start(p,()=>{s.current||i.setOpen(!0,W(wt,d,f))})},onBlur(t){e();let n=t.relatedTarget,r=t.nativeEvent,a=St(n)&&n.hasAttribute(ie(`focus-guard`))&&n.getAttribute(`data-type`)===`outside`;u.start(0,()=>{let e=i.select(`domReferenceElement`),t=se(Pn(e));!n&&t===e||G(o.current.floatingContext?.refs.floating.current,t)||G(e,t)||a||ye(n??t,i.context.triggerElements)||i.setOpen(!1,W(wt,r))})}}},[o,r,i,u]);return q.useMemo(()=>n?{reference:d,trigger:d}:{},[n,d])}var vi=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 tr,this.restTimeout=new tr,this.handleCloseOptions=void 0}static create(){return new e}dispose=()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()};disposeEffect=()=>this.dispose};const yi=new WeakMap;function bi(e){if(!e.performedPointerEventsMutation)return;let t=e.pointerEventsScopeElement;t&&yi.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty(`pointer-events`),e.pointerEventsReferenceElement?.style.removeProperty(`pointer-events`),e.pointerEventsFloatingElement?.style.removeProperty(`pointer-events`),yi.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function xi(e,t){let{scopeElement:n,referenceElement:r,floatingElement:i}=t,a=yi.get(n);a&&a!==e&&bi(a),bi(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=n,e.pointerEventsReferenceElement=r,e.pointerEventsFloatingElement=i,yi.set(n,e),n.style.pointerEvents=`none`,r.style.pointerEvents=`auto`,i.style.pointerEvents=`auto`}function Si(e){let t=e.context.dataRef.current,n=_t(()=>t.hoverInteractionState??vi.create()).current;return t.hoverInteractionState||=n,Qn(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function Ci(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=Ve(),d=p(),f=Si(a),m=mt(),h=K(()=>ri(l.current.openEvent?.type,f.interactedInside)),g=K(()=>ii(l.current.openEvent?.type)),_=K(()=>{bi(f)});gn(()=>{o||(f.pointerType=void 0,f.restTimeoutPending=!1,f.interactedInside=!1,_())},[o,f,_]),q.useEffect(()=>_,[_]),gn(()=>{if(n&&o&&f.handleCloseOptions?.blockPointerEvents&&g()&&St(c)&&s){let e=c,t=s,n=Pn(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 xi(f,{scopeElement:o,referenceElement:e,floatingElement:t}),()=>{_()}}},[n,o,c,s,f,g,u,d,_]),q.useEffect(()=>{if(!n)return;function e(){return!!(u&&d&&ue(u.nodesRef.current,d).length>0)}function t(e){let t=ti(r,`close`,f.pointerType),n=()=>{a.setOpen(!1,W(Mt,e)),u?.events.emit(`floating.closed`,e)};t?f.openChangeTimeout.start(t,n):(f.openChangeTimeout.clear(),n())}function o(e){let t=ar(e);if(!pe(t)){f.interactedInside=!1;return}f.interactedInside=t?.closest(`[aria-haspopup]`)!=null}function c(){f.openChangeTimeout.clear(),m.clear(),u?.events.off(`floating.closed`,v),_()}function p(n){if(e()&&u){u.events.on(`floating.closed`,v);return}if(ye(n.relatedTarget,a.context.triggerElements))return;let r=l.current.floatingContext?.nodeId??i,o=n.relatedTarget;if(!(u&&r&&St(o)&&ue(u.nodesRef.current,r,!1).some(e=>G(e.context?.elements.floating,o)))){if(f.handler){f.handler(n);return}_(),g()&&!h()&&t(n)}}function v(t){!u||!d||e()||m.start(0,()=>{u.events.off(`floating.closed`,v),a.setOpen(!1,W(Mt,t)),u.events.emit(`floating.closed`,t)})}let y=s;return V(y&&Fn(y,`mouseenter`,c),y&&Fn(y,`mouseleave`,p),y&&Fn(y,`pointerdown`,o,!0),()=>{u?.events.off(`floating.closed`,v)})},[n,s,a,l,r,i,g,h,_,f,u,d,m])}var wi=t(De(),1);const Ti={current:null};function Ei(e,t={}){let{enabled:n=!0,delay:r=0,handleClose:i=null,mouseOnly:a=!1,restMs:o=0,move:s=!0,triggerElementRef:c=Ti,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=Ve(l),y=Si(h),b=q.useRef(!1),x=Dt(i),S=Dt(r),C=Dt(o),w=Dt(n),T=Dt(p),E=Dt(f),D=K(()=>ri(g.current.openEvent?.type,y.interactedInside)),O=K(()=>T.current?.()!==!1),k=K((e,t,n)=>{let r=h.context.triggerElements;if(r.hasElement(t))return!e||!G(e,t);if(!St(n))return!1;let i=n;return r.hasMatchingElement(e=>G(e,i))&&(!e||!G(e,i))}),A=K(()=>{y.handler&&=(Pn(h.select(`domReferenceElement`)).removeEventListener(`mousemove`,y.handler),void 0)}),j=K(()=>{bi(y)});return u&&(y.handleCloseOptions=x.current?.__options),q.useEffect(()=>A,[A]),q.useEffect(()=>{if(!n)return;function e(e){e.open?b.current=!1:(b.current=e.reason===Mt,A(),y.openChangeTimeout.clear(),y.restTimeout.clear(),y.blockMouseMove=!0,y.restTimeoutPending=!1)}return _.on(`openchange`,e),()=>{_.off(`openchange`,e)}},[n,_,y,A]),q.useEffect(()=>{if(!n)return;function e(e,t=!0){let n=ti(S.current,`close`,y.pointerType);n?y.openChangeTimeout.start(n,()=>{h.setOpen(!1,W(Mt,e)),v?.events.emit(`floating.closed`,e)}):t&&(y.openChangeTimeout.clear(),h.setOpen(!1,W(Mt,e)),v?.events.emit(`floating.closed`,e))}let t=c.current??(u?h.select(`domReferenceElement`):null);if(!St(t))return;function r(e){if(y.openChangeTimeout.clear(),y.blockMouseMove=!1,a&&!Yt(y.pointerType))return;let t=ni(C.current),n=ti(S.current,`open`,y.pointerType),r=ar(e),i=e.currentTarget??null,o=h.select(`domReferenceElement`),s=i;if(St(r)&&!h.context.triggerElements.hasElement(r)){for(let e of h.context.triggerElements.elements())if(G(e,r)){s=e;break}}St(i)&&St(o)&&!h.context.triggerElements.hasElement(i)&&G(i,o)&&(s=o);let c=s!=null&&k(o,s,r),l=h.select(`open`),u=E.current?.()??h.select(`transitionStatus`)===`ending`,d=!l&&u&&b.current,f=!c&&St(s)&&St(o)&&G(o,s)&&d,p=t>0&&!n,m=c&&(l||d)||f,g=!l||c;if(m){O()&&h.setOpen(!0,W(Mt,e,s));return}p||(n?y.openChangeTimeout.start(n,()=>{g&&O()&&h.setOpen(!0,W(Mt,e,s))}):g&&O()&&h.setOpen(!0,W(Mt,e,s)))}function i(t){if(D()){j();return}A();let n=Pn(h.select(`domReferenceElement`));y.restTimeout.clear(),y.restTimeoutPending=!1;let r=g.current.floatingContext??d?.();if(!ye(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(){j(),A(),w.current&&!D()&&i===h.select(`domReferenceElement`)&&e(t,!0)}}),n.addEventListener(`mousemove`,y.handler),y.handler(t);return}(y.pointerType!==`touch`||!G(h.select(`floatingElement`),t.relatedTarget))&&e(t)}}function o(e){G(t,e.relatedTarget)||(y.openChangeTimeout.clear(),y.restTimeout.clear(),y.restTimeoutPending=!1)}let l=m?Fn(t,`mouseout`,o):void 0;return s?V(Fn(t,`mousemove`,r,{once:!0}),Fn(t,`mouseenter`,r),Fn(t,`mouseleave`,i),l):V(Fn(t,`mouseenter`,r),Fn(t,`mouseleave`,i),l)},[A,j,g,S,h,n,x,y,u,k,D,a,s,C,c,v,w,d,E,O,m]),q.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=k(r,n,e.target);if(a&&!Yt(y.pointerType))return;if(i&&o&&y.handleCloseOptions?.blockPointerEvents){let e=h.select(`floatingElement`);if(e){let t=y.handleCloseOptions?.getScope?.()??n.ownerDocument.body;xi(y,{scopeElement:t,referenceElement:n,floatingElement:e})}}let s=ni(C.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,D())return;let e=h.select(`open`);!y.blockMouseMove&&(!e||o)&&O()&&h.setOpen(!0,W(Mt,t,n))}y.pointerType===`touch`?wi.flushSync(()=>{c()}):o&&i?c():(y.restTimeoutPending=!0,y.restTimeout.start(s,c))}}},[n,y,D,k,a,h,C,O])}const Y=.5;function Di(e,t,n,r,i,a){return r>=t!=a>=t&&e<=(i-n)*(t-r)/(a-r)+n}function Oi(e,t,n,r,i,a,o,s,c,l){let u=!1;return Di(e,t,n,r,i,a)&&(u=!u),Di(e,t,i,a,o,s)&&(u=!u),Di(e,t,o,s,c,l)&&(u=!u),Di(e,t,c,l,n,r)&&(u=!u),u}function ki(e,t,n){return e>=n.x&&e<=n.x+n.width&&t>=n.y&&t<=n.y+n.height}function Ai(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 ji(e={}){let{blockPointerEvents:t=!1}=e,n=new tr,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=ar(r),g=r.type===`mouseleave`,_=G(u,h),v=G(a,h);if(_&&(l=!0,!g))return;if(v&&(l=!1,!g)){l=!0;return}if(g&&St(r.relatedTarget)&&G(u,r.relatedTarget))return;function y(){return!!(s&&ue(s.nodesRef.current,o).length>0)}function b(){y()||m()}if(y())return;let x=a.getBoundingClientRect(),S=u.getBoundingClientRect(),C=e>S.right-S.width/2,w=t>S.bottom-S.height/2,T=S.width>x.width,E=S.height>x.height,D=(T?x:S).left,O=(T?x:S).right,k=(E?x:S).top,A=(E?x:S).bottom;if(c===`top`&&t>=x.bottom-1||c===`bottom`&&t<=x.top+1||c===`left`&&e>=x.right-1||c===`right`&&e<=x.left+1){b();return}let j=!1;switch(c){case`top`:j=Ai(d,f,D,x.top+1,O,S.bottom-1);break;case`bottom`:j=Ai(d,f,D,S.top+1,O,x.bottom-1);break;case`left`:j=Ai(d,f,S.right-1,A,x.left+1,k);break;case`right`:j=Ai(d,f,x.right-1,A,S.left+1,k);break;default:}if(j)return;if(l&&!ki(d,f,x)){b();return}if(!g&&p(d,f)){b();return}let M=!1;switch(c){case`top`:{let n=T?Y/2:Y*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t+Y+1,o=C||T?S.bottom-Y:S.top,s=C?T?S.bottom-Y:S.top:S.bottom-Y;M=Oi(d,f,r,a,i,a,S.left,o,S.right,s);break}case`bottom`:{let n=T?Y/2:Y*4,r=T||C?e+n:e-n,i=T?e-n:C?e+n:e-n,a=t-Y,o=C||T?S.top+Y:S.bottom,s=C?T?S.top+Y:S.bottom:S.top+Y;M=Oi(d,f,r,a,i,a,S.left,o,S.right,s);break}case`left`:{let n=E?Y/2:Y*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e+Y+1,o=w||E?S.right-Y:S.left,s=w?E?S.right-Y:S.left:S.right-Y;M=Oi(d,f,o,S.top,s,S.bottom,a,r,a,i);break}case`right`:{let n=E?Y/2:Y*4,r=E||w?t+n:t-n,i=E?t-n:w?t+n:t-n,a=e-Y,o=w||E?S.left+Y:S.right,s=w?E?S.left+Y:S.right:S.left+Y;M=Oi(d,f,a,r,a,i,o,S.top,s,S.bottom);break}default:}M?l||n.start(40,b):b()}};return r.__options={...e,blockPointerEvents:t},r}const Mi=q.createContext(void 0);function Ni(e){let t=q.useContext(Mi);if(t===void 0&&!e)throw Error(Gt(69));return t}const Pi=`ArrowUp`,Fi=`ArrowDown`,Ii=`ArrowLeft`,Li=`ArrowRight`,Ri=new Set([Pi,Fi,Ii,Li,`Home`,`End`]),zi=[`Shift`,`Control`,`Alt`,`Meta`];function Bi(e){return At(e)&&e.tagName===`INPUT`}function Vi(e){return!!(Bi(e)&&e.selectionStart!=null||At(e)&&e.tagName===`TEXTAREA`)}function Hi(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=Ui(e,t,`left`),a=Wi(e),o=Wi(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=Ui(e,t,`top`),r=Wi(e),i=Wi(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 Ui(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 Wi(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 Gi=q.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,...o}=e,{store:s}=qr(),{side:c,align:l}=Gr(),u=Ni(!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`;at({open:d,ref:s.context.popupRef,onComplete(){d&&s.context.onOpenChangeComplete?.(!0)}}),q.useEffect(()=>{function e(e){s.setOpen(!1,W(e.reason,e.domEvent))}return x.events.on(`close`,e),()=>{x.events.off(`close`,e)}},[x.events,s]),Ci(b,{enabled:C&&!w&&!E&&_.type!==`menubar`,closeDelay:S});let D=s.useStateSetter(`popupElement`),O=B(`div`,e,{state:{transitionStatus:f,side:c,align:l,open:d,nested:_.type===`menu`,instant:h},ref:[t,s.context.popupRef,D],stateAttributesMapping:Ye,props:[p,{onKeyDown(e){u&&Ri.has(e.key)&&e.stopPropagation()}},ot(f),o,{"data-rootownerid":y}]}),k=_.type===void 0||E;return(g||_.type===`menubar`&&v!==`outside-press`)&&(k=!0),(0,J.jsx)(te,{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})}),Ki=q.createContext(void 0);function qi(){let e=q.useContext(Ki);if(e===void 0)throw Error(Gt(32));return e}const Ji=q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i}=qr();return i.useState(`mounted`)||n?(0,J.jsx)(Ki.Provider,{value:n,children:(0,J.jsx)(Re,{ref:t,...r})}):null}),Yi=q.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=Ge,style:g,..._}=e,{store:v}=qr(),y=qi(),b=Yr(!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`),L=q.useRef(null),R=Un(A),te=n,ne=c,z=l,B=s,V=h;x.type===`context-menu`&&(te=n??x.context?.anchor,B??=`start`,!o&&B!==`center`&&(z=e.alignOffset??2,ne=e.sideOffset??-5));let re=o,H=B;x.type===`menu`?(re??=`inline-end`,H??=`start`,V=e.collisionAvoidance??ee):x.type===`menubar`&&(re??=x.context.orientation===`vertical`?`inline-end`:`bottom`,H??=`start`);let ie=x.type===`context-menu`,ae=ln({anchor:te,floatingRootContext:S,positionMethod:b?`fixed`:r,mounted:w,side:re,sideOffset:ne,align:H,alignOffset:z,arrowPadding:ie?0:f,collisionBoundary:u,collisionPadding:d,sticky:p,nodeId:P,keepMounted:y,disableAnchorTracking:m,collisionAvoidance:V,shift:ie?{crossAxis:!(`side`in V&&V.side===`flip`),rootBoundary:`layoutViewport`}:void 0,externalTree:C,adaptiveOrigin:M});q.useEffect(()=>{function e(e){e.open&&(e.parentNodeId===P&&v.set(`hoverEnabled`,!1),e.nodeId!==P&&e.parentNodeId===v.select(`floatingParentNodeId`)&&v.setOpen(!1,W(zn)))}return C.events.on(`menuopenchange`,e),()=>{C.events.off(`menuopenchange`,e)}},[v,C.events,P]),q.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,W(t))}return C.events.on(`menuopenchange`,e),()=>{C.events.off(`menuopenchange`,e)}},[C.events,v]);let oe=mt();q.useEffect(()=>{T||oe.clear()},[T,oe]),q.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?oe.isStarted()||oe.start(e,()=>{v.setOpen(!1,W(zn))}):v.setOpen(!1,W(zn))}else oe.clear()}return C.events.on(`itemhover`,e),()=>{C.events.off(`itemhover`,e)}},[C.events,T,O,v,oe]),q.useEffect(()=>{let e={open:T,nodeId:P,parentNodeId:F,reason:v.select(`lastOpenChangeReason`)};C.events.emit(`menuopenchange`,e)},[C.events,T,v,P,F]),gn(()=>{let e=I,t=L.current;if(e&&(L.current=e),t&&e&&e!==t){v.set(`instantType`,void 0);let e=new AbortController;return R(()=>{v.set(`instantType`,`trigger-change`)},e.signal),()=>{e.abort()}}},[I,R,v]);let se={open:T,side:ae.side,align:ae.align,anchorHidden:ae.anchorHidden,nested:x.type===`menu`,instant:j},le=x.type===`menubar`&&x.context.modal;Bn(T&&(le||E&&N!==`trigger-hover`),D===`touch`,A,O);let ue=Tt(e,se,{styles:ae.positionerStyles,transitionStatus:k,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!w,inert:!T}),de=w&&x.type!==`menu`&&(x.type!==`menubar`&&E&&N!==`trigger-hover`||x.type===`menubar`&&x.context.modal),fe=null;return x.type===`menubar`?fe=x.context.contentElement:x.type===void 0&&(fe=O),(0,J.jsxs)(Wr.Provider,{value:ae,children:[de&&(0,J.jsx)(Nt,{ref:x.type===`context-menu`||x.type===`nested-context-menu`?x.context.internalBackdropRef:null,inert:Rt(!T),cutout:fe}),(0,J.jsx)(ce,{id:P,children:(0,J.jsx)(xn,{elementsRef:v.context.itemDomElements,labelsRef:v.context.itemLabels,children:ue})})]})}),Xi=q.createContext(null);function Zi(e){let t=q.useContext(Xi);if(t===null&&!e)throw Error(Gt(5));return t}const Qi={...pi,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 $i=class extends l{constructor(e){super({...ta(),...e},ea(),Qi),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 ea(){return{positionerRef:q.createRef(),popupRef:q.createRef(),typingRef:{current:!1},itemDomElements:{current:[]},itemLabels:{current:[]},allowMouseUpTriggerRef:{current:!1},triggerFocusTargetRef:q.createRef(),beforeContentFocusGuardRef:q.createRef(),onOpenChangeComplete:void 0,triggerElements:new ht}}function ta(){return{...si(),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 F,floatingNodeId:void 0,floatingParentNodeId:null,itemProps:Je,keyboardEventRelay:void 0,closeDelay:0,adaptiveOrigin:void 0}}const na=q.createContext(void 0);function ra(){return q.useContext(na)}const ia=Xt(function(e){let{children:t,open:n,onOpenChange:r,onOpenChangeComplete:i,defaultOpen:a=!1,disabled:o=!1,modal:s,loopFocus:c=!0,orientation:l=`vertical`,actionsRef:u,closeParentOnEsc:d=!1,handle:f,triggerId:m,defaultTriggerId:h=null,highlightItemOnHover:g=!0}=e,_=Yr(!0),y=qr(!0),b=Zi(!0),S=ra(),C=q.useMemo(()=>S&&y?{type:`menu`,store:y.store}:b?{type:`menubar`,context:b}:_&&!y?{type:`context-menu`,context:_}:{type:void 0},[_,y,b,S]),w=aa({open:a,openProp:n,activeTriggerId:h,triggerIdProp:m,parent:C});w.useControlledProp(`openProp`,n),w.useControlledProp(`triggerIdProp`,m),w.useContextCallback(`onOpenChangeComplete`,i);let E=Le(),D=Le(),O=w.useState(`floatingTreeRoot`),k=or(O),A=p(),j=w.useState(`open`),M=w.useState(`activeTriggerElement`),ee=w.useState(`positionerElement`),N=w.useState(`hoverEnabled`),P=w.useState(`disabled`),F=w.useState(`lastOpenChangeReason`),I=w.useState(`parent`),L=w.useState(`activeIndex`),R=w.useState(`payload`),te=w.useState(`floatingParentNodeId`),ne=q.useRef(null),z=q.useRef(I.type!==`context-menu`),B=mt(),V=q.useRef(!0),re=mt(),H=te!=null,{openMethod:ie,triggerProps:ae}=rn(j);w.useSyncedValues({disabled:o,highlightItemOnHover:g,modal:I.type===void 0?s:void 0,openMethod:ie,rootId:E}),Pe(w);let{forceUnmount:oe}=T(j,w,()=>{w.set(`allowMouseEnter`,!1)});gn(()=>{_&&!y?w.update({parent:{type:`context-menu`,context:_},floatingNodeId:k,floatingParentNodeId:A}):y&&w.update({floatingNodeId:k,floatingParentNodeId:A})},[_,y,k,A,w]),q.useEffect(()=>{if(j||(ne.current=null),I.type===`context-menu`){if(!j){B.clear(),z.current=!1;return}B.start(500,()=>{z.current=!0})}},[B,j,I.type]),gn(()=>{!j&&!N&&w.set(`hoverEnabled`,!0)},[j,N,w]);let se=K((e,t)=>{let n=t.reason;if(!e&&!w.select(`open`)||j===e&&t.trigger===M&&F===n)return;let i=v(t);if(!e&&t.trigger==null&&(t.trigger=M??void 0),r?.(e,t),t.isCanceled)return;w.state.floatingRootContext.dispatchOpenChange(e,t);let a=t.event;if(e===!1&&a?.type===`click`&&a.pointerType===`touch`&&!V.current)return;e&&n===`trigger-focus`?(V.current=!1,re.start(300,()=>{V.current=!0})):(V.current=!0,re.clear());let o=(n===`trigger-press`||n===`item-press`)&&a.detail===0,s=!e&&(n===`escape-key`||n==null),c={open:e,openChangeReason:n};ne.current=t.event,Jn(c,e,t.trigger,i()),w.update(c),I.type===`menubar`&&(n===`trigger-focus`||n===`focus-out`||n===`trigger-hover`||n===`list-navigation`||n===`sibling-open`)?w.set(`instantType`,`group`):o||s?w.set(`instantType`,o?`click`:`dismiss`):w.set(`instantType`,void 0)}),ce=ai({popupStore:w,floatingId:D,nested:A!=null,onOpenChange:se}),le=ce.context.events;gn(()=>{let e=({open:e,eventDetails:t})=>se(e,t);return le.on(`setOpen`,e),()=>{le?.off(`setOpen`,e)}},[le,se]);let ue=q.useCallback(()=>{w.setOpen(!1,W(On))},[w]);q.useImperativeHandle(u,()=>({unmount:oe,close:ue}),[oe,ue]);let de;I.type===`context-menu`&&(de=I.context),q.useImperativeHandle(de?.positionerRef,()=>ee,[ee]),q.useImperativeHandle(de?.actionsRef,()=>({setOpen:se}),[se]);let fe=be(ce,{enabled:!P,bubbles:{escapeKey:d&&I.type===`menu`},outsidePress(){return I.type!==`context-menu`||ne.current?.type===`contextmenu`||z.current},externalTree:H?O:void 0}),pe=Ut(),me=q.useCallback(e=>{w.select(`activeIndex`)!==e&&w.set(`activeIndex`,e)},[w]),U=nr(ce,{enabled:!P,listRef:w.context.itemDomElements,activeIndex:L,nested:I.type!==void 0,loopFocus:c,orientation:l,parentOrientation:I.type===`menubar`?I.context.orientation:void 0,rtl:pe===`rtl`,disabledIndices:Ze,onNavigate:me,openOnArrowKeyDown:I.type!==`context-menu`,externalTree:H?O:void 0,focusItemOnHover:g}),he=q.useCallback(e=>{w.context.typingRef.current=e},[w]),ge=Wn(ce,{enabled:!P,listRef:w.context.itemLabels,elementsRef:w.context.itemDomElements,activeIndex:L,resetMs:500,onMatch:e=>{j&&e!==L&&w.set(`activeIndex`,e)},onTyping:he});x(w,{floatingRootContext:ce,activeTriggerProps:q.useMemo(()=>{let e=ct(ge.reference,U.reference,fe.reference,{onMouseMove(){w.set(`allowMouseEnter`,!0)}},ae);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=j,e},[w,ge.reference,U.reference,fe.reference,ae,j]),inactiveTriggerProps:q.useMemo(()=>{let e=ct(U.trigger,fe.trigger,ae);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=!1,e},[U.trigger,fe.trigger,ae]),popupProps:q.useMemo(()=>ct($n,{id:D,role:`menu`,"aria-labelledby":M?.id,onMouseMove(){w.set(`allowMouseEnter`,!0),I.type===`menu`&&w.set(`hoverEnabled`,!1)},onClick(){w.select(`hoverEnabled`)&&w.set(`hoverEnabled`,!1)},onKeyDown(e){let t=w.select(`keyboardEventRelay`);t&&!e.isPropagationStopped()&&t(e)}},ge.floating,U.floating,fe.floating),[M,D,I.type,w,ge.floating,U.floating,fe.floating]),itemProps:U.item??Je});let _e=q.useMemo(()=>({store:w,parent:C}),[w,C]),ve=(0,J.jsxs)(Kr.Provider,{value:_e,children:[f&&(0,J.jsx)(Ae,{handle:f,store:w}),typeof t==`function`?t({payload:R}):t]});return I.type===void 0||I.type===`context-menu`?(0,J.jsx)(Te,{externalTree:O,children:ve}):ve});function aa(e){return _t(()=>new $i(e)).current}function oa(e={}){let{highlightItemOnHover:t,highlightedIndex:n,onHighlightedIndexChange:r}=En(),{ref:i,index:a}=Qe(e),o=n===a,s=q.useRef(null),c=xe(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 sa(e){let{render:t,className:n,style:r,state:i=Je,props:a=Ze,refs:o=Ze,metadata:s,stateAttributesMapping:c,tag:l=`div`,...u}=e,{compositeProps:d,compositeRef:f}=oa({metadata:s});return B(l,e,{state:i,ref:[f,...o],props:[d,...a,u],stateAttributesMapping:c})}function ca(e){if(At(e)&&e.hasAttribute(`data-rootownerid`))return e.getAttribute(`data-rootownerid`);if(!yn(e))return ca(tn(e))}function la(e,t){let n=q.useRef(null);function r(t){wi.flushSync(()=>{e.setOpen(!1,W(pn,t.nativeEvent,t.currentTarget))}),qn(n.current)?.focus()}function i(n){let r=e.select(`positionerElement`);if(r&&Ne(n,r))e.context.beforeContentFocusGuardRef.current?.focus();else{wi.flushSync(()=>{e.setOpen(!1,W(pn,n.nativeEvent,n.currentTarget))});let i=_(e.context.triggerFocusTargetRef.current||t.current);for(;i!==null&&G(r,i);){let e=i;if(i=ke(i),i===e)break}i?.focus()}}return{preFocusGuardRef:n,handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}function ua(e){let{enabled:t=!0,mouseDownAction:n,open:r}=e,i=q.useRef(!1);return q.useMemo(()=>t?{onMouseDown:e=>{(n===`open`&&!r||n===`close`&&r)&&(i.current=!0,Pn(e.currentTarget).addEventListener(`click`,()=>{i.current=!1},{once:!0}))},onClick:e=>{i.current&&(i.current=!1,e.preventBaseUIHandler())}}:Je,[t,n,r])}const da=de(function(e,t){let{render:n,className:r,style:o,disabled:s=!1,nativeButton:c=!0,id:l,openOnHover:u,delay:d=100,closeDelay:f=0,handle:m,payload:h,...g}=e,_=qr(!0),v=hi(m)??_?.store;if(!v)throw Error(Gt(85));let y=P(l),b=v.useState(`isTriggerActive`,y),x=v.useState(`floatingRootContext`),S=v.useState(`isOpenedByTrigger`,y),C=v.useState(`triggerPopupId`,y),w=q.useRef(null),T=pa(),E=En(!0),D=Ve(),O=q.useMemo(()=>D??new F,[D]),{registerTrigger:A,isMountedByThisTrigger:j}=ge(y,w,v,{payload:h,closeDelay:f,parent:T,floatingTreeRoot:O,floatingNodeId:or(O),floatingParentNodeId:p(),keyboardEventRelay:E?.relayKeyboardEvent}),M=T.type===`menubar`,ee=v.useState(`disabled`),N=s||ee||M&&T.context.disabled,{getButtonProps:I,buttonRef:L}=a({disabled:N,native:c});q.useEffect(()=>{!S&&T.type===void 0&&(v.context.allowMouseUpTriggerRef.current=!1)},[v,S,T.type]);let R=q.useRef(null),te=mt(),ne=K(e=>{if(!R.current)return;te.clear(),v.context.allowMouseUpTriggerRef.current=!1;let t=e.target;G(R.current,t)||G(v.select(`positionerElement`),t)||t===R.current||t!=null&&ca(t)===v.select(`rootId`)||bt(e,R.current)||O.events.emit(`close`,{domEvent:e,reason:i})});q.useEffect(()=>{S&&v.select(`lastOpenChangeReason`)===`trigger-hover`&&Pn(R.current).addEventListener(`mouseup`,ne,{once:!0})},[S,ne,v]);let z=M&&T.context.hasSubmenuOpen,V=Ei(x,{enabled:(u??z)&&!N&&(!M||z&&!j),handleClose:ji({blockPointerEvents:!M}),mouseOnly:!0,move:!1,restMs:T.type===void 0?d:void 0,delay:{close:f},triggerElementRef:w,externalTree:O,isActiveTrigger:b,isClosing:()=>v.select(`transitionStatus`)===`ending`}),re=fa(S,v.select(`lastOpenChangeReason`)),H=k(x,{enabled:!N,event:S&&M?`click`:`mousedown`,toggle:!0,ignoreMouse:!1,stickIfOpen:T.type===void 0&&re}),ie=_i(x,{enabled:!N&&z}),ae=ua({open:S,enabled:M,mouseDownAction:`open`}),oe=q.useMemo(()=>ct(ie.reference,H.reference),[ie.reference,H.reference]),se=v.useState(`triggerProps`,j),{preFocusGuardRef:ce,handlePreFocusGuardFocus:le,handleFocusTargetFocus:ue}=la(v,w),de={disabled:N,open:S},fe=[R,t,L,A,w],pe=[oe,V??Je,se,{"aria-haspopup":`menu`,"aria-controls":C,id:y,onMouseDown:e=>{v.select(`open`)||(te.start(200,()=>{v.context.allowMouseUpTriggerRef.current=!0}),Pn(e.currentTarget).addEventListener(`mouseup`,ne,{once:!0}))}},M?{role:`menuitem`}:{},ae,g,I],me=B(`button`,e,{enabled:!M,stateAttributesMapping:tt,state:de,ref:fe,props:pe});return M?(0,J.jsx)(sa,{tag:`button`,render:n,className:r,style:o,state:de,refs:fe,props:pe,stateAttributesMapping:tt}):S?(0,J.jsxs)(q.Fragment,{children:[(0,J.jsx)(wn,{ref:ce,onFocus:le},`${y}-pre-focus-guard`),(0,J.jsx)(q.Fragment,{children:me},y),(0,J.jsx)(wn,{ref:v.context.triggerFocusTargetRef,onFocus:ue},`${y}-post-focus-guard`)]}):(0,J.jsx)(q.Fragment,{children:me},y)});function fa(e,t){let n=mt(),[r,i]=q.useState(!1);return gn(()=>{e&&t===`trigger-hover`?(i(!0),n.start(500,()=>{i(!1)})):e||(n.clear(),i(!1))},[e,t,n]),r}function pa(){let e=Zi(!0);return q.useMemo(()=>e?{type:`menubar`,context:e}:{type:void 0},[e])}const ma=q.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return B(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})});function ha(e){return e==null||e.hasAttribute(`disabled`)||e.getAttribute(`aria-disabled`)===`true`}function ga({...e}){return(0,J.jsx)(ia,{"data-slot":`dropdown-menu`,...e})}function _a({...e}){return(0,J.jsx)(da,{"data-slot":`dropdown-menu-trigger`,...e})}function va({align:e=`start`,alignOffset:t=0,side:n=`bottom`,sideOffset:r=4,className:i,container:a,...o}){return(0,J.jsx)(Ji,{container:a,children:(0,J.jsx)(Yi,{className:`isolate z-50 outline-none`,align:e,alignOffset:t,side:n,sideOffset:r,children:(0,J.jsx)(Gi,{"data-slot":`dropdown-menu-content`,className:H(`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 ya({className:e,inset:t,variant:n=`default`,...r}){return(0,J.jsx)($r,{"data-slot":`dropdown-menu-item`,"data-inset":t,"data-variant":n,className:H(`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 ba({className:e,...t}){return(0,J.jsx)(ma,{"data-slot":`dropdown-menu-separator`,className:H(`-mx-1 my-1 h-px bg-border`,e),...t})}function xa({chat:e,state:t,thread:n,onDelete:r}){let i=(0,q.useRef)(null),a=(0,q.useRef)(null),[o,s]=(0,q.useState)(!1),[c,l]=(0,q.useState)(``),[u,d]=(0,q.useState)(!1),[f,p]=(0,q.useState)(!1),m=n.title??``,h=n.role===`manager`&&t.status!==`submitted`&&t.status!==`streaming`;return(0,q.useEffect)(()=>{o&&requestAnimationFrame(()=>a.current?.select())},[o]),(0,q.useEffect)(()=>{if(!f)return;let e=setTimeout(()=>p(!1),2e3);return()=>clearTimeout(e)},[f]),(0,J.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,J.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,J.jsx)($e,{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,J.jsx)(We,{type:`submit`,size:`sm`,disabled:!c.trim()||u,children:u?`Saving…`:`Save`})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,title:m,children:m}),f&&(0,J.jsx)(`span`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Copied`}),(0,J.jsxs)(ga,{children:[(0,J.jsx)(_a,{"aria-label":`Conversation actions`,title:`Conversation actions`,render:(0,J.jsx)(We,{variant:`ghost`,size:`icon-sm`}),children:(0,J.jsx)(Er,{})}),(0,J.jsxs)(va,{container:i,align:`end`,className:`w-40`,children:[(0,J.jsxs)(ya,{disabled:!h,onClick:()=>{l(n.title??``),s(!0)},children:[(0,J.jsx)(Mr,{}),`Rename`]}),(0,J.jsxs)(ya,{disabled:t.messages.length===0,onClick:()=>{navigator.clipboard.writeText(ve(m,t.messages)).then(()=>p(!0))},children:[(0,J.jsx)(wr,{}),`Copy Markdown`]}),(0,J.jsx)(ba,{}),(0,J.jsxs)(ya,{variant:`destructive`,disabled:!h,onClick:()=>{e.deleteThread().then(e=>{e&&r(n.id)})},children:[(0,J.jsx)(Pr,{}),`Delete`]})]})]})]})})}const Sa=[];function Ca(e){let{loopFocus:t=!0,orientation:n=`both`,grid:r,onLoop:i,direction:a,highlightedIndex:o,onHighlightedIndexChange:s,rootRef:l,enableHomeAndEndKeys:u=!1,stopEventPropagation:d,disabledIndices:f,modifierKeys:p=Sa}=e,[m,h]=q.useState(0),g=r!=null,_=q.useRef(null),v=xe(_,l),y=q.useRef([]),x=q.useRef(!1),S=o??m,C=K((e,t=!1)=>{if((s??h)(e),t){let t=y.current[e];Hi(_.current,t,a,n)}}),T=K(e=>{if(e.size===0||x.current)return;x.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)C(i);else if(c(t,S,f)){let e=w(t,{disabledIndices:f});$t(t,e)||C(e)}Hi(_.current,r,a,n)});gn(()=>{if(f==null||o!=null||!x.current)return;let e=y.current;if(c(e,S,f)){let t=w(e,{disabledIndices:f});$t(e,t)||C(t)}},[f,o,S,y,C]);let E=K((e,t,n)=>i?i(e,t,n,y):n),D=K(e=>{let o=e.key===`Home`||e.key===`End`;if(!Ri.has(e.key)||!u&&o||wa(e,p)||!_.current)return;let s=a===`rtl`,c=s?Ii:Li,l=s?Li:Ii,m=n===`vertical`?Fi:c,h=n===`vertical`?Pi:l,v=ar(e.nativeEvent);if(v!=null&&Vi(v)&&!ha(v)){let t=v.selectionStart,n=v.selectionEnd,r=v.value;if(t==null||e.shiftKey||t!==n||e.key!==h&&t<r.length||e.key!==m&&t>0)return}let x=S,T=he(y,f),D=b(y,f);r!=null&&(x=r({disabledIndices:f,elementsRef:y,event:e,highlightedIndex:S,loopFocus:t,maxIndex:D,minIndex:T,onLoop:E,orientation:n,rtl:s}));let O=n!==`vertical`&&e.key===c||n!==`horizontal`&&e.key===`ArrowDown`,k=n!==`vertical`&&e.key===l||n!==`horizontal`&&e.key===`ArrowUp`;u&&(e.key===`Home`?x=T:e.key===`End`&&(x=D)),x===S&&(O||k)&&(t&&x===D&&O?(x=T,i&&(x=i(e,S,x,y))):t&&x===T&&k?(x=D,i&&(x=i(e,S,x,y))):x=w(y.current,{startingIndex:x,decrement:k,disabledIndices:f})),x!==S&&!$t(y.current,x)&&(d&&e.stopPropagation(),(g||o||O||k)&&e.preventDefault(),C(x,!0),queueMicrotask(()=>{y.current[x]?.focus()}))});return{props:{ref:v,onFocus(e){let t=_.current,n=ar(e.nativeEvent);!t||n==null||!Vi(n)||n.setSelectionRange(0,n.value.length)},onKeyDown:D},highlightedIndex:S,onHighlightedIndexChange:C,elementsRef:y,onMapChange:T,relayKeyboardEvent:D}}function wa(e,t){for(let n of zi)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}function Ta(e){let{render:t,className:n,style:r,refs:i=Ze,props:a=Ze,state:o=Je,stateAttributesMapping:s,highlightedIndex:c,onHighlightedIndexChange:l,orientation:u,grid:d,loopFocus:f,onLoop:p,enableHomeAndEndKeys:m,onMapChange:h,stopEventPropagation:g=!0,rootRef:_,disabledIndices:v,modifierKeys:y,highlightItemOnHover:b=!1,tag:x=`div`,...S}=e,{props:C,highlightedIndex:w,onHighlightedIndexChange:T,elementsRef:E,onMapChange:D,relayKeyboardEvent:O}=Ca({grid:d,loopFocus:f,onLoop:p,orientation:u,highlightedIndex:c,onHighlightedIndexChange:l,rootRef:_,stopEventPropagation:g,enableHomeAndEndKeys:m,direction:Ut(),disabledIndices:v,modifierKeys:y}),k=B(x,e,{state:o,ref:i,props:[C,...a,S],stateAttributesMapping:s}),A=q.useMemo(()=>({highlightedIndex:w,onHighlightedIndexChange:T,highlightItemOnHover:b,relayKeyboardEvent:O}),[w,T,b,O]);return(0,J.jsx)(dn.Provider,{value:A,children:(0,J.jsx)(xn,{elementsRef:E,onMapChange:e=>{h?.(e),D(e)},children:k})})}const Ea=q.createContext(void 0);function Da(){let e=q.useContext(Ea);if(e===void 0)throw Error(Gt(64));return e}const Oa={tabActivationDirection:e=>({"data-activation-direction":e})},ka=q.forwardRef(function(e,t){let{className:n,defaultValue:r=0,onValueChange:i,orientation:a=`horizontal`,render:o,value:s,style:c,...l}=e,u=e.defaultValue!==void 0,d=q.useRef([]),[f,p]=q.useState(()=>new Map),[m,h]=cn({controlled:s,default:r,name:`Tabs`,state:`value`}),g=s!==void 0,[_,v]=q.useState(()=>new Map),y=q.useRef(void 0),b=q.useCallback(e=>Aa(_,e),[_]),[x,S]=q.useState(()=>({previousValue:m,tabActivationDirection:`none`})),{previousValue:C,tabActivationDirection:w}=x,T=w,E=!1;C!==m&&(T=ja(C,m,a,_),E=C!=null&&m!=null&&b(m)==null);let D=E?C:m,O=C!==D||w!==T;gn(()=>{O&&S({previousValue:D,tabActivationDirection:T})},[D,O,T]);let k=K((e,t)=>{t.activationDirection=ja(m,e,a,_),i?.(e,t),!t.isCanceled&&h(e)}),A=K((e,t)=>{i?.(e,W(t,void 0,void 0,{activationDirection:`none`}))}),j=K((e,t)=>(p(n=>{let r=new Map(n);return r.set(e,t),r}),()=>{p(n=>{if(n.get(e)!==t)return n;let r=new Map(n);return r.delete(e),r})})),M=q.useCallback(e=>f.get(e),[f]),ee=q.useCallback(e=>{for(let t of _.values())if(e===t.value)return t.id},[_]),N=q.useMemo(()=>({getTabElementBySelectedValue:b,getTabIdByPanelValue:ee,getTabPanelIdByValue:M,onValueChange:k,orientation:a,registerMountedTabPanel:j,setTabMap:v,tabActivationDirection:T,value:m}),[b,ee,M,k,a,j,v,T,m]),P=q.useMemo(()=>{for(let e of _.values())if(e.value===m)return e},[_,m]),F=q.useMemo(()=>{for(let e of _.values())if(!e.disabled)return e.value},[_]),I=q.useRef(!u),L=q.useRef(r),R=q.useRef(u),te=q.useRef(!1);gn(()=>{if(g)return;function e(e,t){h(e),S({previousValue:e,tabActivationDirection:`none`}),A(e,t),I.current=!1}if(_.size===0){te.current&&m!==null&&!y.current?.isConnected&&e(null,jn);return}te.current=!0,y.current=_.keys().next().value;let t=P?.disabled,n=P==null&&m!==null;if(!t&&m===L.current&&(R.current=!1),R.current&&t&&m===L.current)return;let r=I.current;if(t||n){let n=F??null;if(m===n){I.current=!1;return}let i=jn;r?i=qt:t&&(i=Ot),e(n,i);return}r&&P!=null&&(A(m,qt),I.current=!1)},[F,g,A,P,h,_,m]);let ne=B(`div`,e,{state:{orientation:a,tabActivationDirection:T},ref:t,props:l,stateAttributesMapping:Oa});return(0,J.jsx)(Ea.Provider,{value:N,children:(0,J.jsx)(xn,{elementsRef:d,children:ne})})});function Aa(e,t){for(let[n,r]of e.entries())if(t===r.value)return n;return null}function ja(e,t,n,r){if(e==null||t==null)return`none`;let[i,a,o]=n===`horizontal`?[`left`,`left`,`right`]:[`top`,`up`,`down`],s=Aa(r,e),c=Aa(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 Ma=q.createContext(void 0);function Na(){let e=q.useContext(Ma);if(e===void 0)throw Error(Gt(65));return e}const Pa=q.forwardRef(function(e,t){let{className:n,disabled:r=!1,render:i,value:o,id:s,nativeButton:c=!0,style:l,...u}=e,{value:d,getTabPanelIdByValue:f,onValueChange:p,orientation:m,tabActivationDirection:h}=Da(),{activateOnFocus:g,registerTabResizeObserverElement:_,tabsListElement:v}=Na(),{highlightedIndex:y,onHighlightedIndexChange:b}=En(),x=P(s),{compositeProps:S,compositeRef:C,index:w}=oa({metadata:q.useMemo(()=>({disabled:r,id:x,value:o}),[r,x,o])}),T=o===d,E=q.useRef(!1),D=q.useRef(null),O=K(e=>{D.current?.(),D.current=e?_(e):null});gn(()=>{if(E.current){E.current=!1;return}if(!(T&&w>-1&&y!==w))return;let e=v;if(e!=null){let t=se(Pn(e));if(t&&G(e,t))return}r||b(w)},[T,w,y,b,r,v]);let{getButtonProps:k,buttonRef:A}=a({disabled:r,native:c,focusableWhenDisabled:!0}),j=f(o),M=q.useRef(!1),ee=q.useRef(!1);function N(e){p(o,W(yt,e.nativeEvent,void 0,{activationDirection:`none`}))}function F(e){T||r||N(e)}function I(e){T||r||g&&(!M.current||ee.current)&&N(e)}function L(e){if(T||r)return;M.current=!0,ee.current=e.button===0;let t=Pn(e.currentTarget);function n(){M.current=!1,ee.current=!1,t.removeEventListener(`pointerup`,n),t.removeEventListener(`pointercancel`,n)}t.addEventListener(`pointerup`,n),t.addEventListener(`pointercancel`,n)}return B(`button`,e,{state:{disabled:r,active:T,orientation:m,tabActivationDirection:h},ref:[t,A,C,O],props:[S,{role:`tab`,"aria-controls":j,"aria-selected":T,id:x,onClick:F,onFocus:I,onPointerDown:L,"data-composite-item-active":T?``:void 0,onKeyDownCapture(){E.current=!0}},u,k],stateAttributesMapping:Oa})}),Fa={...Oa,...Lt},Ia=q.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}=Da(),p=P(),{ref:m,index:h}=Qe(),g=r===c,{mounted:_,transitionStatus:v,setMounted:y}=Ht(g),b=!_,x=l(r),S={hidden:b,orientation:u,tabActivationDirection:d,transitionStatus:v},C=q.useRef(null),w=B(`div`,e,{state:S,ref:[t,m,C],props:[{"aria-labelledby":x,hidden:b,id:p,role:`tabpanel`,tabIndex:g?0:-1,inert:Rt(!g),"data-index":h},s],stateAttributesMapping:Fa});return at({open:g,ref:C,onComplete(){g||y(!1)}}),gn(()=>{if(!(p==null||b&&!a))return f(r,p)},[b,a,r,p,f]),a||_?w:null}),La=q.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}=Da(),[d,f]=q.useState(0),[p,m]=q.useState(null),h=q.useRef(new Set),g=q.useRef(new Set),_=q.useRef(null);gn(()=>{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=K(e=>(h.current.add(e),()=>{h.current.delete(e)})),y=K(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=q.useMemo(()=>({activateOnFocus:n,registerIndicatorUpdateListener:v,registerTabResizeObserverElement:y,tabsListElement:p}),[n,v,y,p]);return(0,J.jsx)(Ma.Provider,{value:S,children:(0,J.jsx)(Ta,{render:a,className:r,style:o,state:b,refs:[t,m],props:[x,s],stateAttributesMapping:Oa,highlightedIndex:d,enableHomeAndEndKeys:!0,loopFocus:i,orientation:c,onHighlightedIndexChange:f,onMapChange:l,disabledIndices:Ze})})});function Ra(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 za(e){let t=new Date,n=[];for(let r of e){let e=Ra(r.updatedAt,t),i=n.at(-1);i?.value===e?i.items.push(r):n.push({value:e,items:[r]})}return n}const Ba=e=>e.title||`Untitled`,Va=e=>e.stopPropagation();function Ha({chat:e,state:t,onSelect:n,onDelete:i}){let a=(0,q.useRef)(null),o=(0,q.useRef)(null),[s,c]=(0,q.useState)(``),[l,d]=(0,q.useState)(!1),[f,p]=(0,q.useState)(0),[m]=mn(s.trim(),{wait:300}),h=(0,q.useContext)(r),[g]=(0,q.useState)(()=>new Ke),_=ne({queryKey:[`thread-history`,(0,q.useId)(),f,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??g),v=s.trim()!==m||_.isPending,{hasNextPage:y,isFetching:b,isError:x,fetchNextPage:S}=_;(0,q.useEffect)(()=>{let e=o.current;if(!l||!e||v||!y||b||x)return;let t=()=>{e.scrollHeight-e.scrollTop-e.clientHeight<48&&S({cancelRefetch:!1})};return t(),e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[l,v,y,b,x,S,_.data]);let C=v?[]:za(_.data?.pages.flatMap(e=>e.items)??[]),w=t.thread?.id,T=t.status===`submitted`||t.status===`streaming`,E=t=>{e.deleteThread(t).then(e=>{e&&(i(t.id),_.refetch())})};return(0,J.jsx)(`div`,{ref:a,"data-slot":`thread-history`,children:(0,J.jsxs)(I,{items:C,filteredItems:C,value:null,onValueChange:t=>{!t||t.id===w||e.openThread(t.id).then(n)},itemToStringLabel:Ba,itemToStringValue:e=>e.id,isItemEqualToValue:(e,t)=>e.id===t.id,onInputValueChange:(e,t)=>{c(t.reason===`input-change`?e:``)},onOpenChange:e=>{d(e),e?p(e=>e+1):c(``)},children:[(0,J.jsx)(Mn,{"aria-label":`Show older chats`,title:`Show older chats`,render:(0,J.jsx)(We,{variant:`ghost`,size:`icon-sm`}),children:(0,J.jsx)(Cr,{})}),(0,J.jsxs)(Ce,{container:a,align:`end`,"aria-label":`Chat history`,"aria-busy":v||_.isFetching?!0:void 0,className:`w-80 min-w-0`,children:[(0,J.jsx)(ze,{"aria-label":`Search chats`,placeholder:`Search chats…`,maxLength:255,showTrigger:!1}),(0,J.jsx)(A,{className:`text-center text-sm text-muted-foreground [&:not(:empty)]:py-2`,children:v||_.isFetchingNextPage?`Loading…`:null}),(0,J.jsx)(rr,{children:!v&&!_.isError?`No chats found.`:null}),(0,J.jsx)(He,{ref:o,className:`max-h-[min(24rem,calc(var(--available-height)---spacing(9)))]`,children:e=>(0,J.jsxs)(u,{items:e.items,children:[(0,J.jsx)(Fe,{children:e.value}),(0,J.jsx)(ae,{children:e=>{let t=e.id===w;return(0,J.jsxs)(N,{value:e,"aria-label":Ba(e),"aria-current":t?`true`:void 0,className:H(`group/thread ps-2 pe-1`,t&&`bg-muted font-semibold`),children:[(0,J.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:Ba(e)}),e.role===`manager`&&(0,J.jsx)(We,{variant:`ghost`,size:`icon-xs`,"aria-label":`Delete ${Ba(e)}`,title:`Delete`,disabled:t&&T,className:`opacity-0 group-hover/thread:opacity-100 group-data-highlighted/thread:opacity-100 focus-visible:opacity-100`,onPointerDown:Va,onMouseDown:Va,onClick:t=>{t.stopPropagation(),E(e)},children:(0,J.jsx)(Pr,{})})]},e.id)}})]},e.value)}),!v&&_.isError&&(0,J.jsxs)(`div`,{className:`p-2 text-xs`,role:`alert`,children:[`Could not load chats.`,(0,J.jsx)(We,{variant:`ghost`,size:`sm`,disabled:_.isFetching,onClick:()=>void(_.isFetchNextPageError?_.fetchNextPage():_.refetch()),children:`Retry`})]})]})]})})}function Ua({className:e,orientation:t=`horizontal`,...n}){return(0,J.jsx)(ka,{"data-slot":`tabs`,"data-orientation":t,className:H(`group/tabs flex gap-2 data-horizontal:flex-col`,e),...n})}const Wa=Cn(`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 Ga({className:e,variant:t=`default`,...n}){return(0,J.jsx)(La,{"data-slot":`tabs-list`,"data-variant":t,className:H(Wa({variant:t}),e),...n})}function Ka({className:e,...t}){return(0,J.jsx)(Pa,{"data-slot":`tabs-trigger`,className:H(`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 qa({className:e,...t}){return(0,J.jsx)(Ia,{"data-slot":`tabs-content`,className:H(`flex-1 text-sm outline-none`,e),...t})}const Ja=new Set([`c`,`cpp`,`css`,`go`,`html`,`js`,`json`,`jsx`,`mjs`,`py`,`rb`,`rs`,`sh`,`sql`,`toml`,`ts`,`tsx`,`yaml`,`yml`]);function Ya(e){let t=e.slice(e.lastIndexOf(`.`)+1).toLowerCase();return Ja.has(t)?(0,J.jsx)(Or,{}):t===`csv`||t===`tsv`?(0,J.jsx)(kr,{}):(0,J.jsx)(rt,{})}function Xa(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function Za({file:e}){return(0,J.jsxs)(`div`,{className:`flex items-start gap-1`,children:[(0,J.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,J.jsx)(o,{icon:Ya(e.path),label:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`font-mono wrap-anywhere`,children:e.label}),(0,J.jsxs)(`span`,{className:`text-muted-foreground`,children:[` · `,e.lines===1?`1 line`:`${e.lines} lines`]})]}),children:(0,J.jsx)(`div`,{className:`mt-1 flex min-w-0 flex-col`,children:(0,J.jsx)(Dn,{emptyLabel:`Empty file`,caption:e.label===e.path?void 0:e.path,children:e.content})})})}),(0,J.jsx)(We,{variant:`ghost`,size:`icon-sm`,"aria-label":`Download ${e.label}`,title:`Download`,onClick:()=>Qt(Xa(e.path),e.content),children:(0,J.jsx)(Dr,{})})]})}function Qa({run:e}){let t=e.timedOut||e.exitCode!==void 0&&e.exitCode!==0;return(0,J.jsx)(o,{icon:(0,J.jsx)(Ft,{}),running:!e.finished,label:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`font-mono wrap-anywhere`,children:e.command}),e.finished&&(0,J.jsx)(`span`,{className:H(`ms-1`,t?`text-destructive`:`text-muted-foreground`),children:lt(e)})]}),children:(0,J.jsx)(`div`,{className:`mt-1 flex min-w-0 flex-col`,children:(0,J.jsx)(fn,{run:e})})})}function $a({activity:e}){let[t,n]=(0,q.useState)(!1),r=e.files.length,i=e.commands.length;return(0,J.jsxs)(`div`,{className:`relative w-full`,children:[t&&(0,J.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,J.jsxs)(Ua,{defaultValue:`files`,className:`flex min-h-0 flex-col gap-0`,children:[(0,J.jsxs)(Ga,{variant:`line`,className:`w-full shrink-0 px-2`,children:[(0,J.jsxs)(Ka,{value:`files`,children:[(0,J.jsx)(rt,{}),`Files`,r>0&&(0,J.jsx)(`span`,{className:`text-muted-foreground`,children:r})]}),(0,J.jsxs)(Ka,{value:`log`,children:[(0,J.jsx)(Ft,{}),`Log`,i>0&&(0,J.jsx)(`span`,{className:`text-muted-foreground`,children:i})]})]}),(0,J.jsx)(qa,{value:`files`,className:`min-h-0 overflow-y-auto p-2`,children:r===0?(0,J.jsx)(eo,{children:`The agent has not written any files yet.`}):e.files.map(e=>(0,J.jsx)(Za,{file:e},e.toolCallId))}),(0,J.jsx)(qa,{value:`log`,className:`min-h-0 overflow-y-auto p-2`,children:i===0?(0,J.jsx)(eo,{children:`The agent has not run any commands yet.`}):e.commands.map(e=>(0,J.jsx)(Qa,{run:e},e.toolCallId))})]})}),(0,J.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,J.jsx)(Tr,{}),(0,J.jsxs)(`span`,{className:`flex-1`,children:[`Sandbox · `,r,` `,r===1?`file`:`files`,` · `,i,` `,i===1?`command`:`commands`]}),(0,J.jsx)(Sr,{className:H(`shrink-0 transition-transform`,t&&`rotate-180`)})]})]})}function eo({children:e}){return(0,J.jsx)(`p`,{className:`px-1 py-2 text-xs text-muted-foreground italic`,children:e})}function to({status:e}){if(e===`ready`)return null;let t=e===`starting`;return(0,J.jsxs)(_n,{role:`status`,className:`w-full rounded-full border bg-muted/50 px-3 py-1.5`,children:[(0,J.jsx)(vt,{children:t?(0,J.jsx)(Rn,{}):(0,J.jsx)(Bt,{})}),(0,J.jsx)(An,{className:t?`shimmer`:void 0,children:t?`Starting the sandbox…`:`The sandbox could not be started`})]})}let no;function ro(e,t,n){if(!n){if(!no)try{let e=`astralbeam:draft-session`;no=globalThis.sessionStorage?.getItem(e)??zt(),globalThis.sessionStorage?.setItem(e,no)}catch{no??=zt()}n=`new:${no}`}return JSON.stringify([e.replace(/\/+$/,``),t,n])}function io(e,t,n,r){if(!t)return``;let i=`astralbeam:draft:${ro(e,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 ao({apiUrl:e,identity:t,threadId:n,update:r,moveTo:i}){let a=()=>{if(!t)return[];let a=`astralbeam:attachments:${ro(e,t,n)}`,o=e=>JSON.parse(globalThis.localStorage?.getItem(e)??`[]`),s=o(a);if(r&&(s=r(s).filter(e=>e.status===`ready`&&e.fileId!==void 0)),i!==void 0){let n=`astralbeam:attachments:${ro(e,t,i)}`;s=[...new Map([...o(n),...s].map(e=>[e.id,e])).values()],globalThis.localStorage?.setItem(n,JSON.stringify(s.map(({data:e,...t})=>t))),globalThis.localStorage?.removeItem(a)}else r&&(s.length?globalThis.localStorage?.setItem(a,JSON.stringify(s.map(({data:e,...t})=>t))):globalThis.localStorage?.removeItem(a));return s};return globalThis.navigator?.locks?navigator.locks.request(`astralbeam:attachment-drafts`,a):Promise.resolve().then(a)}function oo(e){if(e)return{onChunk:co(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 so(e){try{return JSON.parse(e)}catch{return e}}function co(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:so(t?.args??``)});break}case`TOOL_CALL_RESULT`:e(`tool`,`result for tool call ${a.toolCallId}`,{toolCallId:a.toolCallId,messageId:a.messageId,content:so(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 lo=class extends Error{missingFeature;constructor(e){super(uo(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function uo(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 fo(e){if(!e.body)throw new lo(`Response.body`);if(typeof e.body.getReader!=`function`)throw new lo(`Response.body.getReader`);return e.body.getReader()}function po(){if(typeof globalThis.TextDecoder!=`function`)throw new lo(`TextDecoder`);return new globalThis.TextDecoder}function mo(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function ho(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 go(e){let t=ho(e.createdAt),n=e.parts.map(e=>{if(e.type!==`tool-result`)return e;let t=ho(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 _o(e){return e.map(go)}function vo(e){return Object.keys(e).length>0?e:void 0}function yo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function bo(e,t){return yo(e)?e:xo(Array.isArray(e)?e:void 0,t)}function xo(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=vo({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...n?.cacheWriteInputTokens===void 0?{}:{cacheWriteTokens:n.cacheWriteInputTokens},...r}),s=vo({...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 So(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Co(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return So(e.tanstack)&&So(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function X(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 wo(e,t){let n=e.metadata,r=X(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}let Z=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 To=`redacted_thinking-`;function Eo(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var Do=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 Oo(e,t){return e>>>t|e<<32-t}function ko(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=Oo(t,7)^Oo(t,18)^t>>>3,i=Oo(n,17)^Oo(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=Oo(a,6)^Oo(a,11)^Oo(a,25),s=a&g^~a&_,c=v+o+s+(Do[e]??0)+(h[e]??0)>>>0,l=(Oo(t,2)^Oo(t,13)^Oo(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 Ao(e){return`sha256:${ko(e)}`}function jo(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(jo(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${jo(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function Mo(e){return jo(e,new WeakSet)}function No(e,t=Ao){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function Po(e){typeof e!=`object`||!e||Object.isFrozen(e)||(Object.values(e).forEach(Po),Object.freeze(e))}function Q(e){let t=JSON.parse(Mo(e));return Po(t),t}function Fo(e){let t=Q([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=Mo(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:No(n)})}function Io(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function Lo(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function Ro(e){if(!Lo(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 zo(e){return Lo(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 Bo(e){return Object.keys(e).length>0?e:void 0}function Vo(e){if(Array.isArray(e)){let t=e.map(e=>Ho(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=Ho(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function Ho(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=Ho(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=Vo(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=Vo(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:Bo(r)}}function Uo(e,t=`input`){if(Ro(e)){let n=Io(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(zo(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`?Io(e):e}function Wo(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!Ro(e)&&!zo(e))return e;let i=Uo(e,r);return!i||typeof i!=`object`||!n?i:Ho(i,i.required||[]).schema}async function Go(e,t){if(!zo(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 Ko=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function qo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Jo(e){return qo(e)&&Object.keys(e).some(e=>Ko.has(e))}function Yo(e){return zo(e)||Ro(e)||Jo(e)}function Xo(e){if(!qo(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>Yo(e[t]))}function Zo(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Qo(e){if(zo(e)){let t=Ro(e)?Zo(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Jo(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function $o(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 es(e,t){let n=t===void 0?null:Qo(t),r=null,i=null;if(e!==void 0)if(zo(e)||Jo(e))r=Qo(e),i=r;else if(Xo(e))r=e.approve===void 0?null:Qo(e.approve),i=e.reject===void 0?null:Qo(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`);let a={oneOf:[$o({approved:!0,payload:r,inputSchema:n}),$o({approved:!1,payload:i,inputSchema:null})]},o=Mo(a),s=Mo({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:No(o),approvalSchemaHash:No(s)}}function ts(e){return No(e===void 0?`undefined`:Mo(Qo(e).jsonSchema??{standardValidator:`unserialized`}))}var ns=`tanstack:interruptBinding`,rs=ns;function is(e){return e&&typeof e==`object`?e:null}function as(e,t){return typeof e[t]==`string`?e[t]:void 0}function os(e){let t=e.v;return t===void 0||t===1}function ss(e){let t=is(e.metadata),n=t?is(t[rs]):null;if(!n||as(n,`interruptId`)!==e.id||!os(n))return;let r=as(n,`kind`),i=as(n,`interruptId`),a=as(n,`responseSchemaHash`),o=as(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=as(n,`definitionId`),t=as(n,`key`),s=n.batchIndex,c=as(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=as(n,`toolName`),c=as(n,`toolCallId`);if(!(!s||!c)){if(r===`client-tool-execution`){let e=as(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=as(n,`inputSchemaHash`),t=as(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 cs(e){let t=ss(e);if(!t)return;let n=is(e.metadata),r=n?is(n[rs]):null;if(!r)return;let i=as(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var ls=`tanstack:interruptPayload`;function us(e,t){if(!Ro(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:Mo(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function ds(e){return No(us(e,`Interrupt schema`).canonicalJson)}var fs=`tanstack:interruptContinuation`;function ps(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ms(e){return{[fs]:e}}function hs(e){let t=ss(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=ps(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[ls]}:{}}}function gs(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function _s(e){return gs(e)!==null}function vs(e,t){return e?.startsWith(`${t}-segment-`)===!0}var ys=new Set([`text`,`image`,`audio`,`video`,`document`]);function bs(e){return e===`cancelled`||e===`denied`}function xs(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!ys.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 Ss(e){return Array.isArray(e)&&e.length>0&&e.every(xs)}function Cs(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function ws(e){return typeof e==`string`||Ss(e)?e:JSON.stringify(e)}function Ts(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Es(e){if(!Ts(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function Ds(e){if(!Ts(e)||!Ts(e.metadata))return;let t=e.metadata.tanstack;if(!Ts(t)||!Ts(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!Os(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},...Ts(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},...Ts(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function Os(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function ks(e){if(!Ts(e))return e;let{subagentRunId:t,...n}=e,r=Ts(n.metadata)?n.metadata:void 0,i=Ts(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 As(e){let t=new Map;for(let n of e){let e=Es(n);e!==void 0&&!t.has(e)&&t.set(e,Ds(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=Es(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=Ds(t);s&&(o.info=s),s?.placeholder||o.messages.push(ks(t))}return{top:r,groups:[...i.values()]}}function js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ms(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function Ns(e){try{return JSON.stringify(e)??``}catch{return``}}function Ps(e){return typeof e==`string`&&e!==``?e:void 0}function Fs(e){if(`encryptedValue`in e){let t=Ps(e.encryptedValue);if(t!==void 0)return t}return Ps(X(e)?.signature)}function Is(e){return`id`in e&&Eo(e.id)?{redacted:!0}:{}}function Ls(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function Rs(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function zs(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=Bs(n);e!==``&&t.push(e)}return t.join(`
2
-
3
- `)}function Bs(e){let t=[];for(let n of e.subagent.messages){if(!(`parts`in n))continue;let e=zs(n.parts).trim();e!==``&&t.push(e)}return t.length===0?``:`${e.subagent.name}:\n${t.join(`
4
-
5
- `)}`}function Vs(e){return Array.isArray(e)?e:Rs(e)}function Hs(e){if(!(`role`in e)||e.role!==`tool`)return e;let t=e,n=X(t)?.toolResult;if(!js(n)||`content`in n&&!Ss(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=Us(n.createdAt);e&&Reflect.set(r,`createdAt`,e)}Ss(n.content)&&Reflect.set(r,`content`,n.content);let i=Reflect.get(t,`metadata`);if(js(i)){let e=i.tanstack;if(js(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 Us(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 Ws(e){if(e.type!==`tool-result`)return e;let t=Us(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function Gs(e){return Us(X(e)?.createdAt)}function Ks(e){let t=Us(e.createdAt);return t===void 0?{}:{createdAt:t}}function qs(e){return e.name===void 0?{}:{name:e.name}}function Js(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 Ys(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Xs(e,t){if(t.length===0)return e;let n=new Set(e.parts.filter(Js).map(e=>Ys(e))),r=t.filter(e=>!n.has(Ys(e)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function Zs(e){let t=e.parts.filter(Js),n=e.metadata??{},r=X(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 Qs(e){return e.role===`system`||e.role===`activity`?[]:e.role===`assistant`?nc(e):[$s(e)]}function $s(e){let t=[];for(let n of e.parts)Ms(n)&&t.push(n);return{id:e.id,role:e.role,content:Ls(t),...qs(e),...Ks(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function ec(){return{contentParts:[],toolCalls:[]}}function tc(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 nc(e){let t=[],n=ec(),r=[],i=new Set,a={id:e.id,...qs(e),...Ks(e)},o=Zs(e),s={...a,...o!==void 0&&{metadata:o}};function c(e=!1){let i=Ls(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=ec()}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`:tc(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:wo(a,{toolResultOutcome:a.outcome}).metadata;t.push({...a.id!==void 0&&{id:a.id},...Ks(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(_s)&&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?``:Ns(a.data):a.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=a)}break;case`ui-resource`:break;case`activity`:break;case`subagent`:{let e=a.subagent.parentToolCallId===void 0?Bs(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:ws(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 rc(e,t){let n=[],r=Us(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??oc(X(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=X(e)?.toolResultOutcome,i=bs(t)?t:void 0,a=e.error===void 0&&i===void 0?`complete`:`error`;n.push({type:`tool-result`,toolCallId:e.toolCallId,content:Vs(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=Rs(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||uc(),role:e.role===`tool`?`assistant`:e.role,parts:n,...qs(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},o=X(e)?.uiResources;return Xs(a,Array.isArray(o)?o.filter(Js):[])}function ic(e){if(`parts`in e)return ac(e,{...e,id:e.id||uc()});let t=e.id||uc();switch(e.role){case`user`:return ac(e,{id:t,role:`user`,parts:sc(e.content)});case`assistant`:{let n=X(e),r=n?.toolCallMetadata,i=oc(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 ac(e,rc({role:`assistant`,content:e.content??null,...qs(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=Hs(e);let n=Us(`createdAt`in e?e.createdAt:void 0)??Gs(e);return ac(e,rc({role:`tool`,content:Ss(e.content)?e.content:cc(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 ac(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=Fs(e),r=typeof e.content==`string`?e.content:``;return ac(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n},...Is(e)}]:[]})}case`activity`:return ac(e,{id:t,role:`activity`,parts:[{type:`activity`,activityType:e.activityType,content:structuredClone(e.content)}]});default:return ac(e,{id:t,role:`assistant`,parts:[]})}}function ac(e,t){let n=t.parts.map(e=>Ws(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=Us(i.createdAt)??(a===void 0?void 0:Gs(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=X(a)?.uiResources,c=Array.isArray(s)?s.filter(Js):[];return Xs(i,c)}function oc(e){if(e==null||e.status!==`streaming`&&e.status!==`complete`&&e.status!==`error`||typeof e.raw!=`string`)return;let t={type:`structured-output`,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage}};if(e.status!==`complete`)return{...t,status:e.status};if(e.data!==void 0)return{...t,status:`complete`,data:e.data}}function sc(e){let t=cc(e);return typeof t==`string`?t?[{type:`text`,content:t}]:[]:t}function cc(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 lc(e,t){if(`parts`in e){let n=e.parts.map(e=>Ws(e));return{...e,parts:n,id:e.id||t(),createdAt:Us(e.createdAt)??new Date}}else return{...rc(e,t()),createdAt:Us(e.createdAt)??new Date}}function uc(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function dc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fc(e,t,n,r,i=!1,a){let o=dc(e)?e:{},s=dc(o.tanstack)?{...o.tanstack}:{};i&&delete s.uiResources;let c=Us(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 pc(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=t?.includeActivity??!1,o=new Set;for(let t of e)t.role===`assistant`&&t.id!==void 0&&o.add(t.id);for(let s of e){if(s.role===`activity`){if(a&&`parts`in s){let e=s.parts.find(e=>e.type===`activity`);if(e){let t={id:s.id,role:`activity`,activityType:e.activityType,content:structuredClone(e.content),...s.metadata!=null&&{metadata:s.metadata},...e.subagentRunId!==void 0&&{subagentRunId:e.subagentRunId}};n.push(t)}}continue}if(!(`parts`in s)&&s.role===`tool`&&s.toolCallId){let e=Ec(Oc(s.id,s.toolCallId,o),r),t=fc(s.metadata,s.createdAt,s.id,s.content);n.push({role:`tool`,id:e,...s.name!==void 0&&{name:s.name},toolCallId:s.toolCallId,content:typeof s.content==`string`?s.content:JSON.stringify(s.content),...s.error!==void 0&&{error:s.error},...t!==void 0&&{metadata:t}});continue}let e=`parts`in s?s:rc(s,s.id),c=e.parts;if(r.add(e.id),s.role===`system`){n.push(mc(e,`system`,{content:c.length>0?vc(c):s.content??``},c,i));continue}if(s.role===`user`){n.push(mc(e,`user`,{content:c.length>0?xc(c):s.content??``},c,i));continue}let l={thinking:[],parts:[]},u=[l];for(let e of c)e.type===`thinking`?l.parts.some(e=>e.type===`tool-call`&&_s(e))?(l={thinking:[e],parts:[]},u.push(l)):l.thinking.push(e):l.parts.push(e);u.forEach((t,a)=>{for(let i of t.thinking){let t={role:`reasoning`,id:Dc(wc(e.id,i),r),content:i.content};i.signature&&(t.encryptedValue=i.signature),n.push(t)}let o=vc(t.parts),s=Cc(t.parts),c=a===0?e:{...e,id:Dc(`${e.id}-segment-${a}`,r)};n.push(mc(c,`assistant`,{...o!==``&&{content:o},...s&&{toolCalls:s}},t.parts,i))});let d=new Set(c.flatMap(e=>e.type===`tool-result`?[e.toolCallId]:[]));for(let e of c)if(e.type===`tool-result`){let t=Ec(e.id??Tc(e.toolCallId),r),i=fc(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(d.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`}):ws(e.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:Ec(Tc(e.id),r),toolCallId:e.id,content:a,metadata:fc(void 0,void 0,void 0,i,!1,e.approval?.approved===!1?`denied`:void 0)})}for(let e of c)e.type===`subagent`&&n.push(...yc(e,t))}return n}function mc(e,t,n,r,i){let a=hc(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 hc(e,t,n){let r={...e.metadata??{}},i=X(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=Us(e.createdAt);o!==void 0&&(a.createdAt=o.toISOString());let s=gc(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 gc(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return _c(n,t)}function _c(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 vc(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 yc(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=pc(n.messages,t),a=i.some(e=>Es(e)===void 0);return(a?i:[{id:`subagent:${n.id}`,role:`assistant`},...i]).map((e,t)=>{let i=Es(e);if(i!==void 0){let t=Ds(e);return!t||t.parentSubagentRunId!==void 0?e:bc(e,i,{...t,parentSubagentRunId:n.id})}return bc(e,n.id,!a&&t===0?{...r,placeholder:!0}:r)})}function bc(e,t,n){let r=dc(e.metadata)?e.metadata:{},i=dc(r.tanstack)?r.tanstack:{};return{...e,subagentRunId:t,metadata:{...r,tanstack:{...i,subagent:n}}}}function xc(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return vc(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 Sc(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 Cc(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=Sc(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 wc(e,t){let n=`${e}-reasoning-${t.id??kc(t.content)}`;return t.type===`thinking`&&t.redacted?`${To}${n}`:n}function Tc(e){return`tool-${e}`}function Ec(e,t){return Dc(e,t)}function Dc(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 Oc(e,t,n){let r=Tc(t);return e===void 0||n.has(e)?r:e}function kc(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 Ac(e){if((e.type===Z.RUN_FINISHED||e.type===Z.RUN_ERROR)&&(Array.isArray(e.usage)||yo(e.usage))){let t=bo(e.usage,X(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===Z.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===Z.TOOL_CALL_END&&e.input===void 0){let t=X(e)?.input;t!==void 0&&(e.input=t)}return e}function jc(e){Ac(e);let t=X(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 Mc(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 Nc(e){return typeof e==`string`&&e!==``?e:void 0}function Pc(e){if(`runId`in e){let t=Nc(e.runId);if(t!==void 0)return t}return Nc(X(e)?.runId)}var Fc=class{shouldEmit(e,t){return!0}};function Ic(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}
8
- /*!
9
- * https://github.com/Starcounter-Jack/JSON-Patch
10
- * (c) 2017-2022 Joachim Wester
11
- * MIT licensed
12
- */
13
- var Lc=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Rc=Object.prototype.hasOwnProperty;function zc(e,t){return Rc.call(e,t)}function Bc(e){if(Array.isArray(e)){for(var t=Array(e.length),n=0;n<t.length;n++)t[n]=``+n;return t}if(Object.keys)return Object.keys(e);var r=[];for(var i in e)zc(e,i)&&r.push(i);return r}function Vc(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function Hc(e){for(var t=0,n=e.length,r;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function Uc(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Wc(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Gc(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(Gc(e[t]))return!0}else if(typeof e==`object`){for(var r=Bc(e),i=r.length,a=0;a<i;a++)if(Gc(e[r[a]]))return!0}}return!1}function Kc(e,t){var n=[e];for(var r in t){var i=typeof t[r]==`object`?JSON.stringify(t[r],null,2):t[r];i!==void 0&&n.push(r+`: `+i)}return n.join(`
14
- `)}var qc=function(e){Lc(t,e);function t(t,n,r,i,a){var o=this.constructor,s=e.call(this,Kc(t,{name:n,index:r,operation:i,tree:a}))||this;return s.name=n,s.index=r,s.operation=i,s.tree=a,Object.setPrototypeOf(s,o.prototype),s.message=Kc(t,{name:n,index:r,operation:i,tree:a}),s}return t}(Error),Jc=e({JsonPatchError:()=>$,_areEquals:()=>il,applyOperation:()=>$c,applyPatch:()=>el,applyReducer:()=>tl,deepClone:()=>Yc,getValueByPointer:()=>Qc,validate:()=>rl,validator:()=>nl}),$=qc,Yc=Vc,Xc={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){var r=Qc(n,this.path);r&&=Vc(r);var i=$c(n,{op:`remove`,path:this.from}).removed;return $c(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=Qc(n,this.from);return $c(n,{op:`add`,path:this.path,value:Vc(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:il(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},Zc={add:function(e,t,n){return Hc(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:Xc.move,copy:Xc.copy,test:Xc.test,_get:Xc._get};function Qc(e,t){if(t==``)return e;var n={op:`_get`,path:t};return $c(e,n),n.value}function $c(e,t,n,r,i,a){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),a===void 0&&(a=0),n&&(typeof n==`function`?n(t,0,e,t.path):nl(t,0)),t.path===``){var o={newDocument:e};if(t.op===`add`)return o.newDocument=t.value,o;if(t.op===`replace`)return o.newDocument=t.value,o.removed=e,o;if(t.op===`move`||t.op===`copy`)return o.newDocument=Qc(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=il(e,t.value),o.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o.newDocument=e,o}else if(t.op===`remove`)return o.removed=e,o.newDocument=null,o;else if(t.op===`_get`)return t.value=e,o;else if(n)throw new $("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);else return o}else{r||(e=Vc(e));var s=(t.path||``).split(`/`),c=e,l=1,u=s.length,d=void 0,f=void 0,p=void 0;for(p=typeof n==`function`?n:nl;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=Wc(f)),i&&(f==`__proto__`||f==`prototype`&&l>0&&s[l-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(c[f]===void 0?d=s.slice(0,l).join(`/`):l==u-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(c)){if(f===`-`)f=c.length;else if(n&&!Hc(f))throw new $(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else Hc(f)&&(f=~~f);if(l>=u){if(n&&t.op===`add`&&f>c.length)throw new $(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);var o=Zc[t.op].call(t,c,f,e);if(o.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}}else if(l>=u){var o=Xc[t.op].call(t,c,f,e);if(o.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}if(c=c[f],n&&l<u&&(!c||typeof c!=`object`))throw new $(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}}function el(e,t,n,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),n&&!Array.isArray(t))throw new $(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=Vc(e));for(var a=Array(t.length),o=0,s=t.length;o<s;o++)a[o]=$c(e,t[o],n,!0,i,o),e=a[o].newDocument;return a.newDocument=e,a}function tl(e,t,n){var r=$c(e,t);if(r.test===!1)throw new $(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function nl(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new $(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!Xc[e.op])throw new $("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new $("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new $('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new $("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new $("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&Gc(e.value))throw new $("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new $("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new $(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=rl([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new $(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function rl(e,t,n){try{if(!Array.isArray(e))throw new $(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)el(Vc(t),Vc(e),n||!0);else{n||=nl;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof $)return e;throw e}}function il(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!il(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!il(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}
15
- /*!
16
- * https://github.com/Starcounter-Jack/JSON-Patch
17
- * (c) 2017-2021 Joachim Wester
18
- * MIT license
19
- */
20
- var al=e({compare:()=>gl,generate:()=>ml,observe:()=>pl,unobserve:()=>fl}),ol=new WeakMap,sl=function(){function e(e){this.observers=new Map,this.obj=e}return e}(),cl=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function ll(e){return ol.get(e)}function ul(e,t){return e.observers.get(t)}function dl(e,t){e.observers.delete(t.callback)}function fl(e,t){t.unobserve()}function pl(e,t){var n=[],r,i=ll(e);if(!i)i=new sl(e),ol.set(e,i);else{var a=ul(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=Vc(e),t){r.callback=t,r.next=null;var o=function(){ml(r)},s=function(){clearTimeout(r.next),r.next=setTimeout(o)};typeof window<`u`&&(window.addEventListener(`mouseup`,s),window.addEventListener(`keyup`,s),window.addEventListener(`mousedown`,s),window.addEventListener(`keydown`,s),window.addEventListener(`change`,s))}return r.patches=n,r.object=e,r.unobserve=function(){ml(r),clearTimeout(r.next),dl(i,r),typeof window<`u`&&(window.removeEventListener(`mouseup`,s),window.removeEventListener(`keyup`,s),window.removeEventListener(`mousedown`,s),window.removeEventListener(`keydown`,s),window.removeEventListener(`change`,s))},i.observers.set(t,new cl(t,r)),r}function ml(e,t){t===void 0&&(t=!1);var n=ol.get(e.object);hl(n.value,e.object,e.patches,``,t),e.patches.length&&el(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function hl(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=Bc(t),o=Bc(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(zc(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?hl(u,d,n,r+`/`+Uc(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+Uc(l),value:Vc(u)}),n.push({op:`replace`,path:r+`/`+Uc(l),value:Vc(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+Uc(l),value:Vc(u)}),n.push({op:`remove`,path:r+`/`+Uc(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!zc(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+Uc(l),value:Vc(t[l])})}}}function gl(e,t,n){n===void 0&&(n=!1);var r=[];return hl(e,t,r,``,n),r}var _l=Object.assign({},Jc,al,{JsonPatchError:qc,deepClone:Vc,escapePathComponent:Uc,unescapePathComponent:Wc});function vl(e){return e.type===`activity`}function yl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bl(e,t){let{messageId:n,activityType:r,content:i}=t,a=t.replace??!0,o=e.findIndex(e=>e.id===n),s=o>=0?e[o]:void 0;if(s&&s.role!==`activity`)return console.warn(`ACTIVITY_SNAPSHOT: Message '${n}' is not an activity message`),e;if(s&&!a)return e;let c=Co(s?.role===`activity`?s.metadata:void 0,t.metadata),l={id:n,role:`activity`,parts:[{type:`activity`,activityType:r,content:structuredClone(i??{})}],...c==null?{}:{metadata:c},...s?.role===`activity`&&s.createdAt!=null?{createdAt:s.createdAt}:{},...s?.role===`activity`&&s.name!=null?{name:s.name}:{}};return o===-1?[...e,l]:e.map((e,t)=>t===o?l:e)}function xl(e,t){let{messageId:n,activityType:r,patch:i}=t,a=e.findIndex(e=>e.id===n);if(a===-1)return console.warn(`ACTIVITY_DELTA: No activity message '${n}'`),e;let o=e[a];if(o==null||o.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${n}' is not an activity message`),e;let s=o.parts.find(vl);if(s&&s.activityType!==r)return console.warn(`ACTIVITY_DELTA: activityType '${r}' does not match '${s.activityType}' for '${n}'`),e;let c=structuredClone(s?.content??{});try{let l=_l.applyPatch(c,i??[],!0,!1);if(!yl(l.newDocument))return console.warn(`ACTIVITY_DELTA: patched content for '${n}' is not an object`),e;let u={type:`activity`,activityType:r,content:structuredClone(l.newDocument)},d=s?o.parts.map(e=>e.type===`activity`?u:e):[u],f=Co(o.metadata,t.metadata);return e.map((e,t)=>t===a?{...e,parts:d,...f==null?{}:{metadata:f}}:e)}catch(t){let r=t instanceof Error?t.message:String(t);return console.warn(`Failed to apply activity patch for '${n}': ${r}`),e}}function Sl(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 Cl(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 wl(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 Tl(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 El(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 Dl(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 Ol(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=vn(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 kl(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 Al(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 jl(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=Eo(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 Ml=12,Nl=new Set([`RAW`,`ACTIVITY_SNAPSHOT`,`ACTIVITY_DELTA`,`REASONING_ENCRYPTED_VALUE`,`SUBAGENT_STARTED`,`SUBAGENT_FINISHED`,`SUBAGENT_ERROR`]),Pl=new Set([`RUN_STARTED`,`RUN_FINISHED`,`RUN_ERROR`,`MESSAGES_SNAPSHOT`]);function Fl(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[ns];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}function Il(e){if(e!=null)try{let t=JSON.stringify(e);return typeof t==`string`?t:void 0}catch{return}}function Ll(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}var Rl=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;openChunk=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;runToolCallIds=[];toolCallsSentToClient=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 Fc,this.events=e.events||{},this.jsonParser=e.jsonParser||kt,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??uc(),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=El(this.messages,e,t,n?`error`:void 0,n),a=ws(t),o=n?`error`:`complete`;i=wl(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=Dl(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...Qs(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)||_s(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.openChunk=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))for(let t of this.expandChunk(e))this.dispatchChunk(t)}dispatchChunk(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);break;case`ACTIVITY_SNAPSHOT`:this.handleActivitySnapshotEvent(e);break;case`ACTIVITY_DELTA`:this.handleActivityDeltaEvent(e)}}expandChunk(e){let t=this.openChunk,n=e.timestamp;switch(e.type){case`TEXT_MESSAGE_CHUNK`:{let r=this.chunkStreamId(`TEXT_MESSAGE`,e.messageId,e.type);if(r===void 0)return this.closeChunk();let i=[];return(t?.family!==`TEXT_MESSAGE`||t.id!==r)&&(i.push(...this.closeChunk(),{type:Z.TEXT_MESSAGE_START,messageId:r,role:e.role??`assistant`,...e.name===void 0?{}:{name:e.name},timestamp:n}),this.openChunk={family:`TEXT_MESSAGE`,id:r}),(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:Z.TEXT_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,metadata:e.metadata,timestamp:n}),i}case`TOOL_CALL_CHUNK`:{let r=this.chunkStreamId(`TOOL_CALL`,e.toolCallId,e.type);if(r===void 0)return this.closeChunk();let i=[];if(t?.family!==`TOOL_CALL`||t.id!==r){if(e.toolCallName===void 0)return console.warn(`[StreamProcessor] Dropped TOOL_CALL_CHUNK ${r}: the first chunk of a tool call needs a toolCallName`),this.closeChunk();i.push(...this.closeChunk(),{type:Z.TOOL_CALL_START,toolCallId:r,toolCallName:e.toolCallName,parentMessageId:e.parentMessageId,metadata:e.metadata,timestamp:n}),this.openChunk={family:`TOOL_CALL`,id:r}}return(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:Z.TOOL_CALL_ARGS,toolCallId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}case`REASONING_MESSAGE_CHUNK`:{let r=this.chunkStreamId(`REASONING_MESSAGE`,e.messageId,e.type);if(r===void 0)return this.closeChunk();let i=[];return(t?.family!==`REASONING_MESSAGE`||t.id!==r)&&(i.push(...this.closeChunk(),{type:Z.REASONING_MESSAGE_START,messageId:r,role:`reasoning`,timestamp:n}),this.openChunk={family:`REASONING_MESSAGE`,id:r}),(e.delta!==void 0||e.metadata!==void 0)&&i.push({type:Z.REASONING_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}default:{let n=t&&!Nl.has(e.type)?this.closeChunk():[];return Pl.has(e.type)&&this.closeChildChunkLanes(),[...n,e]}}}closeChildChunkLanes(){for(let e of this.childProcessors.values()){for(let t of e.closeChunk())e.dispatchChunk(t);e.closeChildChunkLanes()}}childContinuing(e){let t;if(e.type===`TEXT_MESSAGE_CHUNK`&&e.messageId===void 0)t=`TEXT_MESSAGE`;else if(e.type===`REASONING_MESSAGE_CHUNK`&&e.messageId===void 0)t=`REASONING_MESSAGE`;else if(e.type===`TOOL_CALL_CHUNK`&&e.toolCallId===void 0)t=`TOOL_CALL`;else return;if(this.openChunkCount(t)===1){for(let[e,n]of this.childProcessors)if(n.openChunkCount(t)===1)return e}}openChunkCount(e){let t=+(this.openChunk?.family===e);for(let n of this.childProcessors.values())t+=n.openChunkCount(e);return t}chunkStreamId(e,t,n){if(t!==void 0)return t;if(this.openChunk?.family===e)return this.openChunk.id;console.warn(`[StreamProcessor] Dropped ${n}: it has no id and continues nothing`)}closeChunk(){let e=this.openChunk;if(!e)return[];this.openChunk=null;let t=Date.now();switch(e.family){case`TEXT_MESSAGE`:return[{type:Z.TEXT_MESSAGE_END,messageId:e.id,timestamp:t}];case`TOOL_CALL`:return[{type:Z.TOOL_CALL_END,toolCallId:e.id,timestamp:t}];case`REASONING_MESSAGE`:return[{type:Z.REASONING_MESSAGE_END,messageId:e.id,timestamp:t}]}}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,t=!0){if(e){let t=this.getMessageState(e);if(t)return this.resumeAssistantState(e,t),{messageId:e,state:t}}let n=t?this.getActiveAssistantMessageId():null;if(n){let e=this.getMessageState(n);if(e)return this.resumeAssistantState(n,e),{messageId:n,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t?.role===`activity`)e=void 0;else 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 r=e||uc(),i={id:r,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,i];let a=this.createMessageState(r,`assistant`);return this.activeMessageIds.add(r),e||(this.pendingManualMessageId=r),this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:r,state:a}}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=X(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=Co(n.metadata,a),s=Us(X(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 t=`subagentRunId`in e&&e.subagentRunId?e.subagentRunId:`toolCallId`in e&&typeof e.toolCallId==`string`?this.childToolCalls.get(e.toolCallId):this.childContinuing(e);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`||e.type===`TOOL_CALL_CHUNK`)&&e.toolCallId!==void 0&&this.childToolCalls.set(e.toolCallId,n),this.updateChild(n,t=>t.processChunk(e)),!0)}renameMessage(e,t){this.messages=this.messages.map(n=>n.id===e?{...n,id:t}:n);let n=this.messageStates.get(e);n&&(n.id=t,this.messageStates.delete(e),this.messageStates.set(t,n)),this.activeMessageIds.delete(e),this.activeMessageIds.add(t);for(let[n,r]of this.toolCallToMessage)r===e&&this.toolCallToMessage.set(n,t);this.structuredMessageIds.delete(e)&&this.structuredMessageIds.add(t);let r=this.structuredOutputUpdateBatches.get(e);r&&(this.structuredOutputUpdateBatches.delete(e),this.structuredOutputUpdateBatches.set(t,r))}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e;if(this.messages.some(e=>e.id===t&&e.role===`activity`)){console.warn(`TEXT_MESSAGE_START: Dropped text for '${t}', the id of an activity message`);return}let r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let n=this.pendingManualMessageId;this.pendingManualMessageId=null,n!==t&&this.renameMessage(n,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.applySenderName(t,e.name),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.applySenderName(t,e.name),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.applySenderName(t,e.name),this.mergeMessageMetadata(t,e.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}applySenderName(e,t){t!==void 0&&(this.messages=this.messages.map(n=>n.id===e?{...n,name:t}:n))}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}=As(e.messages),a=this.mergeReasoningFanOut(r.map(ic)),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.mergeOmittedActivity(t,this.attachSnapshotSubagents(o,r,i,t)),this.emitMessagesChange()}mergeOmittedActivity(e,t){let n=new Set(t.map(e=>e.id)),r=e.filter(e=>e.role===`activity`&&!n.has(e.id));if(r.length===0)return t;let i=[...t];for(let t of r){let n=e.findIndex(e=>e.id===t.id);i.splice(Math.min(Math.max(n,0),i.length),0,t)}return i}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:Z.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:uc(),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`&&vs(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`?Cs(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){if(this.messages.some(t=>t.id===e.messageId&&t.role===`activity`)){console.warn(`TEXT_MESSAGE_CONTENT: Dropped text for '${e.messageId}', the id of an activity message`);return}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=Ol(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=this.pendingManualMessageId,n=e.parentMessageId;if(t&&n&&n!==t){let e=this.messages.find(e=>e.id===n),r=this.messages.find(e=>e.id===t);e?e.role===`assistant`&&r&&(this.pendingManualMessageId=null,this.messages=this.messages.filter(e=>e.id!==t).map(e=>e.id===n?{...e,parts:[...e.parts,...r.parts]}:e),this.renameMessage(t,n)):(this.pendingManualMessageId=null,this.renameMessage(t,n))}let r=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:i,state:a}=this.ensureAssistantMessage(r??void 0,e.parentMessageId===void 0);a.hasToolCallsSinceTextStart=!0;let o=e.toolCallId;if(!a.toolCalls.get(o)){let t=`awaiting-input`,n=e.toolCallName,r=e.metadata,s={id:e.toolCallId,name:n,arguments:``,state:t,parsedArguments:void 0,index:a.toolCalls.size,...r!==void 0&&{metadata:r}};a.toolCalls.set(o,s),a.toolCallOrder.push(o),this.runToolCallIds.push(o),this.toolCallToMessage.set(o,i),this.messages=Cl(this.messages,i,{id:e.toolCallId,name:n,arguments:``,state:t,...r!==void 0&&{metadata:r}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(i,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`;e.metadata!==void 0&&(i.metadata=Co(i.metadata,e.metadata)),i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Cl(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state,...i.metadata!==void 0&&{metadata:i.metadata}}),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?X(e)?.input:e.input,i=n.toolCalls.get(e.toolCallId);if(i&&i.state!==`input-complete`){let a=Il(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=Cl(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=X(e)?.toolResultOutcome,i=bs(r)?r:void 0,a=n.state===`output-error`||X(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=El(this.messages,e.toolCallId,o,a?`error`:void 0);let s=a?`error`:`complete`;this.messages=wl(this.messages,t,e.toolCallId,Ss(o)?o:cc(e.content),s,s===`error`?Cs(o):void 0,i),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.size===0&&(this.runToolCallIds=[],this.toolCallsSentToClient.clear()),this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e;if(this.finishReason=t.finishReason===void 0?X(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;(!e.outcome||e.outcome.type===`success`)&&this.handlePendingToolCalls(e.outcome?.pendingToolCallIds),this.isDone=!0,this.finalizeStream()}}handlePendingToolCalls(e){let t=e?.length?e.filter(e=>this.runToolCallIds.includes(e)):this.runToolCallIds,n=this.messages.flatMap(e=>e.parts??[]);for(let e of t){if(this.toolCallsSentToClient.has(e))continue;let t=n.find(t=>t.type===`tool-call`&&t.id===e);if(!t||_s(t)||t.output!==void 0||n.some(t=>t.type===`tool-result`&&t.toolCallId===e)||this.isToolCallPartTerminal(e)||this.isToolCallPartAwaitingUserAction(e))continue;let r=t.input??Ll(t.arguments);if(r===void 0){console.warn(`[StreamProcessor] Did not run tool call ${e}: the arguments of ${t.name} are not complete JSON`);continue}this.toolCallsSentToClient.add(e),this.events.onToolCall?.({toolCallId:e,toolName:t.name,input:r})}}handleInterrupts(e,t=!0){let n=Fl(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=Tl(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.toolCallsSentToClient.add(a),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=Pc(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=Al(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(Ic(e))}handleStepStartedEvent(e){let t=e.stepName||uc(),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}handleActivitySnapshotEvent(e){this.messages=bl(this.messages,e),this.emitMessagesChange()}handleActivityDeltaEvent(e){this.messages=xl(this.messages,e),this.emitMessagesChange()}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=jl(this.messages,r,a,o,n),this.emitMessagesChange())}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);this.mergeMessageMetadata(t,e.metadata),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=jl(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=jl(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=kl(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.toolCallsSentToClient.add(t),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=Tl(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=Cl(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=Sl(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>=Ml&&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;for(let e of this.closeChunk())this.dispatchChunk(e);this.closeChildChunkLanes();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=Al(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.openChunk=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(zl(t))}};function zl(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var Bl=/^[a-z][a-z0-9-]{0,63}$/;function Vl(e){return typeof e==`string`&&Bl.test(e)}function Hl(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`||!Vl(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Ul=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},Wl=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}},Gl=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},Kl=new WeakMap;function ql(e){return Kl.get(e)??Pc(e)}var Jl=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Yl=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Xl=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Zl=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function Ql(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 $l(e){let t=Ql(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 Zl(t.maxAttempts);await eu(t.delayMs,n)}}}function eu(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 tu(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function nu(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 ru(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var iu=`X-Run-Id`;function au(e){return e===void 0?{}:{[iu]:e}}function ou(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*su(e,t){try{let n=po(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Yl(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
21
- `);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 Jl}finally{try{e.cancel().catch(()=>{})}catch{}e.releaseLock()}}function cu(e){return jc(e)}function lu(e){let t=X(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*uu(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=mo(o);if(e===`[DONE]`){yield{chunk:wo({type:Z.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,timestamp:Date.now()},{finishReason:`stop`,...i===void 0?{}:{model:i}})};return}let s=cu(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=lu(s);c!==void 0&&(i=c);let l=a;a=void 0,yield{chunk:s,...l===void 0?{}:{id:l}}}}async function du(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Hl(t))throw new Ul(t.error.provider)}throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}function fu(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 pu(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 mu(e,t,n,r,i,a){let o=await e(ou(t,fu(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await du(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)?_o(s.messages):[],activeRun:c,interrupts:l,page:pu(s.page)}}async function hu(e,t,n,r,i){let a=await e(ou(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await du(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*gu(e,t,n){await du(e),yield*uu(su(fo(e),t),n)}async function*_u(e,t){for await(let{chunk:n}of gu(e,t))yield n}function vu(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 Yl(e)}yield*r(o,a)}}async function*yu(e,t,n){let r=$l(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 Jl||e instanceof Yl)&&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 Xl}return}}function bu(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&&Kl.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(wo({type:Z.RUN_FINISHED,threadId:nu(o??i?.threadId,`threadId`),runId:nu(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:Z.RUN_ERROR,threadId:nu(o??i?.threadId,`threadId`),runId:nu(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 xu(e,t,n,r){let i=pc(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??tu(`thread`),runId:n?.runId??tu(`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 Su(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`,...ru(s.headers),...ru(a?.headers),...au(a?.runId)},l=xu(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*yu(vu(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>gu(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=ou(i,{offset:`-1`,runId:n}),s={...ru(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*yu(vu(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>gu(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 mu(a.fetchClient??fetch,i,ru(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 hu(i.fetchClient??fetch,r,ru(i.headers),i.credentials||`same-origin`,n)}}}function Cu(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*_u(a,r):yield*wu(a,r)}}}async function*wu(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 Tu(e){return e.resumable}function Eu(e,t){let n=hs(e.descriptor);return n?{...t,metadata:ms(n)}:t}function Du(e){return`cancel`in e&&`clearResolution`in e}var Ou=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),ku=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 Au(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ju(e){return Au(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function Mu(e){return Au(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function Nu(e){return ju(e.metadata)||Mu(e.metadata)}function Pu(e){return cs(e)}function Fu(e){if(!Au(e.metadata))return!1;let t=e.metadata[ns];return!Au(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 Iu(e){if(!Au(e.metadata))return!1;let t=e.metadata[ns];return!Au(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function Lu(e){return e.metadata?.[`tanstack:interruptPayload`]}function Ru(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function zu(e){if(e.responseSchema!==void 0)try{return No(Mo(e.responseSchema))}catch{return}}function Bu(e){if(e!==void 0)try{return ds(e)}catch{return}}function Vu(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Hu(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(zo(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 Vu(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function Uu(e){for(let t of Ou)if(t===e)return!0;return!1}function Wu(e){for(let t of ku)if(t===e)return!0;return!1}function Gu(e){if(!Au(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`?Uu(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&Wu(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`):!1}function Ku(e){return Gu(e)?[e]:!Au(e)||!Array.isArray(e.errors)?[]:e.errors.every(Gu)?e.errors:[]}function qu(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 Ju(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&qu(e.interruptIds,t.interruptIds)}function Yu(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Ju(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Ju(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Xu(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):qu(e.interruptIds,n)}function Zu(e,t,n){let r=zu(e)??n?.responseSchemaHash;return Q({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 Qu(e,t){let n=Q(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([Q(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 $u=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:Q(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=Pu(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)Tu(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Eu(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`&&Ru(t.descriptor.reason)&&t.descriptor.toolCallId===e&&Mu(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=Q(wo(Eu(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`&&ju(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=Q(e),i=Pu(r),a=i===void 0&&Nu(r);if(i===void 0&&!a)return Fu(r)?{descriptor:r,binding:Zu(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&&zu(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(zu(r)??i.responseSchemaHash);if(i!==void 0&&Iu(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Zu(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=es(e.approvalSchema,e.inputSchema);if(ts(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:Q(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&&ts(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:Q(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:Q(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&&Bu(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===Bu(e.payloadSchema))){let t=Lu(r);return{descriptor:r,binding:Q(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:Q(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||zu(r)===void 0||i.responseSchemaHash===zu(r));return{descriptor:r,binding:Zu(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=Qu(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=Q(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:Q(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=Au(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`?Q(n.binding):Q({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(Vu(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(Eu(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=>Tu(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=Fo(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=Q(Eu(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=Hu(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 Vu(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=Hu(e.tool?.outputSchema,t,`invalid-tool-output`),r=e=>{if(!(`valid`in e))return e;try{return{valid:!0,payload:Q(e.payload)}}catch(e){return{code:`invalid-tool-output`,message:e instanceof Error?e.message:String(e)}}};return Vu(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!Au(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=Hu(e.tool?.inputSchema,r,`invalid-edited-args`);return Vu(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=Hu(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 Vu(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!Au(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=>Tu(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=Q({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(Du),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:Vu(n)?`async-resolver`:`inactive-transaction`,message:Vu(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>Tu(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)Tu(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=Ku(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)Tu(e)&&(e.status=`error`);return}let r=n.filter(e=>Xu(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=>Tu(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=Q(e))}else o.push(Q(e));let s=Yu(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)Tu(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(Tu).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})}},ed=new WeakMap;function td(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(Vl);if(t.length===1)return t[0];let n=ed.get(e)??[];if(n.length===1)return n[0]}function nd(e,...t){let n=e?.();if(Vl(n))return n;for(let e of t)if(Vl(e))return e}async function rd(e,t){if(!t)throw new Gl;return await e.prepare(t),e.headers(t)}var id=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})}},ad=class extends id{emitEvent(){}},od=class{events;constructor(e){this.events=new ad(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){}},sd=e=>new od(e);function cd(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function ld(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function ud(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function dd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var fd=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(cd).catch(()=>void 0);let t=cd(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;return 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=ql(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=ld(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=dd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=ud(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=ud(e);t&&this.clearedMessageIds.add(t);let n=ld(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return ql(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===`TEXT_MESSAGE_CHUNK`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`TOOL_CALL_CHUNK`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function pd(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function md(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function hd(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var gd=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=ql(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=pd(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=hd(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=md(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=md(e);t&&this.clearedMessageIds.add(t);let n=pd(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return ql(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===`TEXT_MESSAGE_CHUNK`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`TOOL_CALL_CHUNK`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}},_d=8;function vd(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function yd(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 bd(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 Cu(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function xd(e){return`connect`in e}function Sd(e){if(e.type!==`RUN_FINISHED`||e.outcome?.type===`interrupt`)return!1;let t=e;return t.finishReason===void 0?X(e)?.finishReason===`tool_calls`:t.finishReason===`tool_calls`}function Cd(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 wd(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(`
22
- `),...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=Co(i,t.content.metadata)}return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function Td(e){if(!(typeof e!=`object`||!e||Array.isArray(e))&&!(!(`approved`in e)||typeof e.approved!=`boolean`))return e.approved}function Ed(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 Dd=2e3,Od=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TEXT_MESSAGE_CHUNK`,`REASONING_MESSAGE_CONTENT`,`REASONING_MESSAGE_CHUNK`,`TOOL_CALL_START`,`TOOL_CALL_CHUNK`,`MESSAGES_SNAPSHOT`,`SUBAGENT_STARTED`]);function kd(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:Od.has(e.type)}function Ad(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...Ad(e.subagent.messages)));return t}function jd(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var Md=64;function Nd(e){if(Array.isArray(e))return e.map(Nd);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]=Nd(r));return t}var Pd=class{processor;subagentHandles=new Map;stoppedSubagentIds=new Set;connection;uniqueId;threadId;persistor;clearedStreamTracker=new gd;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;handingOverPendingToolCalls=!1;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;hydrationInFlight;storeHydrating=!1;isHydrating=!1;rejoinRunId;cachesMessages;historyPageSize;hasOlderMessages=!1;olderMessagesCursor;knownServerMessageIds=new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){yd(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 fd(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=Cd(e.queue);let n=bd(e);if(this.connectionDrainsOnSend=xd(n),this.connection=bu(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??sd)(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||(()=>{}),onHydratingChange:e.onHydratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new $u({...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 Rl({...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(this.handingOverPendingToolCalls&&t?.needsApproval===!0){console.warn(`[ChatClient] Did not run tool call ${e.toolCallId}: ${e.toolName} needs approval, and the server did not ask for it`);return}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();let s=this.persistor?.hydrateAsync(r);s&&(this.storeHydrating=!0,s.finally(()=>{this.storeHydrating=!1,this.syncIsHydrating()})),this.rejoinRunId=o,this.cachesMessages=t,this.isHydrating=this.storeHydrating||!t&&!!this.connection.hydrate}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=Ed(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){this.syncIsHydrating();return}if(this.hydrationInFlight===this.historyGeneration)return;let t=this.historyPageSize,n=t===void 0?void 0:{limit:t};(async()=>{let t,r=this.historyGeneration;this.hydrationInFlight=r,this.syncIsHydrating();let i=()=>this.hydrationInFlight===r&&r===this.historyGeneration,a;try{t=await e(this.threadId,n)}catch(e){i()&&this.failHydration(e);return}finally{a=i(),this.hydrationInFlight===r&&(this.hydrationInFlight=void 0)}if(a&&!(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=_o(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)}})().finally(()=>this.syncIsHydrating())}failHydration(e){if(this.disposed||!this.tailing||this.isLoading||this.abortController)return;let t=e instanceof Error?e:Error(String(e));t instanceof Ul&&this.byok?.request(t.provider,`missing`),t instanceof Wl&&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=ql(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),ql(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=ql(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=ql(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`&&Sd(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=ql(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!Sd(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<Md;){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=Td(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),e&&this.supersedeHydration()}supersedeHydration(){this.hydrationInFlight=void 0,this.storeHydrating=!1,this.syncIsHydrating()}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()}syncIsHydrating(){let e=this.hydrationInFlight!==void 0||this.storeHydrating;this.isHydrating!==e&&(this.isHydrating=e,this.callbacksRef.current.onHydratingChange(e))}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:Nd(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<_d)&&(n=0,!(typeof document<`u`&&document.hidden)&&await vd())}}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()},Dd);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&kd(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=jc(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=X(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`)&&(ql(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=jd(e);if(t&&e.type===Z.SUBAGENT_STARTED&&this.stoppedSubagentIds.delete(t),t&&this.stoppedSubagentIds.has(t)){this.updateRunLifecycle(e),this.resolveJoinedRun(e);return}this.handingOverPendingToolCalls=e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`;try{this.processor.processChunk(e)}finally{this.handingOverPendingToolCalls=!1}this.syncSubagentHandles(),this.updateRunLifecycle(e),this.observeInterruptState(e),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=X(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=ql(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=ql(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=lc(e,uc);if(t.role===`system`)return;if(t.role===`activity`){let e=t;this.events.messageAppended(e);let n=this.processor.getMessages();this.processor.setMessages([...n,e]),this.devtoolsBridge.emitSnapshot();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=nd(this.byokProvider,f.provider,td(this.byok));m=await rd(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?Wo(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 Ul&&this.byok?.request(n.provider,`missing`),n instanceof Wl&&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 Ul||n instanceof Wl||n instanceof Gl))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.supersedeHydration(),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&&zo(t.outputSchema)?await this.validateClientToolOutput(t,e.output):e.output;this.interruptManager.getDescriptors().some(t=>t.toolCallId===e.toolCallId)&&(n=Q(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 Go(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=Ad(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:Z.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=_o(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){let t=e.filter(e=>e.role!==`activity`);if(this.historyPageSize===void 0)return t;let n=[];for(let e of t)this.knownServerMessageIds.has(e.id)||n.push(e);if(n.length>0)return n;let r=t.findLastIndex(e=>e.role===`user`);return r===-1?[]:t.slice(r)}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=wd(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}getIsHydrating(){return this.isHydrating}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=bd({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=xd(n),this.connection=bu(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=Cd(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.onHydratingChange!==void 0&&(this.callbacksRef.current.onHydratingChange=e.onHydratingChange),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 Fd(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?Wo(e):{type:`object`}:e:{type:`object`,properties:{}}}async function Id(e,t){let n=await Go(e,t);return n.success?n.data??{}:null}function Ld(e,t,n,r){return[...Object.keys(e).length>0?[Rd(e,n)]:[],zd(),...Bd(t,r)]}function Rd(e,t){return Mc({name:d,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:
23
- `+Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(Fd(n))}`).join(`
24
- `),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 zd(){return Mc({name:ir,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 Bd(e,t){return Object.entries(e).map(([e,n])=>Mc({name:e,description:n.description,inputSchema:Fd(n.parameters),...n.metadata?{metadata:n.metadata}:{}}).client(async r=>{t?.(`tool`,`executing host tool "${e}"`,{input:r});let i=await Id(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{Mo(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 Vd(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function Hd(e,t=!1){let r={...e},i=n(r.debug),a=new Set,o={messages:[],status:`ready`,error:void 0,auth:{status:`loading`},capabilities:{attachments:!0},agentTools:[],sandboxStatus:void 0,usageLimitReached: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=st({apiUrl:r.apiUrl,scope:`tenant`,fetchAstralBeamToken:r.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),l,u,d,f=!1,p=0,h=0,g=0,_=Promise.resolve(),v=new AbortController,y,b=!1,x=[],C=zt(),w,T=!1,D=new Map,O=()=>{!w||w.accepted||(w.accepted=!0,o.thread&&s({thread:{...o.thread,hasMessages:!0}}),w.callbacks?.onAccepted?.())},k=e=>{let t=[...U.getMessages()],n=t.findLastIndex(e=>e.role===`user`);n!==-1&&(t[n]=Pt([e])[0],U.setMessagesManually(t))},A=new Set,M=new Map,ee=new Map,N=new Map,P=new Map,F=e=>{let t=M.get(e);return t?`live:${t}:${e}`:e},I=e=>{let t=new Map;for(let n of e.pending_interactions){let e=`live:${n.source_message_id}:${n.tool_call_id}`,r=nt(n.source_message_id,n.source_part_id,n.response_target_id),i=N.get(e)??N.get(r);i&&(t.set(r,i),M.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}N.clear();for(let[e,n]of t)N.set(e,n)},L=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));s({error:t,status:`error`}),(o.auth.status!==`error`||o.auth.error!==t)&&r.streamCallbacks?.onError?.(t)},R=async(e=!0)=>{let t=p,n=c.session.abortController.signal,r=await gt(c);if(n.throwIfAborted(),e&&t!==p)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:c.apiUrl,astralBeamToken:r,cache:`no-store`,signal:e?AbortSignal.any([v.signal,n]):n,fetchClient:(e,t)=>kn({...c,input:e,init:t})}},te=0,ne,z=async()=>{let e=++te,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 R();if(e!==te||t!==p)return;let a=await m(n?{agentId:n}:{},r);if(e!==te||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)}},B=new Map,V=new Set,H=new Set,ie=()=>{for(let e of B.values())e();B.clear(),V.clear(),H.clear()},ae=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 Id(a?.parameters,e.props??{});if(n!==p||o.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==r.widgets?.[e.widget])return ae(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};B.get(t)?.(),B.delete(t);let l,u=c({widget:e.widget,props:s,toolCallId:t,release:()=>{B.get(t)===l&&B.delete(t)}});return u&&(l=u,B.set(t,u)),V.add(t),{widget:e.widget,rendered:!0}},se=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(nt(e.id,n.id),r.widgetRenderId),r.applicationPartId&&t.set(nt(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(nt(n.id,e.id))??(a.applicationPartId?t.get(nt(n.id,a.applicationPartId,a.responseTargetId)):void 0)??(s&&M.get(s)===n.id&&V.has(s)?s:e.id);if(a.widgetRenderId=c,V.has(c)||H.has(c))continue;H.add(c);let l=p,{widgets:u,onRenderWidget:d}=r;ae(e.input,c).catch(e=>i?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{l===p&&(H.delete(c),(u!==r.widgets||d!==r.onRenderWidget)&&se(o.messages))})}},ce=()=>Ld(r.widgets??{},r.tools??{},ae,i).map(e=>{if(!e.execute)return e;let t=e.execute;return{...e,execute:async(e,n)=>{let r=n?.toolCallId;if(!r||!A.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=N,a=F(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}}}}),le=()=>{let e=ce(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return Vd(o.agentTools,t)||s({agentTools:t}),e},ue=()=>r.debug?{debug:!0}:{},de=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=S(),c,l=i.messages.at(-1)?.role===`user`?w: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:C}};else{ge();let e=await an(n.id,t,void 0,M);if(r!==p)throw new DOMException(`Conversation changed`,`AbortError`);s({thread:er(e.thread,e.messages.length>0)}),I(e);let o=e.pendingInteractions.filter(e=>N.has(F(e.toolCallId))),l=o.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??o[0],u=e.pendingInteractions.flatMap(e=>{let t=N.get(F(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=je(n.id),c={client_id:C,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:u}}A.clear(),s({activeToolCallIds:[]});let d=new Headers(e.headers);l&&d.set(`Idempotency-Key`,l.key);let f=await Ie(a,{...t,...e,headers:d,body:JSON.stringify(c)}).catch(e=>{let t=Ue(e)?e.body?.usage_limit:void 0;throw t&&s({usageLimitReached:{name:t.name,resetsAt:t.resets_at}}),l&&!u&&Ue(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`);if(s({thread:{...o.thread,version:e.thread_version},...e.usage_limit?{usageLimitReached:{name:e.usage_limit.name,resetsAt:e.usage_limit.resets_at}}:{}}),l){let i=await an(n.id,t,void 0,M);if(r!==p)throw new DOMException(`Conversation changed`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&k(a),O()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return f},fe=Su(()=>j(S(),c.apiUrl),async()=>{let e=d,t=await gt(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)=>kn({...c,input:e,init:t})};return de(n??{},r)}}}),pe=fe.connect;fe.connect=async function*(...e){try{for await(let t of pe(...e)){if(t.type===Z.TOOL_CALL_START&&t.parentMessageId&&M.set(t.toolCallId,t.parentMessageId),t.type!==Z.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=ee.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&&Ue(e.cause)?e.cause:e}};let me=(e=o.thread?.id)=>{let t=p,n={...fe};delete n.hydrate,e&&(n.hydrate=(n,r)=>{let i=++g;r?.before||s({threadLoading:!0});let c=(async()=>{let n=await an(e,await R(),r?.before,M);for(;r?.before&&n.messages.every(e=>e.role===`tool`)&&n.page_after;){let t=await an(e,await R(),n.page_after,M);n={...t,messages:[...t.messages,...n.messages]}}if(t!==p||i!==g)throw new DOMException(`Conversation changed`,`AbortError`);I(n),x=r?.before?[...n.messages,...x]:n.messages;let c=new Set(n.messages.map(e=>e.id)),l=Pt(x,n.pendingInteractions,M).filter(e=>c.has(e.id));n.thread.role===`viewer`&&ie();let u=o.thread?.agentId!==n.thread.agent_id;return s({thread:er(n.thread,n.messages.length>0),messagesCursor:n.page_after??void 0,pendingInteractions:n.pendingInteractions,threadLoadFailed:!1}),se(l),!r?.before&&u&&z(),!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){_=c;let e=e=>queueMicrotask(()=>{t===p&&i===g&&s({threadLoading:!1,threadLoadFailed:e})});c.then(()=>e(!1),()=>e(!0))}return c});let a=new Pd({connection:n,threadId:e??C,persistence:!0,history:{pageSize:100},queue:`drop`,tools:le(),forwardedProps:ue(),onMessagesChange:e=>{if(!(U!==a||t!==p)){se(e);for(let t of e){if(t.role!==`user`)continue;let e=o.messages.find(e=>e.id===t.id);e?.parts.some(e=>`savedAttachmentId`in e)&&(t.parts=e.parts)}s({messages:e,sandbox:Kt(e),error:a.getError()})}},onStatusChange:e=>{U===a&&t===p&&s({status:e,error:a.getError(),...e===`submitted`?{usageLimitReached:void 0}:{}})},onInterruptStateChange:e=>{U===a&&i?.(`tool`,`interrupt state changed`,e)},onCustomEvent:(e,t)=>{if(U!==a)return;if(e===`astralbeam_thread`){let e=t;if(o.thread?.id===e.threadId){if(e.acceptedMessage&&w&&!w.accepted&&k(e.acceptedMessage),e.acceptedMessageId&&O(),e.saved)for(let t of e.executableToolCallIds??[])A.has(t)||N.delete(F(t)),A.add(t);s({thread:{...o.thread,version:e.version},activeToolCallIds:[...A],...e.acceptedMessageId?{unsentMessage:void 0}:{}})}return}let n=t;if(e===`astralbeam.usage_limit.reached`&&typeof n?.name==`string`&&typeof n.resetsAt==`string`){s({usageLimitReached:{name:n.name,resetsAt:n.resetsAt}});return}let r=t?.state;if(e===`astralbeam.sandbox.status`&&(r===`starting`||r===`ready`||r===`error`)){i?.(`sandbox`,`sandbox ${r}`),s({sandboxStatus:r});return}i?.(`stream`,`custom event "${e}"`,t)},onChunk:e=>{U===a&&r.streamCallbacks?.onChunk?.(e)},onResponse:e=>{U===a&&r.streamCallbacks?.onResponse?.(e)},onFinish:e=>{U===a&&r.streamCallbacks?.onFinish?.(e)},onError:e=>{U===a&&(o.auth.status!==`error`||o.auth.error!==e)&&r.streamCallbacks?.onError?.(e)}});return a},U=me(),he=(e=o.thread?.id)=>{U.stop();let t=U;t.detach(),A.clear(),M.clear(),s({activeToolCallIds:[]}),U=me(e),f&&U.attach(),t.dispose()},ge=()=>{ee.clear(),U.setMessagesManually(o.messages.map(e=>{let t=new Map,n=e.parts.map(n=>{if(n.type!==`tool-call`||re(n).providerExecuted)return n;let r=n,i=r.upstreamToolCallId??n.id;if(M.get(i)===e.id&&!oe(n))return n;let a=nt(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`&&M.get(i)===e.id?{widgetRenderId:r.widgetRenderId??n.id}:{}}});return t.size&&ee.set(e.id,t),{...e,parts:n}}))},ve=e=>{let t=o.thread?.id;t&&(w&&!w.accepted?D.set(t,w):D.delete(t),P.set(t,N)),p++,g++,T=!1,v.abort(),v=new AbortController,w=void 0,N=P.get(e??``)??new Map,ee.clear(),x=[],ie(),s({thread:void 0,messages:[],unsentMessage:void 0,error:void 0,status:`ready`,sandbox:{files:[],commands:[]},sandboxStatus:void 0,usageLimitReached:void 0,pendingInteractions:[],threadLoadFailed:!1,messagesCursor:void 0,olderMessagesLoading:!1}),he(e)},ye=async(e,t=!1)=>{t||h++,ve(e);let n=p;s({threadLoading:!0});try{if(w=D.get(e),s({unsentMessage:w?.content}),f||U.attach(),await _,n!==p)return;y&&Vn(y,e)}catch(e){if(n===p){if(t&&(r.threadId===void 0||r.threadId===`auto`)&&Ue(e)&&e.status===404){be();return}s({threadLoadFailed:!0}),L(e)}}finally{n===p&&s({threadLoading:!1})}},be=()=>{h++,ve(),s({threadLoading:!1}),f&&z(),y?Vn(y,null):b=!0},W=(e=!1)=>{let t=r.threadId;if(t===void 0||t===`auto`){if(!y)return;t=Vn(y)}t&&t!==`new`?ye(t,e):e||be()},xe=async()=>{if(o.thread)return;let e=p,t=await R(),n=await dt(r.agentId?{agent_id:r.agentId}:{},t);if(e!==p)throw new DOMException(`Conversation changed`,`AbortError`);let i=er(n,!1);s({thread:i}),he(),await _,z(),y&&Vn(y,i.id)},Se=async(e=!1,t=!0)=>{if(!o.thread?.id)return;let n=p,r=o.error;s({threadLoading:!0,olderMessagesLoading:!1});try{if(t?he():(U.detach(),U.attach()),await _,n!==p)return;e&&r&&s({error:r,status:`error`})}catch(e){if(n===p){if(Ue(e)&&e.status===404){be();return}L(e)}}finally{n===p&&s({threadLoading:!1})}},Ce=async()=>{if(!U.getHasOlderMessages()||o.olderMessagesLoading||o.threadLoading||T)return;let e=p;s({olderMessagesLoading:!0});try{await U.loadOlderMessages()}catch(t){e===p&&L(t)}finally{e===p&&s({olderMessagesLoading:!1})}},we=async e=>{let t=o.thread;if(!t||t.role!==`manager`)return!1;let n=p;try{let r=await _e(t.id,{title:e,expected_version:t.version},await R());if(n!==p)return!1;let i=er(r,t.hasMessages);return s({thread:i,error:U.getError(),status:U.getStatus()}),!0}catch(e){return n===p&&L(e),!1}},G=async(e=o.thread)=>{if(!e||e.role!==`manager`)return!1;let t=p;try{return await Yn(e.id,{expected_version:String(e.version)},await R()),t===p&&o.thread?.id===e.id&&be(),!0}catch(e){return t===p&&L(e),!1}},Te=async e=>{let t=p;if(T||U.getIsLoading()){L(Error(`Wait for this client's current request to finish before responding.`));return}let n=Wt(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`||!A.has(e.toolCallId)&&!a&&!i&&!N.has(F(e.toolCallId))){L(Error(`This tool call belongs to another session and cannot be executed here.`));return}if(i&&!N.has(F(e.toolCallId)))N.set(F(e.toolCallId),{outcome:`unknown`,output:null});else if(!N.has(F(e.toolCallId))&&`tool`in e){let t=e.output;N.set(F(e.toolCallId),{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}if(ge(),r){if(he(),await _,t!==p)return;s({threadLoading:!1}),await U.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(N.get(F(e.toolCallId)))})}else`tool`in e&&await U.addToolResult(e);t===p&&await Se(U.getError()!==void 0,!1)},De=e=>Te({toolCallId:e}),Oe=async(e,t)=>{let n=h;try{await gt(c)}catch(t){if(n!==h)return;s({unsentMessage:e}),L(t);return}if(n!==h)return;if(T||o.threadLoading||o.status===`streaming`){L(Error(`Wait for this client's current request to finish before sending.`));return}if(o.threadLoadFailed){L(Error(`Reopen this conversation or start a new one before sending.`));return}let r=w!==void 0&&JSON.stringify(w.content)===JSON.stringify(e),i=w?.tools!==void 0&&!w.accepted?w:void 0,a=i!==void 0&&r;if(o.thread?.agentId===null&&!a){L(Error(`This conversation’s agent is unavailable. Start a new conversation to continue.`));return}if(o.thread?.role===`viewer`&&!a){L(Error(`You have read-only access to this conversation.`));return}if(i&&!r){s({unsentMessage:i.content}),L(Error(`The previous message’s acceptance is unconfirmed. Retry that message before sending different text, or start a new conversation.`));return}let l=p;g++,s({olderMessagesLoading:!1}),T=!0,(!w||w.accepted||!r)&&(w={content:e,accepted:!1,key:zt(),callbacks:t},U.stop(),A.clear(),ge(),M.clear(),s({activeToolCallIds:[]})),w.callbacks??=t,s({unsentMessage:e,error:void 0,status:`submitted`});try{if(await xe(),l!==p||(w.callbacks?.onThreadReady?.(o.thread.id),l!==p)||(ge(),await U.sendMessage(e),l!==p))return;let t=U.getError()!==void 0;w?.accepted&&(w=void 0,s({unsentMessage:void 0})),await Se(t,!1)}catch(e){l===p&&L(e)}finally{l===p&&(T=!1)}},ke=()=>{let e=Wt(c),t=o.auth;if(e.status===`ready`){let t=Tn(e.currentUser);d!==void 0&&d!==t&&(h++,D.clear(),P.clear(),N.clear(),w=void 0),d=t;let n=`astralbeam:thread:${r.apiUrl??`https://astralbeam.ai/api`}:${t}`;y!==n&&(ve(),y=n,b?(Vn(n,null),b=!1):W(!0)),ne!==t&&(ne=t,z())}s({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&r.streamCallbacks?.onError?.(e.error)},Ae=()=>{f||(f=!0,U.attach(),v.signal.aborted&&(v=new AbortController),u=In(c,ke),ke(),l=un(c))};return t||Ae(),{start:Ae,getState:()=>o,subscribe:e=>(a.add(e),()=>a.delete(e)),updateOptions:e=>{let t=r.agentId,a=r.apiUrl,l=r.threadId,{widgets:u,onRenderWidget:d}=r;r={...r,...e},i=n(r.debug),xt(c,{apiUrl:r.apiUrl,fetchAstralBeamToken:r.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),c.debug=i,U.updateOptions({tools:le(),forwardedProps:ue()}),r.apiUrl===a?r.threadId!==l&&W():(h++,D.clear(),P.clear(),N.clear(),w=void 0,ve(),y=void 0,s({threadLoading:!1}),ke()),(u!==r.widgets||d!==r.onRenderWidget)&&se(o.messages),f&&(r.agentId!==t||r.apiUrl!==a)&&z()},sendMessage:Oe,addToolResult:Te,stop:()=>U.stop(),retryAuthentication:()=>{gt({...c,force:!0}).catch(()=>void 0)},reload:async()=>{let e=p;if(await Se(),e!==p||o.error)return;let t=new Set;for(;e===p;){let e=o.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&N.has(F(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await Te({toolCallId:e.toolCallId}),o.error))return}},searchThreads:async(e=``,t,n)=>{let r=await R(),i=await Zt({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>er(e)),page_after:i.page_after}},openThread:ye,renameThread:we,deleteThread:G,refreshThread:Se,loadOlderMessages:Ce,uploadAttachment:async({data:e,filename:t,mimeType:n})=>{let i=o.thread?o.thread.agentId:r.agentId,[a,s]=await Promise.all([e,R(!1)]);return E({...i?{agentId:i}:{},type:n.startsWith(`image/`)?`image`:`document`,source:{type:`data`,value:a,mimeType:n},metadata:{filename:t}},s)},getFile:async e=>{let t=o.thread;if(!t)throw Error(`Open a conversation before downloading files.`);return(await Gn({threadId:t.id,fileId:e},await R())).blob()},getAttachment:async(e,t)=>{let n=o.thread;if(!n)throw Error(`Open a conversation before downloading attachments.`);return(await Ee(n.id,e,t,await R())).blob()},abandonToolCall:De,reset:()=>{i?.(`status`,`conversation reset`),be()},dispose:()=>{U.detach(),ie(),U.stop(),v.abort(),p++,y=void 0,te++,ne=void 0,l?.(),u?.(),hn(c),f=!1,queueMicrotask(()=>{f||U.dispose()}),a.clear()}}}const Ud=[`header`,`headerActions`,`empty`,`composerActions`];function Wd(e){return`${D}${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}function Gd(e,t,n){let[r,i]=(0,q.useState)(new Set),a=(0,q.useRef)(new Map);return(0,q.useEffect)(()=>{for(let r of Ud){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=Wd(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,q.useEffect)(()=>()=>{for(let e of a.current.values())e.cleanup?.(),e.container.remove();a.current.clear()},[]),r}function Kd(e,t,n){let[r,i]=(0,q.useState)(new Map),a=(0,q.useRef)(new Map),o=(0,q.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(fe(n)));return t},[]),s=(0,q.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,q.useRef)(!0);(0,q.useEffect)(()=>(c.current=!0,()=>{c.current=!1,s(()=>!0)}),[s]);let l=(0,q.useRef)(e),u=(0,q.useRef)(n);(0,q.useEffect)(()=>{l.current=e,u.current=n});let d=(0,q.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=Jt(l.current,e);if(!f)throw Error(`Unknown widget "${e}"`);if(!c.current)throw Error(`The chat is no longer mounted`);let p=fe(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,q.useState)(e);return f!==e&&(p(e),i(t=>{let n=new Map([...t].filter(([,t])=>Jt(e,t)));return n.size===t.size?t:n})),(0,q.useEffect)(()=>{let t=o(t=>!Jt(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 qd={},Jd=[],Yd={text:``,attachments:Jd,settledAttachments:Jd,savedAttachments:Jd,attachmentsLoaded:!1,storageError:!1};function Xd({options:e,host:t,controller:r}){let i=e.widgets??qd,a=(0,q.useMemo)(()=>n(e.debug),[e.debug]),{activeSlots:o,renderWidget:s}=Kd(i,t,a),c=Gd(e.slots,t,a),l=(0,q.useMemo)(()=>oo(a),[a]),u=(0,q.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,q.useState)(()=>Hd(u,!0));(0,q.useEffect)(()=>{d.updateOptions(u)},[d,u]),(0,q.useEffect)(()=>(d.start(),()=>d.dispose()),[d]);let f=(0,q.useSyncExternalStore)(d.subscribe,d.getState,d.getState),{messages:p,status:m,auth:h,capabilities:g,sandbox:_,sandboxStatus:v,agentTools:y}=f,b=f.usageLimitReached,x=b?Error(U(b)):f.error,S=(0,q.useMemo)(()=>new Set(y.map(e=>e.name)),[y]),C=(0,q.useMemo)(()=>{let e=new Set(f.activeToolCallIds);if(h.status===`ready`&&f.thread?.role!==`viewer`)for(let t of f.pendingInteractions)t.targetTenantUserId===h.currentUser.user.id&&p.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,h,p]),w=(0,q.useMemo)(()=>{let e={};for(let t of y)t.title!==void 0&&(e[t.name]=t.title);return e},[y]);(0,q.useEffect)(()=>{a?.(`mount`,`tool set declared to the agent`,{tools:[...S],widgets:Object.keys(i)})},[a,S,i]);let T=e.apiUrl??`https://astralbeam.ai/api`,E=_.files.length>0||_.commands.length>0;(0,q.useEffect)(()=>{a?.(`status`,`chat status is "${m}"`)},[a,m]);let[D,O]=(0,q.useState)({apiUrl:T,identity:``,threads:new Map}),k=h.status===`ready`?Tn(h.currentUser):D.identity;(D.apiUrl!==T||D.identity!==k)&&O({apiUrl:T,identity:k,threads:new Map});let A=f.thread?.id??``,j=D.threads.get(A)??{...Yd,text:io(T,k,A)},M=j.text,ee=(0,q.useRef)(new Set);(0,q.useEffect)(()=>{if(h.status!==`ready`||f.threadLoading||j.attachmentsLoaded)return;let e=!1;return ao({apiUrl:T,identity:k,threadId:A}).then(e=>({attachments:e,storageError:!1}),()=>({attachments:Jd,storageError:!0})).then(({attachments:t,storageError:n})=>{e||O(e=>{if(e.apiUrl!==T||e.identity!==k)return e;let r=e.threads.get(A)??{...Yd,text:io(T,k,A)};return r.attachmentsLoaded?e:{...e,threads:new Map(e.threads).set(A,{...r,attachments:t,settledAttachments:t,savedAttachments:t,attachmentsLoaded:!0,storageError:n})}})}),()=>{e=!0}},[T,k,A,h.status,f.threadLoading,j.attachmentsLoaded]),(0,q.useEffect)(()=>{for(let[e,t]of D.threads){if(!t.attachmentsLoaded||t.attachments===t.settledAttachments)continue;let n=JSON.stringify([D.apiUrl,D.identity,e]);if(ee.current.has(n))continue;ee.current.add(n);let r=r=>{ee.current.delete(n),O(n=>{if(n.apiUrl!==D.apiUrl||n.identity!==D.identity)return n;let i=n.threads.get(e);return i?{...n,threads:new Map(n.threads).set(e,{...i,settledAttachments:t.attachments,savedAttachments:r?i.savedAttachments:t.attachments,storageError:r})}:n})};ao({apiUrl:D.apiUrl,identity:D.identity,threadId:e,update:e=>{let n=new Map(e.map(e=>[e.id,e]));for(let e of t.savedAttachments)t.attachments.some(t=>t.id===e.id)||n.delete(e.id);for(let e of t.attachments)e.status===`ready`&&!t.savedAttachments.some(t=>t.id===e.id&&t.status===`ready`)&&n.set(e.id,e);return[...n.values()]}}).then(()=>r(!1),()=>r(!0))}},[D]);let N=e=>O(t=>t.apiUrl!==T||t.identity!==k?t:{...t,threads:new Map(t.threads).set(A,e(t.threads.get(A)??j))}),P=e=>{io(T,k,A,e),N(t=>({...t,text:e}))},F=e=>N(t=>({...t,attachments:e(t.attachments)})),I=(0,q.useMemo)(()=>Me(g.attachments&&j.attachmentsLoaded?e.attachments:!1),[e.attachments,g.attachments,j.attachmentsLoaded]),R=[];for(let e of I.enabled?j.attachments:Jd){if(e.status===`error`){R.push(e);continue}let[t]=pt({files:[{name:e.name,size:e.size,type:e.mimeType}],existing:R,limits:I,createId:()=>e.id});R.push(t.draft.status===`error`?t.draft:e)}let te=m===`submitted`||m===`streaming`,ne=te&&!we(p),z=h.status===`loading`,B=h.status===`error`?h.error:void 0,V=z||B!==void 0||te||!j.attachmentsLoaded||j.attachments!==j.settledAttachments||f.threadLoading||f.threadLoadFailed||f.thread?.role===`viewer`||f.thread?.agentId===null||L(p.map(e=>({...e,parts:e.parts.filter(e=>e.type!==`tool-call`||C.has(e.id))})),S),re=e=>{let t=pt({files:e,existing:R,limits:I,createId:zt});F(e=>[...e,...t.map(({draft:e})=>e)]);let n=(e,t)=>O(n=>{if(n.apiUrl!==T||n.identity!==k)return n;for(let[r,i]of n.threads)if(i.attachments.some(t=>t.id===e))return{...n,threads:new Map(n.threads).set(r,{...i,attachments:i.attachments.map(n=>n.id===e?{...n,...t}:n)})};return 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});let t=Kn(r);d.uploadAttachment({data:t,filename:e.name,mimeType:e.mimeType}).then(async r=>{n(e.id,{status:`ready`,fileId:r.fileId,mimeType:r.mimeType,size:r.byteSize,...e.kind===`image`?{data:await t}:{}})}).catch(t=>{a?.(`error`,`attachment "${e.name}" could not be uploaded`,t),n(e.id,{status:`error`,error:`The file could not be uploaded`})})}},H=e=>{a?.(`attachment`,`attachment removed`,{id:e}),F(t=>t.filter(t=>t.id!==e))},ie=()=>{let e=M.trim(),t=Oe(R),n=R.some(e=>e.status===`reading`);if(V||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=M,i=new Set(R.filter(e=>e.status===`ready`).map(e=>e.id)),o=A;d.sendMessage(t.length===0?e:{content:[...t,...e.length>0?[{type:`text`,content:e}]:[]]},{onThreadReady:e=>{if(o!==``)return;o=e;let t=io(T,k,``);t&&io(T,k,e,t),io(T,k,``,``),ao({apiUrl:T,identity:k,threadId:``,moveTo:e}).catch(e=>a?.(`error`,`Draft files could not be moved`,e)),O(t=>{if(t.apiUrl!==T||t.identity!==k)return t;let n=t.threads.get(``);if(!n)return t;let r=t.threads.get(e),i=new Map(t.threads);return i.set(e,{...n,text:n.text||r?.text||``,attachments:[...new Map([...r?.attachments??[],...n.attachments].map(e=>[e.id,e])).values()],settledAttachments:Jd,savedAttachments:[...r?.savedAttachments??[],...n.savedAttachments]}),i.delete(``),{...t,threads:i}})},onAccepted:()=>{io(T,k,o)===r&&io(T,k,o,``),ao({apiUrl:T,identity:k,threadId:o,update:e=>e.filter(e=>!i.has(e.id))}).catch(e=>a?.(`error`,`Accepted draft files could not be cleared`,e)),O(e=>{if(e.apiUrl!==T||e.identity!==k)return e;let t=e.threads.get(o);return t?{...e,threads:new Map(e.threads).set(o,{...t,text:t.text===r?``:t.text,attachments:t.attachments.filter(e=>!i.has(e.id))})}:e})}})},ae=(e,t)=>{a?.(`questionnaire`,`answers submitted`,{toolCallId:e,answers:t}),d.addToolResult({toolCallId:e,tool:ir,output:{answers:t}})},oe=()=>{d.reset(),io(T,k,``,``),ao({apiUrl:T,identity:k,threadId:``,update:()=>[]}).catch(e=>a?.(`error`,`Draft files could not be cleared`,e)),O(e=>{let t=new Map(e.threads);return t.set(``,{...Yd,attachmentsLoaded:!0}),{...e,threads:t}})},se=()=>requestAnimationFrame(()=>t.shadowRoot?.querySelector(`textarea`)?.focus()),ce=e=>{io(T,k,e,``),ao({apiUrl:T,identity:k,threadId:e,update:()=>[]}).catch(e=>a?.(`error`,`Deleted conversation's draft files could not be cleared`,e)),O(t=>{if(t.apiUrl!==T||t.identity!==k)return t;let n=new Map(t.threads);return n.delete(e),{...t,threads:n}})};return(0,q.useImperativeHandle)(r,()=>({reset:oe,stop:d.stop})),(0,J.jsxs)(Ir,{className:`h-full w-full gap-0 rounded-none bg-background pt-0 text-foreground ring-0`,children:[e.showHeader!==!1&&(0,J.jsxs)(Lr,{className:`flex h-14 shrink-0 items-center gap-1 border-b py-0 [.border-b]:pb-0`,children:[(0,J.jsx)(`div`,{className:`min-w-0 flex-1`,children:c.has(`header`)?(0,J.jsx)(`slot`,{name:Wd(`header`)}):(0,J.jsx)(Rr,{className:`truncate`,children:e.title??`AstralBeam`})}),(0,J.jsx)(Ha,{chat:d,state:f,onDelete:ce,onSelect:se},`${T}:${k}`),(0,J.jsx)(We,{variant:`ghost`,size:`icon-sm`,"aria-label":`New chat`,title:`New chat`,disabled:!f.thread&&p.length===0,onClick:()=>{oe(),se()},children:(0,J.jsx)(Ar,{})}),c.has(`headerActions`)&&(0,J.jsx)(`slot`,{name:Wd(`headerActions`)})]}),e.showConversationTitle===!0&&f.thread?.title&&(0,J.jsx)(xa,{chat:d,state:f,thread:f.thread,onDelete:ce},`${T}:${k}:${f.thread.id}`),(0,J.jsx)(zr,{className:`min-h-0 flex-1 overflow-hidden p-0`,children:(0,J.jsx)(Se,{readOnly:f.thread?.role===`viewer`,messages:p,getAttachment:d.getAttachment,currentTenantUserId:h.status===`ready`?h.currentUser.user.id:void 0,hasOlder:f.messagesCursor!==void 0,loadingHistory:f.threadLoading,loadingOlder:f.olderMessagesLoading,onLoadOlder:d.loadOlderMessages,getFile:d.getFile,emptySlot:c.has(`empty`)?Wd(`empty`):void 0,emptyHeadline:e.emptyHeadline,emptyDescription:e.emptyDescription,widgets:i,toolTitles:w,activeSlots:o,interactiveToolIds:C,isBusy:V,awaitingReply:ne,onQuestionnaireAnswers:ae})}),(0,J.jsxs)(Br,{className:`flex-col gap-2 rounded-none border-t-0 bg-transparent pt-1`,children:[f.threadLoading?(0,J.jsx)(`span`,{role:`status`,className:`w-full text-xs text-muted-foreground`,children:`Loading conversation…`}):f.thread?.role===`viewer`?(0,J.jsx)(`span`,{className:`w-full text-xs text-muted-foreground`,children:`You can read this conversation.`}):f.thread?.writerActive&&!te?(0,J.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=>!C.has(e.toolCallId)&&(f.thread?.role===`manager`||h.status===`ready`&&e.targetTenantUserId===h.currentUser.user.id)).map(e=>(0,J.jsxs)(`div`,{className:`flex w-full items-center gap-2 text-xs`,children:[(0,J.jsx)(`span`,{className:`min-w-0 flex-1`,children:`An earlier action has no confirmed result.`}),(0,J.jsx)(We,{variant:`outline`,size:`sm`,onClick:()=>void d.abandonToolCall(e.toolCallId),children:`Continue with unknown outcome`})]},e.responseTargetId)),v!==void 0&&(0,J.jsx)(to,{status:v}),e.sandboxPanel===!0&&E&&(0,J.jsx)($a,{activity:_}),I.enabled&&j.storageError&&(0,J.jsx)(`p`,{role:`status`,className:`w-full text-muted-foreground text-xs`,children:`Files cannot be recovered after reload because browser storage is unavailable.`}),(0,J.jsx)(Ur,{title:e.title??`AstralBeam`,actionsSlot:c.has(`composerActions`)?Wd(`composerActions`):void 0,draft:M,onDraftChange:P,onSend:ie,onStop:()=>{a?.(`status`,`generation stopped by user`),d.stop()},onRetry:b?void 0:f.unsentMessage===void 0?p.length>0?()=>void d.reload():void 0:()=>void d.sendMessage(f.unsentMessage),retryLabel:f.unsentMessage===void 0?`Refresh`:`Retry`,showError:m===`error`||b!==void 0,error:x,streamBusy:te,isBusy:V,authPending:z,authError:B,onAuthRetry:d.retryAuthentication,attachments:R,attachmentLimits:I,onAddFiles:re,onRemoveAttachment:H})]})]})}function Zd(e,t){let n=e.host.parentElement??document.body,r=C(),i=document.createElement(`style`);e.append(i);let a=()=>{i.textContent=le(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 Qd(e,t,r){let i=document.createElement(`style`);i.textContent=Nn+(r.customCss??``),e.append(i);let a=r,o=Zd(e,()=>n(a.debug)),s=(0,Fr.createRoot)(t),c=(0,q.createRef)(),l=t=>{a.customCss!==t.customCss&&(i.textContent=Nn+(t.customCss??``)),a=t,s.render((0,J.jsx)(Xd,{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{Qd as renderChat};