@astralbeam/sdk 0.30.6 → 0.30.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +0,0 @@
1
- import{$ as e,$t as t,A as n,An as r,At as i,B as a,Bt as o,C as s,Cn as c,Ct as l,Dn as u,E as d,En as f,Et as p,F as m,Fn as h,Ft as g,G as _,Gt as v,H as y,Ht as b,I as x,In as S,It as C,J as w,Jt as T,K as E,Kt as D,L as O,Lt as k,M as A,Mn as j,Mt as M,N,Nn as P,Nt as F,O as ee,On as I,Ot as L,P as R,Pn as z,Q as te,Qt as ne,R as B,Rt as re,S as ie,Sn as V,St as ae,T as oe,Tn as H,Tt as U,U as se,Ut as ce,V as le,Vt as ue,W as de,Wt as fe,X as pe,Xt as me,Y as he,Z as ge,Zt as _e,_ as ve,_n as ye,_t as W,a as be,an as xe,at as Se,b as Ce,bt as we,c as Te,cn as Ee,ct as De,dn as Oe,dt as ke,et as Ae,fn as je,ft as Me,g as Ne,gn as Pe,gt as Fe,ht as Ie,i as Le,in as Re,it as ze,j as Be,jn as Ve,jt as He,k as Ue,kn as We,kt as Ge,l as Ke,ln as qe,lt as Je,m as Ye,mt as Xe,n as Ze,nn as Qe,nt as $e,o as et,on as tt,ot as G,p as nt,pn as rt,pt as it,q as at,qt as ot,r as st,rn as ct,rt as lt,s as ut,sn as dt,st as ft,t as pt,tt as mt,u as ht,un as gt,ut as _t,v as vt,vt as yt,w as bt,wn as xt,wt as St,x as Ct,xt as wt,y as Tt,yt as Et,z as Dt,zn as Ot,zt as kt}from"./combobox-DXIOk4hb.js";import"./constants-C-Yp0Vhg.js";import{t as At}from"./debug-DLDY8CZb.js";import{$ as jt,$n as Mt,A as Nt,Ar as Pt,At as Ft,B as It,C as Lt,Ct as Rt,D as zt,Dn as Bt,Dr as Vt,E as Ht,Er as Ut,Et as Wt,F as Gt,G as Kt,Gn as qt,Gt as Jt,Ht as Yt,I as Xt,It as Zt,Jn as Qt,Jt as $t,L as en,Ln as tn,Lt as nn,Mt as rn,N as an,O as on,On as sn,Or as cn,P as ln,Pn as un,Qt as dn,R as fn,T as pn,Tn as mn,Tr as hn,Tt as gn,U as _n,V as vn,Vt as yn,W as bn,Xn as xn,Yn as Sn,Zn as Cn,Zt as wn,_ as Tn,_r as En,_t as Dn,a as On,ar as kn,at as An,b as jn,br as Mn,cn as Nn,cr as Pn,ct as Fn,d as In,dn as Ln,dr as Rn,er as zn,et as Bn,f as Vn,fr as Hn,h as Un,ht as Wn,i as Gn,ir as Kn,j as qn,jn as Jn,jr as Yn,jt as Xn,k as Zn,l as Qn,ln as $n,lr as er,lt as tr,m as nr,mt as rr,n as K,nt as ir,o as ar,or,ot as sr,p as cr,pr as lr,q as ur,qn as dr,qt as fr,r as pr,rr as mr,rt as hr,s as gr,sr as _r,t as vr,u as yr,un as br,ur as xr,ut as Sr,vn as Cr,vt as wr,w as Tr,x as Er,xr as Dr,xt as Or,y as kr,z as Ar}from"./styles.generated-BrC_vo9p.js";import{a as jr,d as Mr,f as Nr,g as Pr,h as Fr,i as Ir,l as Lr,m as Rr,n as zr,o as Br,p as Vr,r as Hr,s as Ur,t as Wr,u as Gr}from"./item-D7P71wsB.js";function Kr(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qr(e){typeof globalThis.reportError==`function`?globalThis.reportError(e):console.error(e)}function Jr(e){if(Array.isArray(e))return Object.freeze(e.map(Jr));if(!Kr(e))return e;let t={};for(let n of Object.keys(e))t[n]=Jr(e[n]);return Object.freeze(t)}function Yr(e,t=/* @__PURE__ */ new WeakMap){let n=e,r={...n};if(Kr(n.source)&&(r.source=Object.freeze({...n.source})),n.type===`tool-call`&&Kr(n.approval)&&(r.approval=Object.freeze({...n.approval})),n.type===`tool-result`&&Array.isArray(n.content)&&(r.content=Object.freeze(n.content.map(e=>typeof e==`object`&&e?Yr(e,t):e))),`input`in n&&(r.input=Jr(n.input)),`output`in n&&(r.output=Jr(n.output)),n.type===`subagent`&&Kr(n.subagent)){let e=n.subagent;r.subagent=Object.freeze(Array.isArray(e.messages)?{...e,messages:Zr(t,e.messages)}:{...e})}return Object.freeze(r)}function Xr(e,t,n){let r=e.get(t);return r||(r=n(t),e.set(t,r)),r}function Zr(e,t){return Object.freeze(t.map(t=>Xr(e,t,()=>Object.freeze({...t,parts:Object.freeze(t.parts.map(t=>Xr(e,t,()=>Yr(t,e))))}))))}function Qr(e,t){e.set(e=>{let n=!1,r={...e};for(let i of Object.keys(t))Object.is(e[i],t[i])||(r[i]=t[i],n=!0);return n?Object.freeze(r):e})}var $r=8;function ei(e,t){let{unsubscribe:n}=e.subscribe(()=>{let n,r=0;do{n=e.get();try{t()}catch(e){qr(e)}r++}while(e.get()!==n&&r<$r)});return n}var ti=class extends Error{missingFeature;constructor(e){super(ni(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function ni(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 ri(e){if(!e.body)throw new ti(`Response.body`);if(typeof e.body.getReader!=`function`)throw new ti(`Response.body.getReader`);return e.body.getReader()}function ii(){if(typeof globalThis.TextDecoder!=`function`)throw new ti(`TextDecoder`);return new globalThis.TextDecoder}function ai(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function oi(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 si(e){let t=oi(e.createdAt),n=e.parts.map(e=>{if(e.type!==`tool-result`)return e;let t=oi(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 ci(e){return e.map(si)}function li(e){return Object.keys(e).length>0?e:void 0}function ui(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function di(e,t){return ui(e)?e:fi(Array.isArray(e)?e:void 0,t)}function fi(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=li({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...n?.cacheWriteInputTokens===void 0?{}:{cacheWriteTokens:n.cacheWriteInputTokens},...r}),s=li({...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 pi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mi(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return pi(e.tanstack)&&pi(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function q(e){if(e==null)return;let t=`metadata`in e?e.metadata:void 0,n=(typeof t==`object`&&t&&!Array.isArray(t)?t:e).tanstack;if(typeof n==`object`&&n&&!Array.isArray(n))return n}function hi(e,t){let n=e.metadata,r=q(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}let J=/* @__PURE__ */ 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}({});function gi(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>gi(e,t[n]));if(e===null||t===null||typeof e!=`object`||typeof t!=`object`||Array.isArray(e)||Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&gi(Reflect.get(e,n),Reflect.get(t,n)))}function _i(e,t){let n=0,r=()=>{for(;e[n]===` `||e[n]===` `||e[n]===`\r`||e[n]===`
2
- `;)n++},i=()=>{let t=n++;for(;n<e.length;)if(e[n]===`\\`)n+=2;else if(e[n++]===`"`)break;return e.slice(t,n)},a=t=>{r();let o=n;if(e[n]===`{`){n++,r();let s=/* @__PURE__ */ new Map;for(;e[n]!==`}`;){let o=i(),c=JSON.parse(o);r(),n++;let l=typeof t==`object`&&t&&typeof c==`string`?Reflect.get(t,c):void 0,u=a(l);if(typeof c==`string`&&s.set(c,{...u,keyToken:o}),r(),e[n]!==`,`)break;n++,r()}return n++,{start:o,end:n,value:t,properties:s}}if(e[n]===`[`){n++,r();let i=[];for(;e[n]!==`]`&&(i.push(a(Array.isArray(t)?t[i.length]:void 0)),r(),e[n]===`,`);)n++;return n++,{start:o,end:n,value:t,items:i}}if(e[n]===`"`)i();else for(;n<e.length&&!/[\s,}\]]/.test(e[n]??``);)n++;return{start:o,end:n,value:t}};return a(t)}function vi(e,t,n,r){if(n&&gi(n.value,e))return t.slice(n.start,n.end);if(typeof e==`number`)return Object.is(e,-0)?`-0`:e===1/0?`1e999`:e===-1/0?`-1e999`:JSON.stringify(e);if(typeof e!=`object`||!e)return JSON.stringify(e);if(r.has(e))throw TypeError(`Cannot serialize circular tool input`);r.add(e);try{if(Array.isArray(e))return`[`+Array.from(e,(e,i)=>vi(e,t,n?.items?.[i],r)??`null`).join(`,`)+`]`;let i=[];for(let a of Object.keys(e)){let o=vi(Reflect.get(e,a),t,n?.properties?.get(a),r);o!==void 0&&i.push((n?.properties?.get(a)?.keyToken??JSON.stringify(a))+`:`+o)}return`{`+i.join(`,`)+`}`}finally{r.delete(e)}}function yi(e,t){if(t===void 0)return e??``;if(e===void 0)return vi(t,``,void 0,/* @__PURE__ */ new Set)??``;let n;try{n=JSON.parse(e)}catch{return e.trim()===``?vi(t,``,void 0,/* @__PURE__ */ new Set)??e:e}return gi(n,t)?e:vi(t,e,_i(e,n),/* @__PURE__ */ new Set)??e}function bi(e){if(e.trim()===``)return{};try{return JSON.parse(e)??void 0}catch{return}}function xi(e,t){let n=q(t),r=t.args??n?.args,i=typeof r==`string`?r:void 0,a=t.input??n?.input,o=typeof a==`object`&&a?a:void 0,s=i??e;if(i===void 0&&o!==void 0)try{JSON.parse(s)}catch{s=void 0}let c;try{c=yi(s,o)}catch{c=s??e}return{args:c,input:bi(c)}}var Si=`redacted_thinking-`;function Ci(e){return typeof e==`string`&&e.startsWith(`redacted_thinking-`)}var wi=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 Ti(e,t){return e>>>t|e<<32-t}function Ei(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=/* @__PURE__ */ 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=Ti(t,7)^Ti(t,18)^t>>>3,i=Ti(n,17)^Ti(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=Ti(a,6)^Ti(a,11)^Ti(a,25),s=a&g^~a&_,c=v+o+s+(wi[e]??0)+(h[e]??0)>>>0,l=(Ti(t,2)^Ti(t,13)^Ti(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 Di(e){return`sha256:${Ei(e)}`}function Oi(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(Oi(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Oi(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function ki(e){return Oi(e,/* @__PURE__ */ new WeakSet)}function Ai(e,t=Di){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function ji(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(ji),Object.freeze(e))}function Y(e){let t=JSON.parse(ki(e));return ji(t),t}function Mi(e){let t=Y([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=ki(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:Ai(n)})}function Ni(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function Pi(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function Fi(e){if(!Pi(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 Ii(e){return Pi(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 Li(e){return Object.keys(e).length>0?e:void 0}function Ri(e){if(Array.isArray(e)){let t=e.map(e=>zi(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=zi(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function zi(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=zi(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=Ri(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=Ri(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:Li(r)}}function Bi(e,t=`input`){if(Fi(e)){let n=Ni(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(Ii(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`?Ni(e):e}function Vi(e,t={}){if(!e)return;let{forStructuredOutput:n=!1,io:r}=t;if(!n&&!Fi(e)&&!Ii(e))return e;let i=Bi(e,r);return!i||typeof i!=`object`||!n?i:zi(i,i.required||[]).schema}async function Hi(e,t){if(!Ii(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 Ui=/* @__PURE__ */ new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function Wi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Gi(e){return Wi(e)&&Object.keys(e).some(e=>Ui.has(e))}function Ki(e){return Ii(e)||Fi(e)||Gi(e)}function qi(e){if(!Wi(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>Ki(e[t]))}function Ji(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Yi(e){if(Ii(e)){let t=Fi(e)?Ji(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Gi(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Xi(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 Zi(e,t){let n=t===void 0?null:Yi(t),r=null,i=null;if(e!==void 0){if(Ii(e)||Gi(e))r=Yi(e),i=r;else if(qi(e))r=e.approve===void 0?null:Yi(e.approve),i=e.reject===void 0?null:Yi(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Xi({approved:!0,payload:r,inputSchema:n}),Xi({approved:!1,payload:i,inputSchema:null})]},o=ki(a),s=ki({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:Ai(o),approvalSchemaHash:Ai(s)}}function Qi(e){return Ai(e===void 0?`undefined`:ki(Yi(e).jsonSchema??{standardValidator:`unserialized`}))}var $i=`tanstack:interruptBinding`,ea=$i;function ta(e){return e&&typeof e==`object`?e:null}function na(e,t){return typeof e[t]==`string`?e[t]:void 0}function ra(e){let t=e.v;return t===void 0||t===1}function ia(e){let t=ta(e.metadata),n=t?ta(t[ea]):null;if(!n||na(n,`interruptId`)!==e.id||!ra(n))return;let r=na(n,`kind`),i=na(n,`interruptId`),a=na(n,`responseSchemaHash`),o=na(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=na(n,`definitionId`),t=na(n,`key`),s=n.batchIndex,c=na(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=na(n,`toolName`),c=na(n,`toolCallId`);if(s&&c){if(r===`client-tool-execution`){let e=na(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=na(n,`inputSchemaHash`),t=na(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 aa(e){let t=ia(e);if(!t)return;let n=ta(e.metadata),r=n?ta(n[ea]):null;if(!r)return;let i=na(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var oa=`tanstack:interruptPayload`;function sa(e,t){if(!Fi(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:ki(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function ca(e){return Ai(sa(e,`Interrupt schema`).canonicalJson)}var la=`tanstack:interruptContinuation`;function ua(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function da(e){return{[la]:e}}function fa(e){let t=ia(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=ua(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[oa]}:{}}}function pa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ma=`subagentInput`;function ha(e){if(pa(e)&&pa(e.tanstack))return e.tanstack[ma]}function ga(e){if(!pa(e)||`parts`in e)return;let t=e.subagentRunId;return typeof t==`string`&&t!==``?t:void 0}function _a(e){if(!pa(e)||!pa(e.metadata))return;let t=e.metadata.tanstack;if(!pa(t)||!pa(t.subagent))return;let{name:n,status:r,error:i,interruptIds:a}=t.subagent;if(typeof n!=`string`||!va(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},...pa(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},...pa(l)&&{metadata:l},...u===!0&&{placeholder:!0}}}function va(e){return e===`running`||e===`finished`||e===`error`||e===`suspended`}function ya(e){if(!pa(e))return e;let{subagentRunId:t,...n}=e,r=pa(n.metadata)?n.metadata:void 0,i=pa(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 ba(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=ga(n);e!==void 0&&!t.has(e)&&t.set(e,_a(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=/* @__PURE__ */ new Map;for(let t of e){let e=ga(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=_a(t);s&&(o.info=s),s?.placeholder||o.messages.push(ya(t))}return{top:r,groups:[...i.values()]}}function xa(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Sa(e){return xa(e)!==null}function Ca(e,t){return e?.startsWith(`${t}-segment-`)===!0}var wa=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`video`,`document`]);function Ta(e){return e===`cancelled`||e===`denied`}function Ea(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!wa.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 Da(e){return Array.isArray(e)&&e.length>0&&e.every(Ea)}function Oa(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}function ka(e){return typeof e==`string`||Da(e)?e:JSON.stringify(e)}function Aa(e){let t=[],n=0,r=!0;for(let i of e){let e=t.at(-1);if(i.type===`thinking`)e!==void 0&&e.type!==`thinking`&&(r=!1),t.push({type:`thinking`,index:n++});else if(i.type===`text`){if(i.text===``)continue;if(e?.type===`text`){e.length+=i.text.length;continue}e?.type===`tool-call`&&(r=!1),t.push({type:`text`,length:i.text.length})}else t.push({type:`tool-call`,id:i.id})}return r?void 0:t}function ja(e){let t=e.blockOrder;if(!Array.isArray(t)||t.length===0)return;let n=e.content??``;if(typeof n!=`string`)return;let r=e.thinking??[],i=e.toolCalls??[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=[],c=0;for(let e of t){if(typeof e!=`object`||!e)return;if(e.type===`thinking`){let t=Number.isInteger(e.index)?r[e.index]:void 0;if(t===void 0||a.has(e.index))return;a.add(e.index),s.push({type:`thinking`,thinking:t})}else if(e.type===`text`){let t=c+e.length;if(!Number.isInteger(e.length)||e.length<=0||t>n.length)return;s.push({type:`text`,text:n.slice(c,t)}),c=t}else if(e.type===`tool-call`){let t=i.find(t=>t.id===e.id);if(t===void 0||o.has(e.id))return;o.add(e.id),s.push({type:`tool-call`,toolCall:t})}else return}if(c===n.length&&a.size===r.length&&o.size===i.length)return s}function Ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Na(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function Pa(e){try{return JSON.stringify(e)??``}catch{return``}}function Fa(e){return typeof e==`string`&&e!==``?e:void 0}function Ia(e){if(`encryptedValue`in e){let t=Fa(e.encryptedValue);if(t!==void 0)return t}return Fa(q(e)?.signature)}function La(e){return`id`in e&&Ci(e.id)?{redacted:!0}:{}}function Ra(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function za(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function Ba(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=Va(n);e!==``&&t.push(e)}return t.join(`
3
-
4
- `)}function Va(e){let t=[];for(let n of e.subagent.messages){if(!(`parts`in n))continue;let e=Ba(n.parts).trim();e!==``&&t.push(e)}return t.length===0?``:`${e.subagent.name}:\n${t.join(`
5
-
6
- `)}`}function Ha(e){return Array.isArray(e)?e:za(e)}function Ua(e){if(!(`role`in e)||e.role!==`tool`)return e;let t=e,n=q(t)?.toolResult;if(!Ma(n)||`content`in n&&!Da(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=Wa(n.createdAt);e&&Reflect.set(r,`createdAt`,e)}Da(n.content)&&Reflect.set(r,`content`,n.content);let i=Reflect.get(t,`metadata`);if(Ma(i)){let e=i.tanstack;if(Ma(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 Wa(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 Ga(e){if(e.type!==`tool-result`)return e;let t=Wa(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function Ka(e){return Wa(q(e)?.createdAt)}function qa(e){let t=Wa(e.createdAt);return t===void 0?{}:{createdAt:t}}function Ja(e){return e.name===void 0?{}:{name:e.name}}function Ya(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 Xa(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Za(e,t){if(t.length===0)return e;let n=new Set(e.parts.filter(Ya).map(e=>Xa(e))),r=t.filter(e=>!n.has(Xa(e)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function Qa(e){let t=e.parts.filter(Ya),n=e.metadata??{},r={...q(e)};r.run&&(r.run={...r.run},delete r.run.startedAt,delete r.run.finishedAt),delete r.createdAt,delete r.continues,delete r.structuredOutput,delete r.toolCallMetadata,delete r.toolResult,delete r.toolResultOutcome,delete r.uiResources,t.length>0&&(r.uiResources=t);let i={...n};return Object.keys(r).length>0?i.tanstack=r:delete i.tanstack,Object.keys(i).length>0?i:void 0}function $a(e){return e.role===`system`||e.role===`activity`?[]:e.role===`assistant`?ro(e):[eo(e)]}function eo(e){let t=[];for(let n of e.parts)Na(n)&&t.push(n);return{id:e.id,role:e.role,content:Ra(t),...Ja(e),...qa(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function to(){return{contentParts:[],toolCalls:[],order:[]}}function no(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 ro(e){let t=[],n=to(),r=[],i=/* @__PURE__ */ new Set,a={id:e.id,...Ja(e),...qa(e)},o=Qa(e),s={...a,...o!==void 0&&{metadata:o}};function c(e=!1){let i=Ra(n.contentParts),a=i!==null,o=n.toolCalls.length>0,c=r.length>0,l=Array.isArray(i)?void 0:Aa(n.order);(e||a||o||c)&&(t.push({...s,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...c&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput},...l&&{blockOrder:l}}),r=[]),n=to()}for(let a of e.parts)switch(a.type){case`text`:n.contentParts.push(a),n.order.push({type:`text`,text:a.content});break;case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(a);break;case`tool-call`:no(a)&&(n.toolCalls.push({id:a.id,type:`function`,function:{name:a.name,arguments:a.arguments},...a.metadata!==void 0&&{metadata:a.metadata}}),n.order.push({type:`tool-call`,id:a.id}));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:hi(a,{toolResultOutcome:a.outcome}).metadata;t.push({...a.id!==void 0&&{id:a.id},...qa(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(Sa)&&c(),r.push({content:a.content,...a.signature&&{signature:a.signature},...a.redacted&&{redacted:!0}}),n.order.push({type:`thinking`}));break;case`structured-output`:if(a.status===`complete`){let e=a.raw===``?a.data===void 0?``:Pa(a.data):a.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.order.push({type:`text`,text:e}),n.structuredOutput=a)}break;case`ui-resource`:break;case`activity`:break;case`subagent`:{let e=a.subagent.parentToolCallId===void 0?Va(a):``;if(e!==``){let t=`${n.contentParts.length>0?`
7
-
8
- `:``}${e}`;n.contentParts.push({type:`text`,content:t}),n.order.push({type:`text`,text:t})}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:ka(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 io(e){return{type:`thinking`,content:e.content,...e.signature&&{signature:e.signature},...e.redacted&&{redacted:!0}}}function ao(e){let t;try{t=JSON.parse(e.function.arguments)}catch{t=void 0}return{type:`tool-call`,id:e.id,name:e.function.name,arguments:e.function.arguments,state:`input-complete`,...t!==void 0&&{input:t},...e.metadata!==void 0&&{metadata:e.metadata}}}function oo(e,t){let n=[],r=Wa(e.createdAt);if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)(t.content||t.signature)&&n.push(io(t));let i=e.structuredOutput??lo(q(e)?.structuredOutput);if(e.role===`assistant`&&i){if(typeof e.content==`string`&&e.content&&e.content!==i.raw){let t=i.raw,r=t!==``&&e.content.endsWith(t)?e.content.slice(0,-t.length):e.content;r&&n.push({type:`text`,content:r})}n.push(i)}else if(e.role===`tool`&&e.toolCallId){let t=q(e)?.toolResultOutcome,i=Ta(t)?t:void 0,a=e.error===void 0&&i===void 0?`complete`:`error`;n.push({type:`tool-result`,toolCallId:e.toolCallId,content:Ha(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=za(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls)n.push(ao(t));let a=e.role===`assistant`&&i===void 0?ja(e):void 0;a&&n.splice(0,n.length,...a.flatMap(e=>e.type===`text`?[{type:`text`,content:e.text}]:e.type===`tool-call`?[ao(e.toolCall)]:e.thinking.content||e.thinking.signature?[io(e.thinking)]:[]));let o={id:t||mo(),role:e.role===`tool`?`assistant`:e.role,parts:n,...Ja(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},s=q(e)?.uiResources;return Za(o,Array.isArray(s)?s.filter(Ya):[])}function so(e){if(`parts`in e)return co(e,{...e,id:e.id||mo()});let t=e.id||mo();switch(e.role){case`user`:return co(e,{id:t,role:`user`,parts:uo(e.content)});case`assistant`:{let n=q(e),r=n?.toolCallMetadata,i=lo(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 co(e,oo({role:`assistant`,content:e.content??null,...Ja(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=Ua(e);let n=Wa(`createdAt`in e?e.createdAt:void 0)??Ka(e);return co(e,oo({role:`tool`,content:Da(e.content)?e.content:fo(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 co(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=Ia(e),r=typeof e.content==`string`?e.content:``;return co(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n},...La(e)}]:[]})}case`activity`:return co(e,{id:t,role:`activity`,parts:[{type:`activity`,activityType:e.activityType,content:structuredClone(e.content)}]});default:return co(e,{id:t,role:`assistant`,parts:[]})}}function co(e,t){let n=t.parts.map(e=>Ga(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=Wa(i.createdAt)??(a===void 0?void 0:Ka(a));if(o!==void 0&&!Object.is(o,i.createdAt))i={...i,createdAt:o};else if(o===void 0&&i.createdAt!==void 0){let{createdAt:e,...t}=i;i=t}let s=q(a)?.uiResources,c=Array.isArray(s)?s.filter(Ya):[];return Za(i,c)}function lo(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 uo(e){let t=fo(e);return typeof t==`string`?t?[{type:`text`,content:t}]:[]:t}function fo(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 po(e,t){if(`parts`in e){let n=e.parts.map(e=>Ga(e));return{...e,parts:n,id:e.id||t(),createdAt:Wa(e.createdAt)??/* @__PURE__ */ new Date}}return{...oo(e,t()),createdAt:Wa(e.createdAt)??/* @__PURE__ */ new Date}}function mo(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function ho(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function go(e,t,n,r,i=!1,a){let o=ho(e)?e:{},s=ho(o.tanstack)?{...o.tanstack}:{};i&&delete s.uiResources;let c=Wa(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 _o(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=/* @__PURE__ */ 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=Ao(Mo(s.id,s.toolCallId,o),r),t=go(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:oo(s,s.id),c=e.parts;if(r.add(e.id),s.role===`system`){n.push(vo(e,`system`,{content:c.length>0?So(c):s.content??``},c,i));continue}if(s.role===`user`){n.push(vo(e,`user`,{content:c.length>0?To(c):s.content??``},c,i));continue}let l=e=>({thinking:[],parts:[],continues:e,closed:!1}),u=l(!1),d=[u];for(let e of c){u.closed&&(e.type===`thinking`||e.type===`text`||e.type===`tool-call`)&&(u=l(!1),d.push(u));let t=u.parts.some(e=>e.type===`tool-call`);e.type===`thinking`?(u.parts.some(e=>e.type===`tool-call`&&Sa(e))?(u=l(!1),d.push(u)):(t||u.parts.some(e=>e.type===`text`))&&(u=l(!0),d.push(u)),u.thinking.push(e)):e.type===`text`&&t?(u=l(!0),d.push(u),u.parts.push(e)):(u.parts.push(e),e.type===`tool-result`&&(u.closed=!0))}let f=new Set(c.flatMap(e=>e.type===`tool-result`?[e.toolCallId]:[])),p=e=>{for(let t of e)if(t.type===`tool-result`){let e=Ao(t.id??ko(t.toolCallId),r),i=go(t.metadata,t.createdAt,t.id,t.content,!0,t.outcome);n.push({role:`tool`,id:e,toolCallId:t.toolCallId,...t.name!==void 0&&{name:t.name},content:typeof t.content==`string`?t.content:JSON.stringify(t.content),...t.error!==void 0&&{error:t.error},...i!==void 0&&{metadata:i}})}else if(t.type===`tool-call`){let e=t.approval?.approved;if(f.has(t.id)||t.output===void 0&&(t.state!==`approval-responded`||e===void 0))continue;let i=t.output===void 0?JSON.stringify({approved:e,...e&&{pendingExecution:!0},message:e?`User approved this action`:`User denied this action`}):ka(t.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:Ao(ko(t.id),r),toolCallId:t.id,content:a,metadata:go(void 0,void 0,void 0,i,!1,t.approval?.approved===!1?`denied`:void 0)})}},m=e.id,h=[];d.forEach((t,a)=>{for(let i of t.thinking){let t={role:`reasoning`,id:jo(Oo(e.id,i),r),content:i.content};i.signature&&(t.encryptedValue=i.signature),n.push(t)}let o=So(t.parts),s=Do(t.parts),c=vo(a===0?e:{...e,id:jo(`${e.id}-segment-${a}`,r)},`assistant`,{...o!==``&&{content:o},...s&&{toolCalls:s}},t.parts,i);if(t.continues){let e=c.metadata??{};c.metadata={...e,tanstack:{...ho(e.tanstack)?e.tanstack:{},continues:m}}}n.push(c),m=c.id,h.push(...t.parts),(t.closed||a===d.length-1)&&(p(h),h=[])});for(let e of c)e.type===`subagent`&&n.push(...Co(e,t))}return n}function vo(e,t,n,r,i){let a=yo(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 yo(e,t,n){let r={...e.metadata??{}},i={...q(e)};i.run&&(i.run={...i.run},delete i.run.startedAt,delete i.run.finishedAt),delete i.createdAt,delete i.continues,delete i.structuredOutput,delete i.toolCallMetadata,delete i.toolResult,delete i.toolResultOutcome,delete i.uiResources;let a=Wa(e.createdAt);a!==void 0&&(i.createdAt=a.toISOString());let o=bo(t,n);o&&(i.structuredOutput=o);let s={};for(let e of t)e.type===`tool-call`&&e.metadata!==void 0&&(s[e.id]=e.metadata);Object.keys(s).length>0&&(i.toolCallMetadata=s);let c=t.filter(e=>e.type===`ui-resource`);return c.length>0&&(i.uiResources=c),Object.keys(i).length>0?r.tanstack=i:delete r.tanstack,Object.keys(r).length>0?r:void 0}function bo(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return xo(n,t)}function xo(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 So(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 Co(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=_o(n.messages,t),a=i.some(e=>ga(e)===void 0);return(a?i:[{id:`subagent:${n.id}`,role:`assistant`},...i]).map((e,t)=>{let i=ga(e);if(i!==void 0){let t=_a(e);return!t||t.parentSubagentRunId!==void 0?e:wo(e,i,{...t,parentSubagentRunId:n.id})}return wo(e,n.id,!a&&t===0?{...r,placeholder:!0}:r)})}function wo(e,t,n){let r=ho(e.metadata)?e.metadata:{},i=ho(r.tanstack)?r.tanstack:{};return{...e,subagentRunId:t,metadata:{...r,tanstack:{...i,subagent:n}}}}function To(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return So(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 Eo(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 Do(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=Eo(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 Oo(e,t){let n=`${e}-reasoning-${t.id??No(t.content)}`;return t.type===`thinking`&&t.redacted?`${Si}${n}`:n}function ko(e){return`tool-${e}`}function Ao(e,t){return jo(e,t)}function jo(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 Mo(e,t,n){let r=ko(t);return e===void 0||n.has(e)?r:e}function No(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 Po(e){if((e.type===J.RUN_FINISHED||e.type===J.RUN_ERROR)&&(Array.isArray(e.usage)||ui(e.usage))){let t=di(e.usage,q(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===J.TOOL_CALL_END&&e.input===void 0){let t=q(e),n=t?.input??(typeof t?.args==`string`?bi(t.args):void 0);n!==void 0&&(e.input=n)}return e}function Fo(e){Po(e);let t=q(e),n=e;if(t==null)return n;for(let[e,r]of Object.entries(t))e!==`usage`&&e!==`interruptErrors`&&n[e]===void 0&&r!==void 0&&(n[e]=r);return t.interruptErrors!==void 0&&(n[`tanstack:interruptErrors`]=t.interruptErrors),n}function Io(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 Lo(e){return typeof e==`string`&&e!==``?e:void 0}function Ro(e){if(`runId`in e){let t=Lo(e.runId);if(t!==void 0)return t}return Lo(q(e)?.runId)}var zo=class{shouldEmit(e,t){return!0}};function Bo(e){let t=Error(e.message||`An error occurred`);return e.code!==void 0&&Object.assign(t,{code:e.code}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}
9
- /*!
10
- * https://github.com/Starcounter-Jack/JSON-Patch
11
- * (c) 2017-2022 Joachim Wester
12
- * MIT licensed
13
- */
14
- var Vo=(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)}})(),Ho=Object.prototype.hasOwnProperty;function Uo(e,t){return Ho.call(e,t)}function Wo(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)Uo(e,i)&&r.push(i);return r}function Go(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function Ko(e){for(var t=0,n=e.length,r;t<n;)if(r=e.charCodeAt(t),r>=48&&r<=57)t++;else return!1;return!0}function qo(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Jo(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Yo(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;t<n;t++)if(Yo(e[t]))return!0}else if(typeof e==`object`){for(var r=Wo(e),i=r.length,a=0;a<i;a++)if(Yo(e[r[a]]))return!0}}return!1}function Xo(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(`
15
- `)}var Zo=function(e){Vo(t,e);function t(t,n,r,i,a){var o=this.constructor,s=e.call(this,Xo(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=Xo(t,{name:n,index:r,operation:i,tree:a}),s}return t}(Error),Qo=/* @__PURE__ */ Pt({JsonPatchError:()=>X,_areEquals:()=>cs,applyOperation:()=>rs,applyPatch:()=>is,applyReducer:()=>as,deepClone:()=>$o,getValueByPointer:()=>ns,validate:()=>ss,validator:()=>os}),X=Zo,$o=Go,es={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=ns(n,this.path);r&&=Go(r);var i=rs(n,{op:`remove`,path:this.from}).removed;return rs(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=ns(n,this.from);return rs(n,{op:`add`,path:this.path,value:Go(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:cs(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},ts={add:function(e,t,n){return Ko(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:es.move,copy:es.copy,test:es.test,_get:es._get};function ns(e,t){if(t==``)return e;var n={op:`_get`,path:t};return rs(e,n),n.value}function rs(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):os(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=ns(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=cs(e,t.value),o.test===!1)throw new X(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o.newDocument=e,o}if(t.op===`remove`)return o.removed=e,o.newDocument=null,o;if(t.op===`_get`)return t.value=e,o;if(n)throw new X("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);return o}r||(e=Go(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:os;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=Jo(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&&!Ko(f))throw new X(`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 Ko(f)&&(f=~~f);if(l>=u){if(n&&t.op===`add`&&f>c.length)throw new X(`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=ts[t.op].call(t,c,f,e);if(o.test===!1)throw new X(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}}else if(l>=u){var o=es[t.op].call(t,c,f,e);if(o.test===!1)throw new X(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}if(c=c[f],n&&l<u&&(!c||typeof c!=`object`))throw new X(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}function is(e,t,n,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),n&&!Array.isArray(t))throw new X(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=Go(e));for(var a=Array(t.length),o=0,s=t.length;o<s;o++)a[o]=rs(e,t[o],n,!0,i,o),e=a[o].newDocument;return a.newDocument=e,a}function as(e,t,n){var r=rs(e,t);if(r.test===!1)throw new X(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function os(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new X(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!es[e.op])throw new X("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 X("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new X('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 X("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 X("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`)&&Yo(e.value))throw new X("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 X("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 X(`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=ss([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new X(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function ss(e,t,n){try{if(!Array.isArray(e))throw new X(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)is(Go(t),Go(e),n||!0);else{n||=os;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof X)return e;throw e}}function cs(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(!cs(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],!cs(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}
16
- /*!
17
- * https://github.com/Starcounter-Jack/JSON-Patch
18
- * (c) 2017-2021 Joachim Wester
19
- * MIT license
20
- */
21
- var ls=/* @__PURE__ */ Pt({compare:()=>bs,generate:()=>vs,observe:()=>_s,unobserve:()=>gs}),us=/* @__PURE__ */ new WeakMap,ds=function(){function e(e){this.observers=/* @__PURE__ */ new Map,this.obj=e}return e}(),fs=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function ps(e){return us.get(e)}function ms(e,t){return e.observers.get(t)}function hs(e,t){e.observers.delete(t.callback)}function gs(e,t){t.unobserve()}function _s(e,t){var n=[],r,i=ps(e);if(!i)i=new ds(e),us.set(e,i);else{var a=ms(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=Go(e),t){r.callback=t,r.next=null;var o=function(){vs(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(){vs(r),clearTimeout(r.next),hs(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 fs(t,r)),r}function vs(e,t){t===void 0&&(t=!1);var n=us.get(e.object);ys(n.value,e.object,e.patches,``,t),e.patches.length&&is(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function ys(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=Wo(t),o=Wo(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(Uo(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)?ys(u,d,n,r+`/`+qo(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+qo(l),value:Go(u)}),n.push({op:`replace`,path:r+`/`+qo(l),value:Go(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+qo(l),value:Go(u)}),n.push({op:`remove`,path:r+`/`+qo(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];!Uo(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+qo(l),value:Go(t[l])})}}}function bs(e,t,n){n===void 0&&(n=!1);var r=[];return ys(e,t,r,``,n),r}var xs=Object.assign({},Qo,ls,{JsonPatchError:Zo,deepClone:Go,escapePathComponent:qo,unescapePathComponent:Jo});function Ss(e){return e.type===`activity`}function Cs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ws(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=mi(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 Ts(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(Ss);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=xs.applyPatch(c,i??[],!0,!1);if(!Cs(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=mi(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 Es(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 Ds(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 Os(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 ks(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 As(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 js(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 Ms(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=S(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 Ns(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 Ps(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 Fs(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=Ci(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 Is=12,Ls=/* @__PURE__ */ new Set([`RAW`,`ACTIVITY_SNAPSHOT`,`ACTIVITY_DELTA`,`REASONING_ENCRYPTED_VALUE`,`SUBAGENT_STARTED`,`SUBAGENT_FINISHED`,`SUBAGENT_ERROR`]),Rs=/* @__PURE__ */ new Set([`RUN_STARTED`,`RUN_FINISHED`,`RUN_ERROR`,`MESSAGES_SNAPSHOT`]);function zs(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[$i];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var Bs=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=/* @__PURE__ */ new Map;activeMessageIds=/* @__PURE__ */ new Set;toolCallToMessage=/* @__PURE__ */ new Map;pendingManualMessageId=null;openChunk=null;structuredMessageIds=/* @__PURE__ */ new Set;structuredOutputUpdateBatches=/* @__PURE__ */ new Map;activeRuns=/* @__PURE__ */ new Set;callMessageIds=/* @__PURE__ */ new Map;unassignedCallMessageIds=/* @__PURE__ */ new Set;sealedMessageIds=/* @__PURE__ */ new Set;thinkingOwners=/* @__PURE__ */ new Map;runToolCallIds=[];handOverAtStreamEnd=!1;toolCallsSentToClient=/* @__PURE__ */ new Set;childProcessors=/* @__PURE__ */ new Map;childToolCalls=/* @__PURE__ */ 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 zo,this.events=e.events||{},this.jsonParser=e.jsonParser||h,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??mo(),role:`user`,parts:r,createdAt:/* @__PURE__ */ new Date,...n==null?{}:{metadata:n}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}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=As(this.messages,e,t,n?`error`:void 0,n),a=ka(t),o=n?`error`:`complete`;i=Os(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){let n=this.childOwningToolCall(t=>t.approval?.id===e);n===void 0?(this.messages=js(this.messages,e,t),this.emitMessagesChange()):this.updateChild(n,n=>n.addToolApprovalResponse(e,t))}toModelMessages(){let e=[];for(let t of this.messages)e.push(...$a(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)||Sa(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.pendingManualMessageId&&!t.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null);for(let e of this.callMessageIds.values())for(let n of e)t.has(n)||e.delete(n);for(let e of this.unassignedCallMessageIds)t.has(e)||this.unassignedCallMessageIds.delete(e);for(let e of this.sealedMessageIds)t.has(e)||this.sealedMessageIds.delete(e);for(let[e,n]of this.thinkingOwners)t.has(n.messageId)||this.thinkingOwners.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){for(let e of this.callMessageIds.values())e.clear();this.unassignedCallMessageIds.clear(),this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.sealedMessageIds.clear(),this.thinkingOwners.clear(),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`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_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_START`:{let t=e,n=this.unscopedAssistant(t),r=n.id?this.getMessageState(n.id):void 0;if(r&&(r.currentThinkingStepId=null),t.metadata==null)break;let{messageId:i}=this.ensureAssistantMessage(n.id??void 0,!n.create);this.mergeMessageMetadata(i,t.metadata);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`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:J.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:J.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:J.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:J.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:J.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:J.REASONING_MESSAGE_CONTENT,messageId:r,delta:e.delta??``,...e.metadata===void 0?{}:{metadata:e.metadata},timestamp:n}),i}default:{let n=t&&!Ls.has(e.type)?this.closeChunk():[];return Rs.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:J.TEXT_MESSAGE_END,messageId:e.id,timestamp:t}];case`TOOL_CALL`:return[{type:J.TOOL_CALL_END,toolCallId:e.id,timestamp:t}];case`REASONING_MESSAGE`:return[{type:J.REASONING_MESSAGE_END,messageId:e.id,timestamp:t}]}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,thinkingSteps:/* @__PURE__ */ new Map,thinkingStepSignatures:/* @__PURE__ */ new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:/* @__PURE__ */ new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}getActiveAssistantMessageId(){let e=e=>this.activeRuns.size===0||[...this.activeRuns].some(t=>this.callMessageIds.get(t)?.has(e))||this.pendingManualMessageId===e&&!this.messageStates.get(e)?.isComplete&&!this.isDone,t=Array.from(this.activeMessageIds).reverse();for(let n of t){if(this.sealedMessageIds.has(n))continue;let t=this.messageStates.get(n);if(t&&t.role===`assistant`&&e(n))return n}for(let[t,n]of[...this.messageStates].reverse())if(!this.sealedMessageIds.has(t)&&n.role===`assistant`&&e(t))return t;return null}runOfMessage(e){for(let[t,n]of this.callMessageIds)if(n.has(e))return t}openMessageOfRun(e){let t=this.callMessageIds.get(e);if(!t)return null;for(let e of[...t].reverse())if(!this.sealedMessageIds.has(e)&&this.messageStates.get(e)?.role===`assistant`)return e;return null}unscopedAssistant(e){let t=Ro(e),n=this.activeRuns.size===1?[...this.activeRuns][0]:void 0,r=t??n;if(r!==void 0){let e=this.openMessageOfRun(r);if(e)return{id:e,create:!1};if(t!==void 0||this.activeRuns.has(r))return{id:null,create:!0}}let i=this.getActiveAssistantMessageId();return i?{id:i,create:!1}:{id:null,create:!0}}rememberThinking(e,t,n){let r={messageId:e,stepId:t};this.thinkingOwners.set(t,r),n!==void 0&&n!==t&&this.thinkingOwners.set(n,r)}applyKnownSignature(e,t){if(!e)return!1;let n=this.thinkingOwners.get(e);if(!n)return!1;let r=this.getMessageState(n.messageId);if(!r)return!1;r.thinkingStepSignatures.set(n.stepId,t);let i=r.thinkingSteps.get(n.stepId)??``;return r.thinkingSteps.has(n.stepId)||(r.thinkingSteps.set(n.stepId,i),r.thinkingStepOrder.push(n.stepId)),this.messages=Fs(this.messages,n.messageId,n.stepId,i,t),this.emitMessagesChange(),!0}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.pendingManualMessageId;t&&t!==e&&this.messageStates.get(t)?.isComplete===!1&&!this.messages.some(t=>t.id===e)&&(this.renameMessage(t,e),this.pendingManualMessageId=e);let n=this.getMessageState(e);if(n)return this.resumeAssistantState(e,n),{messageId:e,state:n}}let n=t&&e===void 0?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||mo(),i={id:r,role:`assistant`,parts:[],createdAt:/* @__PURE__ */ 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){let n=q({metadata:typeof t==`object`&&t?{...t}:void 0})?.runId??(this.activeRuns.size===1?[...this.activeRuns][0]:void 0);if(n!==void 0){let t=this.callMessageIds.get(n)??/* @__PURE__ */ new Set;t.add(e),this.callMessageIds.set(n,t)}else this.unassignedCallMessageIds.add(e);if(typeof t!=`object`||!t||Array.isArray(t))return;let r=this.messages.find(t=>t.id===e);if(!r)return;let i=t,a=q(i),o=a!=null&&(`content`in a||`args`in a)?{...i,tanstack:Object.fromEntries(Object.entries(a).filter(([e])=>e!==`content`&&e!==`args`))}:i,s=mi(r.metadata,o),c=Wa(q(i)?.createdAt),l=c!==void 0;this.messages=this.messages.map(t=>t.id===e?{...t,...s===void 0?{}:{metadata:s},...l?{createdAt:c}:{}}: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=>{t.status!==`error`&&(e.outcome?.type===`suspended`?(t.status=`suspended`,t.interruptIds=e.outcome.interruptIds??[]):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&&(console.warn(`[StreamProcessor] Dropped a chunk for unknown subagent ${t}`),!0):(this.findSubagentPart(n)?.part.subagent.status===`error`||((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));for(let n of this.callMessageIds.values())n.delete(e)&&n.add(t);this.unassignedCallMessageIds.delete(e)&&this.unassignedCallMessageIds.add(t),this.sealedMessageIds.delete(e)&&this.sealedMessageIds.add(t);for(let[n,r]of this.thinkingOwners)r.messageId===e&&this.thinkingOwners.set(n,{messageId:t,stepId:r.stepId})}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`,i=this.pendingManualMessageId,a=i?this.runOfMessage(i):void 0,o=this.runOfMessage(t);if(i&&(a===void 0||o===void 0||a===o)){this.pendingManualMessageId=null,i!==t&&this.renameMessage(i,t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1):(n=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 s={id:t,role:r,parts:[],createdAt:/* @__PURE__ */ new Date};this.messages=[...this.messages,s],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}=ba(e.messages),a=this.mergeReasoningFanOut(r.map(so)),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=/* @__PURE__ */ new Map;for(let t of r){let r=new e({subagentRunId:t.id});r.processChunk({type:J.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);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:mo(),role:`assistant`,parts:[e.part]}]):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.length-1;for(;c>=0;){let e=t[c];if(!e||!a(e))break;c--}let l=t[c];if(l?.role===`assistant`&&e.role===`assistant`&&Ca(e.id,l.id)){let n=t.slice(c).flatMap(e=>e.parts);t.splice(c,t.length-c,{...l,parts:[...n,...e.parts]})}else t.push(e)}return o(),t}reconcileSnapshotToolCalls(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=/* @__PURE__ */ 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=/* @__PURE__ */ 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`?Oa(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=Ms(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),i=this.runOfMessage(t),a=e?this.runOfMessage(e.id):void 0;e?(i===void 0||a===void 0||i===a)&&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),o=q(e);this.mergeMessageMetadata(i,o===void 0?void 0:{tanstack:o}),a.hasToolCallsSinceTextStart=!0;let s=e.toolCallId;if(!a.toolCalls.get(s)){let t=`awaiting-input`,n=e.toolCallName,r=e.metadata,o={id:e.toolCallId,name:n,arguments:``,state:t,parsedArguments:void 0,index:a.toolCalls.size,...r!==void 0&&{metadata:r}};a.toolCalls.set(s,o),a.toolCallOrder.push(s),this.runToolCallIds.push(s),this.toolCallToMessage.set(s,i),this.messages=Ds(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=mi(i.metadata,e.metadata)),i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=Ds(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=n.toolCalls.get(e.toolCallId);if(r&&r.state!==`input-complete`){r.arguments=xi(r.arguments,e).args;let i=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,i,r)}}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId)??this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))?.id;if(!t)return;let n=e,r=q(e)?.toolResultOutcome,i=Ta(r)?r:void 0,a=n.state===`output-error`||q(e)?.state===`output-error`||i!==void 0,o;try{o=typeof e.content==`string`?JSON.parse(e.content):e.content}catch{o=e.content}this.messages=As(this.messages,e.toolCallId,o,a?`error`:void 0);let s=a?`error`:`complete`;this.messages=Os(this.messages,t,e.toolCallId,Da(o)?o:fo(e.content),s,s===`error`?Oa(o):void 0,i),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.size===0&&(this.runToolCallIds=[],this.toolCallsSentToClient.clear(),this.handOverAtStreamEnd=!1,this.streamEndEmitted=!1),this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e,n=q(e),r=e.model??n?.model,i=e.responseId??n?.responseId,a=this.callMessageIds.get(e.runId)??(this.activeRuns.has(e.runId)?/* @__PURE__ */ new Set:new Set(this.unassignedCallMessageIds));for(let t of a)this.mergeMessageMetadata(t,hi(e,{...r===void 0?{}:{model:r},...i===void 0?{}:{responseId:i}}).metadata);this.pendingManualMessageId&&a.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null),this.callMessageIds.delete(e.runId);for(let e of a)this.unassignedCallMessageIds.delete(e);if(this.finishReason=t.finishReason===void 0?q(e)?.finishReason??null:t.finishReason,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason===`tool_calls`&&e.outcome?.type!==`interrupt`){for(let e of a)this.sealedMessageIds.add(e);this.handOverAtStreamEnd=this.subagentRunId===void 0;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||Sa(t)||t.output!==void 0||n.some(t=>t.type===`tool-result`&&t.toolCallId===e)||this.isToolCallPartTerminal(e)||this.isToolCallPartAwaitingUserAction(e)||this.finishReason===`length`)continue;let r=t.input??bi(t.arguments);r===void 0?console.warn(`[StreamProcessor] Did not run tool call ${e}: the arguments of ${t.name} are not complete JSON`):(this.toolCallsSentToClient.add(e),this.events.onToolCall?.({toolCallId:e,toolName:t.name,input:r}))}}handleInterrupts(e,t=!0){let n=zs(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`){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=ks(this.messages,e,a,r.id),this.emitMessagesChange()),!t)continue;this.events.onApprovalRequest?.({toolCallId:a,toolName:s,input:c,approvalId:r.id})}else if(i===`client_tool`){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=Ro(e)??(this.activeRuns.size===1?[...this.activeRuns][0]:void 0),n=t===void 0?this.unassignedCallMessageIds:this.callMessageIds.get(t)??this.unassignedCallMessageIds;t?this.activeRuns.delete(t):this.activeRuns.clear();let r=t!==void 0&&this.callMessageIds.has(t)&&n.size===0?void 0:this.ensureAssistantMessage([...n].at(-1)??mo(),!1).messageId,i=new Set(n);r!==void 0&&i.add(r);for(let t of i)this.mergeMessageMetadata(t,hi(e,{stopReason:q(e)?.stopReason??`error`}).metadata);this.pendingManualMessageId&&i.has(this.pendingManualMessageId)&&(this.pendingManualMessageId=null),t!==void 0&&this.callMessageIds.delete(t);for(let e of i)this.unassignedCallMessageIds.delete(e);let a=e.message||`An error occurred`;e.message||console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),r!==void 0&&this.structuredMessageIds.has(r)&&(this.flushStructuredOutputUpdate(r),this.messages=Ps(this.messages,r,a),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`error`),this.emitMessagesChange()),this.events.onError?.(Bo(e))}handleActivitySnapshotEvent(e){this.messages=ws(this.messages,e),this.emitMessagesChange()}handleActivityDeltaEvent(e){this.messages=Ts(this.messages,e),this.emitMessagesChange()}handleReasoningMessageContentEvent(e){let t=this.unscopedAssistant(e),{messageId:n,state:r}=this.ensureAssistantMessage(t.id??void 0,!t.create);this.mergeMessageMetadata(n,e.metadata);let i=e.delta||``,a=r.currentThinkingStepId??e.messageId;r.thinkingSteps.has(a)||(r.thinkingSteps.set(a,``),r.thinkingStepOrder.push(a),r.currentThinkingStepId=a),this.rememberThinking(n,a,e.messageId);let o=(r.thinkingSteps.get(a)??``)+i;r.thinkingSteps.set(a,o),this.messages=Fs(this.messages,n,a,o,r.thinkingStepSignatures.get(a)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(n,a,o)}handleReasoningEncryptedValueEvent(e){let t=e.encryptedValue;if(typeof t!=`string`||t===``)return;if(e.subtype===`tool-call`){this.attachToolCallSignature(e.entityId,t);return}if(this.applyKnownSignature(e.entityId,t))return;let n=this.unscopedAssistant(e),{messageId:r,state:i}=this.ensureAssistantMessage(n.id??void 0,!n.create),a=i.currentThinkingStepId??e.entityId;this.rememberThinking(r,a,e.entityId),this.mergeMessageMetadata(r,e.metadata),i.thinkingStepSignatures.set(a,t);let o=i.thinkingSteps.get(a)??``;i.thinkingSteps.has(a)||(i.thinkingSteps.set(a,o),i.thinkingStepOrder.push(a)),this.messages=Fs(this.messages,r,a,o,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&&this.getMessageState(n.messageId)?n.messageId:t??n.messageId);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}))}else{if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId&&this.getMessageState(n.messageId)?n.messageId:t??n.messageId);r&&(this.flushStructuredOutputUpdate(r),this.messages=Ns(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}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}")`)}else 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=Ds(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=Es(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>=Is&&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.handOverAtStreamEnd&&(this.handOverAtStreamEnd=!1,this.hasError||this.handlePendingToolCalls()),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=Ps(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);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()):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=/* @__PURE__ */ 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.callMessageIds.clear(),this.unassignedCallMessageIds.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.sealedMessageIds.clear(),this.thinkingOwners.clear(),this.openChunk=null,this.finishReason=null,this.handOverAtStreamEnd=!1,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(Vs(t))}};function Vs(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var Hs=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},Us=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}},Ws=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},Gs=/^[a-z][a-z0-9-]{0,63}$/;function Ks(e){return typeof e==`string`&&Gs.test(e)}function qs(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`||!Ks(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Js=/* @__PURE__ */ new WeakMap;function Ys(e){return Js.get(e)??Ro(e)}var Xs=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Zs=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Qs=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},$s=class extends Error{constructor(e,t){super(t===void 0?`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`:`Durable run did not reconnect within its budget of ${t} ms (${e} attempts) — giving up.`),this.name=`StreamReconnectLimitError`}},ec=/* @__PURE__ */ new Set([408,429,502,503,504]),tc=class extends Error{status;retryAfterMs;constructor(e,t,n){super(e),this.status=t,this.name=`StreamHttpError`,this.retryAfterMs=nc(n)}};function nc(e){if(!e)return;let t=Number(e);if(Number.isFinite(t))return t>=0?t*1e3:void 0;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}function rc(e){return e instanceof tc&&ec.has(e.status)}function ic(e){let t=e?.budgetMs,n=e?.maxAttempts??(t===void 0?5:1/0),r=e?.initialDelayMs??e?.delayMs??250,i=e?.maxDelayMs??Math.max(5e3,r);if(e?.maxAttempts!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`Invalid reconnect.maxAttempts: ${n}. Must be a non-negative integer.`);for(let[e,t]of[[`initialDelayMs`,r],[`maxDelayMs`,i]])if(!Number.isFinite(t)||t<0)throw Error(`Invalid reconnect.${e}: ${t}. Must be a non-negative finite number.`);if(t!==void 0&&(!Number.isFinite(t)||t<=0))throw Error(`Invalid reconnect.budgetMs: ${t}. Must be a positive finite number.`);return{maxAttempts:n,initialDelayMs:r,maxDelayMs:i,budgetMs:t}}function ac(e){let t=ic(e),n=/* @__PURE__ */ new Set,r,i=0,a;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,r){if(e)i=0,a=void 0;else if(i+=1,a??=Date.now(),i>t.maxAttempts)throw new $s(t.maxAttempts);let o=t.initialDelayMs===0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,i-1)),s=r===void 0?o*(.5+Math.random()/2):Math.min(r,t.maxDelayMs);if(t.budgetMs!==void 0&&a!==void 0&&Date.now()-a+s>t.budgetMs)throw new $s(i-1,t.budgetMs);await oc(s,n)}}}function oc(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 sc(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var cc=`X-Run-Id`;function lc(e){return{[cc]:e}}function uc(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*dc(e,t){try{let n=ii(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Zs(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
22
- `);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 Xs}finally{try{e.cancel().catch(()=>{})}catch{}e.releaseLock()}}async function*fc(e){let t;for await(let n of e){if(n===`id`||n.startsWith(`id:`)){let e=n===`id`?``:n.slice(3);t=e.startsWith(` `)?e.slice(1):e;continue}if(n.startsWith(`:`)||n.startsWith(`event:`)||n.startsWith(`retry:`))continue;let e=ai(n),r=Fo(JSON.parse(e)),i=t;t=void 0,yield{chunk:r,...i===void 0?{}:{id:i}}}}async function pc(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(qs(t))throw new Hs(t.error.provider)}throw new tc(`HTTP error! status: ${e.status} ${e.statusText}`,e.status,e.headers.get(`retry-after`))}}function mc(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 hc(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 gc(e,t,n,r,i,a){let o=await e(uc(t,mc(i,a)),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await pc(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)?ci(s.messages):[],activeRun:c,interrupts:l,page:hc(s.page)}}async function _c(e,t,n,r,i){let a=await e(uc(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await pc(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*vc(e,t){await pc(e),yield*fc(dc(ri(e),t))}async function*yc(e,t){for await(let{chunk:n}of vc(e,t))yield n}function bc(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 Zs(e)}yield*r(o,a)}}async function*xc(e,t,n){let r=ac(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 Xs||e instanceof Zs||rc(e))&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t,rc(e)?e.retryAfterMs:void 0);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new Qs}return}}function Sc(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&&Js.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(hi({type:J.RUN_FINISHED,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i.runId)}catch(e){if(!r?.aborted&&!a){let t=e instanceof Error?e.message:`Unknown error in connect()`;s({type:J.RUN_ERROR,threadId:o??i.threadId,runId:l??i.runId,timestamp:Date.now(),message:t},i.runId)}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 Cc(e,t,n,r){if(!n)throw Error(`Connection adapter: connect() and send() need a run context with a threadId. ChatClient and the generation clients pass one. Pass it when you call the adapter yourself.`);let i=_o(e),a={...r.body,...n.forwardedProps,...t};return{threadId:n.threadId,runId:n.runId,...n.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n.clientTools??[],context:[],forwardedProps:a}}function wc(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`,...sc(s.headers),...sc(a.headers),...lc(a.runId)},l=Cc(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*xc(bc(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},vc),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=uc(i,{offset:`-1`,runId:n}),s={...sc(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*xc(bc(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},vc),l,a.reconnect)},async hydrate(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t;return gc(a.fetchClient??fetch,i,sc(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 _c(i.fetchClient??fetch,r,sc(i.headers),i.credentials||`same-origin`,n)}}}function Tc(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*yc(a,r):yield*Ec(a,r)}}}async function*Ec(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 Dc(e){return e.resumable}function Oc(e,t){let n=fa(e.descriptor);return n?{...t,metadata:da(n)}:t}function kc(e){return`cancel`in e&&`clearResolution`in e}var Ac=/* @__PURE__ */ new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`]),jc=/* @__PURE__ */ 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`]);function Mc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nc(e){return aa(e)}function Pc(e){if(!Mc(e.metadata))return!1;let t=e.metadata[$i];return!Mc(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 Fc(e){if(!Mc(e.metadata))return!1;let t=e.metadata[$i];return!Mc(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function Ic(e){return e.metadata?.[`tanstack:interruptPayload`]}function Lc(e){if(e.responseSchema!==void 0)try{return Ai(ki(e.responseSchema))}catch{return}}function Rc(e){if(e!==void 0)try{return ca(e)}catch{return}}function zc(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Bc(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(Ii(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 zc(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function Vc(e){for(let t of Ac)if(t===e)return!0;return!1}function Hc(e){for(let t of jc)if(t===e)return!0;return!1}function Uc(e){if(!Mc(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`?!1:t===`item`?Vc(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&Hc(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function Wc(e){return Uc(e)?[e]:!Mc(e)||!Array.isArray(e.errors)?[]:e.errors.every(Uc)?e.errors:[]}function Gc(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 Kc(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Gc(e.interruptIds,t.interruptIds)}function qc(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>Kc(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>Kc(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Jc(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):Gc(e.interruptIds,n)}function Yc(e,t,n){let r=Lc(e)??n?.responseSchemaHash;return Y({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 Xc(e,t){let n=Y(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([Y(e.error)]);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,canResolve:e.canResolve}}var Zc=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;warnedSchemaMismatches=/* @__PURE__ */ new Set;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=/* @__PURE__ */ 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:Y(e.interrupts)};let n=/* @__PURE__ */ new Map;for(let t of e.interrupts){let e=Nc(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,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){this.assertRootMutable(),typeof e==`boolean`?this.resolveBooleanBulk(e):this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)Dc(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Oc(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;e?this.submitBatch(e):this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1)}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)??this.items.find(t=>t.kind===`generic`&&t.canResolve&&t.descriptor.toolCallId===e);return n?t.state===`output-available`?(this.resolveItem(n.descriptor.id,t.output),!0):(this.stageClientToolError(n,t.errorText),!0):!1}stageClientToolError(e,t){this.assertItemMutable(),this.invalidateRetry(),e.canResolve?(e.validationGeneration++,e.resolution=Y(hi(Oc(e,{interruptId:e.descriptor.id,status:`resolved`,payload:{error:t}}),{state:`output-error`})),e.status=`staged`,e.error=void 0,this.publish(),this.maybeSubmit()):(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())}warnSchemaMismatch(e,t,n){this.warnedSchemaMismatches.has(e)||(this.warnedSchemaMismatches.add(e),console.warn(`[TanStack AI] Interrupt "${e}" for tool "${t}": the server and client tool schemas differ, so it is handled as a generic interrupt. Use the same tool definition on the server and the client.`,...n===void 0?[]:[n]))}hydrateInterrupt(e,t,n){let r=Y(e),i=Nc(r);if(i===void 0)return Pc(r)?{descriptor:r,binding:Yc(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 a=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&Lc(r)===i.responseSchemaHash,o=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(Lc(r)??i.responseSchemaHash);if(Fc(r)&&(!o||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Yc(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(o&&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=Zi(e.approvalSchema,e.inputSchema);if(Qi(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:Y(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0};this.warnSchemaMismatch(r.id,i.toolName)}catch(e){this.warnSchemaMismatch(r.id,i.toolName,e)}}if(o&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId){if(Qi(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:Y(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0};this.warnSchemaMismatch(r.id,i.toolName)}}if(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:Y(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(a&&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&&Rc(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===Rc(e.payloadSchema))){let t=Ic(r);return{descriptor:r,binding:Y(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:Y(t)},validationGeneration:0}}}let s=i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||Lc(r)===void 0||i.responseSchemaHash===Lc(r));return{descriptor:r,binding:Yc(r,t,i),kind:`generic`,status:`pending`,canResolve:s,resumable:s,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=Xc(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=Y(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:Y(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=Mc(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`?Y(n.binding):Y({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`){this.hydration?(this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)):(this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts: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);zc(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)})):this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(Oc(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=>Dc(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=Mi(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.resolution=Y(Oc(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit());else{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()}}validateCandidate(e,t){if(e.kind===`generic`){let n=Bc(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 zc(n)?Promise.resolve(n).then(r):r(n)}if(e.kind===`client-tool-execution`){let n=Bc(e.tool?.outputSchema,t,`invalid-tool-output`),r=e=>{if(!(`valid`in e))return e;try{return{valid:!0,payload:Y(e.payload)}}catch(e){return{code:`invalid-tool-output`,message:e instanceof Error?e.message:String(e)}}};return zc(n)?Promise.resolve(n).then(r):r(n)}return this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!Mc(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=Bc(e.tool?.inputSchema,r,`invalid-edited-args`);return zc(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=Bc(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 zc(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!Mc(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=>Dc(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);else{this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=Y({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(kc),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:zc(n)?`async-resolver`:`inactive-transaction`,message:zc(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>Dc(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}i?(this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1)):(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)Dc(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=Wc(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)Dc(e)&&(e.status=`error`);return}let r=n.filter(e=>Jc(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=>Dc(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=Y(e))}else o.push(Y(e));let s=qc(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)Dc(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(Dc).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})}},Qc=/* @__PURE__ */ new WeakMap;function $c(e){let t=Object.entries(e.keys()).filter(e=>!!e[1]).map(e=>e[0]).filter(Ks);if(t.length===1)return t[0];let n=Qc.get(e)??[];if(n.length===1)return n[0]}function el(e,...t){let n=e?.();if(Ks(n))return n;for(let e of t)if(Ks(e))return e}async function tl(e,t){if(!t)throw new Ws;return await e.prepare(t),e.headers(t)}var nl=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})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},rl=class extends nl{emitEvent(){}},il=class{events;constructor(e){this.events=new rl(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){}},al=e=>new il(e);function ol(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function sl(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function cl(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var ll=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;legacyStored=!1;clearedMessageIds=/* @__PURE__ */ new Set;clearedRunIds=/* @__PURE__ */ new Set;ignoredActiveRunIds=/* @__PURE__ */ new Set;clearedToolCallIds=/* @__PURE__ */ new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){if(this.legacyStored)return;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)})}normalize(e){if(Array.isArray(e))this.legacyStored=!0,console.error(`[TanStack AI] The stored chat for threadId "${this.id}" is in the 0.x format (a bare message array). TanStack AI 1.0 does not read this format, so the chat starts empty and the stored value is not overwritten. Clear the chat or the stored value to start saving again.`);else if(e&&Array.isArray(e.messages))return e}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(e=>this.normalize(e)).catch(()=>void 0);let t=this.normalize(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){this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist?this.skipNextPersist=!1:this.writeState()}persistResumeSnapshot(e){this.lastResume=e,this.skipNextPersist||this.writeState()}remove(){this.legacyStored=!1,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)})}else 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=Ys(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=ol(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=cl(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=sl(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=sl(e);t&&this.clearedMessageIds.add(t);let n=ol(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Ys(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 ul(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function dl(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function fl(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var pl=class{clearedMessageIds=/* @__PURE__ */ new Set;clearedRunIds=/* @__PURE__ */ new Set;ignoredActiveRunIds=/* @__PURE__ */ new Set;clearedToolCallIds=/* @__PURE__ */ 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=Ys(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=ul(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=fl(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=dl(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=dl(e);t&&this.clearedMessageIds.add(t);let n=ul(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Ys(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`}},ml=8;function hl(){let{scheduler:e}=globalThis;return e?.yield?e.yield():new Promise(e=>setTimeout(e,0))}function gl(e){let t=/* @__PURE__ */ 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 _l(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 Tc(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function vl(e){return`connect`in e}function yl(e){if(e.type!==`RUN_FINISHED`||e.outcome?.type===`interrupt`)return!1;let t=e;return t.finishReason===void 0?q(e)?.finishReason===`tool_calls`:t.finishReason===`tool_calls`}function bl(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 xl(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(`
23
- `),...t===void 0?{}:{body:t}};let r=[],i;for(let t of e)typeof t.content==`string`?r.push({type:`text`,content:t.content}):(typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content),i=mi(i,t.content.metadata));return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function Sl(e){if(typeof e==`object`&&e&&!Array.isArray(e)&&`approved`in e&&typeof e.approved==`boolean`)return e.approved}function Cl(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 wl=2e3,Tl=/* @__PURE__ */ 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 El(e){return e.type===`REASONING_ENCRYPTED_VALUE`?e.subtype===`message`&&typeof e.encryptedValue==`string`&&e.encryptedValue.length>0:Tl.has(e.type)}function Dl(e){return e.map(e=>({...e,parts:e.parts.map(e=>Object.isFrozen(e)?e.type===`subagent`?{...e,subagent:{...e.subagent,messages:Dl(e.subagent.messages)}}:{...e}:e)}))}function Ol(e){let t=[];for(let n of e)for(let e of n.parts)e.type===`subagent`&&(t.push(e),t.push(...Ol(e.subagent.messages)));return t}function kl(e){if(`subagentRunId`in e&&typeof e.subagentRunId==`string`)return e.subagentRunId}var Al=64;function jl(e){if(Array.isArray(e))return e.map(jl);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]=jl(r));return t}var Ml=class{processor;subagentHandles=/* @__PURE__ */ new Map;stoppedSubagentIds=/* @__PURE__ */ new Set;connection;threadId;persistor;clearedStreamTracker=new pl;snapshotAtom=Ot({messages:[],status:`ready`,isLoading:!1,error:void 0,isSubscribed:!1,connectionStatus:`disconnected`,sessionGenerating:!1,queue:[],runId:null,hasOlderMessages:!1,isHydrating:!1,interruptState:{interrupts:Object.freeze([]),interruptErrors:Object.freeze([]),resuming:!1}});get status(){return this.snapshotAtom.get().status}get isLoading(){return this.snapshotAtom.get().isLoading}get error(){return this.snapshotAtom.get().error}get isSubscribed(){return this.snapshotAtom.get().isSubscribed}get connectionStatus(){return this.snapshotAtom.get().connectionStatus}get sessionGenerating(){return this.snapshotAtom.get().sessionGenerating}get hasOlderMessages(){return this.snapshotAtom.get().hasOlderMessages}get isHydrating(){return this.snapshotAtom.get().isHydrating}get currentRunId(){return this.snapshotAtom.get().runId}lastResume=null;runParents=/* @__PURE__ */ new Map;supersededInterruptRunIds=/* @__PURE__ */ new Set;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=/* @__PURE__ */ new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=/* @__PURE__ */ 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;activeRunIds=/* @__PURE__ */ new Set;disposed=!1;hydrationError;tailing=!1;hydrationInFlight;storeHydrating=!1;rejoinRunId;cachesMessages;historyPageSize;olderMessagesCursor;knownServerMessageIds=/* @__PURE__ */ new Set;loadOlderMessagesInFlight=!1;historyGeneration=0;devtoolsMounted=!1;callbacksRef;constructor(e){if(gl(e.interrupts),typeof e.threadId!=`string`||e.threadId===``)throw Error(`ChatClient: threadId is required (a non-empty string).`);this.threadId=e.threadId;let t=!0;e.persistence===!0?(t=!1,this.historyPageSize=e.history?.pageSize):(e.persistence&&(this.persistor=new ll(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))),this.historyPageSize=void 0),this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=bl(e.queue);let n=_l(e);if(this.connectionDrainsOnSend=vl(n),this.connection=Sc(n),this.clientToolsRef={current:/* @__PURE__ */ new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??al)(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 Zc({...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&&Dl(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 Bs({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.syncSubagentHandles(),this.persistor?.notifyMessagesChanged(e),Qr(this.snapshotAtom,{messages:Zr(this.frozenMessages,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`);else 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,threadId:this.threadId,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.snapshotAtom.set(this.readSnapshot(this.storeHydrating||!t&&!!this.connection.hydrate))}attach(){this.disposed||this.tailing||(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=Cl(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=ci(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 Hs&&this.byok?.request(t.provider,`missing`),t instanceof Us&&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.devtoolsMounted||(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}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=Ys(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Ys(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=Ys(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=Ys(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`&&yl(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=Ys(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(t&&!yl(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));r||i||a||o||s||c||l?(this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset()):this.notifyResumeStateChange(`live`)}markLineageAnswered(e){let t=e,n=0;for(;t!==void 0&&n<Al;){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&&(Qr(this.snapshotAtom,{runId:e}),this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){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)}async submitInterruptBatch(e){let t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=Sl(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)}`}frozenMessages=/* @__PURE__ */ new WeakMap;freezeSnapshotQueue(e){return Object.freeze(e.map(e=>{if(typeof e.content!=`object`)return Object.freeze({...e});let t=Array.isArray(e.content.content)?Object.freeze(e.content.content.map(e=>Yr(e))):e.content.content;return Object.freeze({...e,content:Object.freeze({...e.content,content:t})})}))}readSnapshot(e){return Object.freeze({...this.snapshotAtom.get(),messages:Zr(this.frozenMessages,this.processor.getMessages()),queue:this.freezeSnapshotQueue(this.getQueue()),isHydrating:e,interruptState:this.interruptManager.getState()})}subscribeSnapshot=e=>ei(this.snapshotAtom,e);getSnapshot=()=>this.snapshotAtom.get();setIsLoading(e){Qr(this.snapshotAtom,{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){Qr(this.snapshotAtom,{status:e}),this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){Qr(this.snapshotAtom,{isSubscribed:e}),this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){Qr(this.snapshotAtom,{connectionStatus:e}),this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}syncIsHydrating(){let e=this.hydrationInFlight!==void 0||this.storeHydrating;this.isHydrating!==e&&(Qr(this.snapshotAtom,{isHydrating:e}),this.callbacksRef.current.onHydratingChange(e))}setSessionGenerating(e){this.sessionGenerating!==e&&(Qr(this.snapshotAtom,{sessionGenerating:e}),this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();Qr(this.snapshotAtom,{interruptState:n}),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){Qr(this.snapshotAtom,{error:e}),this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){return{hookId:this.threadId,clientId:this.threadId,threadId:this.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:jl(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<ml||(n=0,typeof document<`u`&&document.hidden||await hl())}}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()},wl);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&El(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=Fo(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=q(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(t)?t:[]}}if(this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(Ys(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=kl(e);if(t&&e.type===J.SUBAGENT_STARTED&&this.stoppedSubagentIds.delete(t),t&&this.stoppedSubagentIds.has(t))this.updateRunLifecycle(e),this.resolveJoinedRun(e);else{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=q(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=Ys(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=Ys(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){this.isSubscribed?(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0}):this.subscribe()}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. Resolve the interrupts first.`);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. Resolve the interrupts first.`);let t=po(e,mo);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();this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading?this.queuePostStreamAction(async()=>{await this.streamResponse()}):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.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=el(this.byokProvider,f.provider,$c(this.byok));m=await tl(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?Vi(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 Hs&&this.byok?.request(n.provider,`missing`),n instanceof Us&&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 Hs||n instanceof Us||n instanceof Ws))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&&Ii(t.outputSchema)?await this.validateClientToolOutput(t,e.output):e.output;this.interruptManager.getDescriptors().some(t=>t.toolCallId===e.toolCallId)&&(n=Y(n)),e={...e,output:n}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}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))||(this.isLoading?this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve()):await this.checkForContinuation()))}async validateClientToolOutput(e,t){let n=await Hi(e.outputSchema,t);if(!n.success)throw Error(n.issues.map(e=>e.message).join(`, `));return n.data}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;else 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=e=>{let{input:t,...n}=e,r=ha(n.metadata);return r===void 0?n:{...n,input:r}},t=Ol(this.processor.getMessages()),n=new Set(t.map(e=>e.subagent.id));for(let e of this.subagentHandles.keys())n.has(e)||this.subagentHandles.delete(e);for(let n of t){let t=n.subagent.id,r=this.subagentHandles.get(t);if(r){if(n.subagent===r)continue;let{stop:t}=r;for(let e of Object.keys(r))Reflect.deleteProperty(r,e);Object.assign(r,e(n.subagent),{stop:t}),n.subagent=r;continue}let i={...e(n.subagent),stop:()=>{this.stopSubagent(t)}};this.subagentHandles.set(t,i),n.subagent=i}}stopSubagent(e){let t=this.subagentHandles.get(e);t&&t.status===`running`&&(this.stoppedSubagentIds.add(e),this.processor.processChunk({type:J.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=ci(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}}setHasOlderMessages(e){Qr(this.snapshotAtom,{hasOlderMessages:e})}resetHistoryPaging(){this.setHasOlderMessages(!1),this.olderMessagesCursor=void 0,this.knownServerMessageIds.clear(),this.historyGeneration++}applyHydrationPage(e){e?.truncated===!0?(this.setHasOlderMessages(!0),this.olderMessagesCursor=e.cursor):(this.setHasOlderMessages(!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=xl(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(){let e=this.getQueue();Qr(this.snapshotAtom,{queue:this.freezeSnapshotQueue(e)}),this.callbacksRef.current.onQueueChange(e),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(Dl(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=_l({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=vl(n),this.connection=Sc(n),t&&this.subscribe()}if(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=/* @__PURE__ */ new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=bl(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}};let Nl;function Pl(e,t,n){if(!n){if(!Nl)try{let e=`astralbeam:draft-session`;Nl=globalThis.sessionStorage?.getItem(e)??Re(),globalThis.sessionStorage?.setItem(e,Nl)}catch{Nl??=Re()}n=`new:${Nl}`}return JSON.stringify([e.replace(/\/+$/,``),t,n])}function Fl(e){return typeof e==`object`&&!!e&&`id`in e&&typeof e.id==`string`&&`name`in e&&typeof e.name==`string`&&`size`in e&&typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0&&`mimeType`in e&&typeof e.mimeType==`string`&&`status`in e&&e.status===`ready`&&`fileId`in e&&typeof e.fileId==`string`&&(!(`kind`in e)||typeof e.kind==`string`&&[`image`,`pdf`,`text`,`data`,`office`].includes(e.kind))&&(!(`error`in e)||typeof e.error==`string`)}function Z(e,t,n,r,i=`draft`){if(!t)return``;let a=`astralbeam:${i}:${Pl(e,t,n)}`;try{if(r===void 0)return globalThis.localStorage?.getItem(a)??``;r?globalThis.localStorage?.setItem(a,r):globalThis.localStorage?.removeItem(a)}catch{}return``}function Il({apiUrl:e,identity:t,threadId:n,update:r,moveTo:i}){let a=()=>{if(!t)return[];let a=`astralbeam:attachments:${Pl(e,t,n)}`,o=e=>{let t=JSON.parse(globalThis.localStorage?.getItem(e)??`[]`);if(!Array.isArray(t)||!t.every(Fl))throw TypeError(`Stored attachment draft is invalid`);return t},s=o(a);if(r&&(s=r(s).filter(e=>e.status===`ready`&&e.fileId!==void 0)),i!==void 0){let n=`astralbeam:attachments:${Pl(e,t,i)}`;s=[...new Map([...o(n),...s].map(e=>[e.id,e])).values()],globalThis.localStorage?.setItem(n,JSON.stringify(s)),globalThis.localStorage?.removeItem(a)}else r&&(s.length?globalThis.localStorage?.setItem(a,JSON.stringify(s)):globalThis.localStorage?.removeItem(a));return s};return globalThis.navigator?.locks?navigator.locks.request(`astralbeam:attachment-drafts`,a):Promise.resolve().then(a)}function Ll(e){return e?`~standard`in e?`jsonSchema`in e[`~standard`]?Vi(e):{type:`object`}:e:{type:`object`,properties:{}}}async function Rl(e,t){let n=await Hi(e,t);return n.success?n.data??{}:null}const zl=Symbol(`Host tool was not executed`);function Bl(e,t,n,r,i){return[...Object.keys(e).length>0?[Vl(e,n)]:[],Hl(),...Ul(t,r,i)]}function Vl(e,n){let r=Object.entries(e).map(([e,{description:t,parameters:n}])=>`- ${e}: ${t} Props schema: ${JSON.stringify(Ll(n))}`).join(`
24
- `);return Io({name:t,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:
25
- `+r,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,t)=>n(e,t?.toolCallId??``))}function Hl(){return Io({name:ne,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 Ul(e,t,n){return Object.entries(e).map(([e,r])=>Io({name:e,description:r.description,inputSchema:Ll(r.parameters),...r.metadata?{metadata:r.metadata}:{}}).client(async(i,a)=>{let o=!1;try{let s=n?.(e,r,a?.toolCallId);t?.(`tool`,`executing host tool "${e}"`,{input:i});let c=await Rl(r.parameters,i??{});if(c==null)throw t?.(`error`,`input for host tool "${e}" failed schema validation`,{input:i}),Error(`Input for tool "${e}" failed schema validation`);a?.abortSignal?.throwIfAborted();let l=s?.()??r;o=!0;let u=await l.execute(c);try{u=Y(u)}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:u}),u}catch(n){t?.(`error`,`host tool "${e}" threw`,{error:n});let r=n instanceof Error?n:Error(String(n));throw o||Object.assign(r,{[zl]:!0}),r}}))}async function Wl(e,t){switch(e.action){case`connect`:case`headers`:{let n=await H({mcp_server_id:e.mcpServerId},t);return e.action===`connect`?n:(await I(n.id,{lock_version:n.lock_version,headers:e.headers},t),{id:n.id})}case`disconnect`:return f(e.id,t);case`test`:return We(e.id,t)}}async function Gl(e,t){let n=window.open(`about:blank`,`_blank`,`popup,width=600,height=720`);if(!n)throw Error(`Allow popups to authorize this connection.`);try{let r=e.id??(await H({mcp_server_id:e.mcpServerId},await t())).id,i=await V(r,await t()),a={organizationId:i.attempt.organization_id,tenantId:i.attempt.tenant_id,connectionId:i.attempt.connection_id,id:i.attempt.id},o=new URL(i.popup_url);o.searchParams.set(`origin`,window.location.origin);let{promise:s,resolve:l,reject:u}=Promise.withResolvers(),d={state:`waiting`},f=new AbortController,p=!1,m=e=>u(e instanceof Error?e:/* @__PURE__ */ Error(`Authorization failed.`)),h=async()=>{let e=await t();return f.signal.throwIfAborted(),{...e,signal:AbortSignal.any([f.signal,...e.signal?[e.signal]:[]])}},g=async()=>{if(!(p||f.signal.aborted)){p=!0;try{if(d.state===`binding`&&(await c(r,{attempt_id:a.id,challenge:d.challenge},await h()),f.signal.throwIfAborted(),d={state:`completing`}),d.state===`completing`){let e=await xt(r,{attempt_id:a.id},await h());if(f.signal.throwIfAborted(),e){l();return}}n.closed&&m(/* @__PURE__ */ Error(`Authorization window closed.`))}catch(e){let t=e instanceof Error?e.status:void 0;!(e instanceof TypeError)&&t!==429&&(t??0)<500&&m(e)}finally{p=!1}}},_=e=>{if(e.source!==n||e.origin!==o.origin)return;let t=e.data;t?.attempt&&t.attempt.id===a.id&&t.attempt.organizationId===a.organizationId&&t.attempt.tenantId===a.tenantId&&t.attempt.connectionId===a.connectionId&&t.type===`mcp-browser-challenge`&&d.state===`waiting`&&typeof t.challenge==`string`&&(d={state:`binding`,challenge:t.challenge},g())},v=setInterval(()=>void g(),5e3),y=setTimeout(()=>m(/* @__PURE__ */ Error(`Authorization expired. Try connecting again.`)),6e5);try{window.addEventListener(`message`,_),n.location.replace(o.href),await s}finally{f.abort(),window.removeEventListener(`message`,_),clearInterval(v),clearTimeout(y)}return r}finally{n.close()}}const Kl=`Reopen this conversation or start a new one before sending.`;function ql(e,t){return e.length===t.length&&e.every((e,n)=>e.name===t[n]?.name&&e.title===t[n]?.title)}function Jl(e,t=!1){let n={...e},i=At(n.debug),a=/* @__PURE__ */ new Set,s,c=()=>s?.options??n,l={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,history:`idle`,messagesCursor:void 0,olderMessagesLoading:!1,submission:void 0,activeToolCallIds:[],pendingInteractions:[]},d,f=/* @__PURE__ */ new Map,p,m=`ready`,h,g=e=>{let t=h||d?.phase===`submitting`?m===`streaming`||l.status===`streaming`?`streaming`:`submitted`:m;l={...l,...e,status:t,history:p?.phase??`idle`};for(let e of a)e()},_=e=>e.client===G&&e.selection===R,y=e=>h===e&&_(e),x=e=>{y(e)&&(h=void 0,g({}))},S=({id:e,content:t,phase:n,error:r})=>({id:e,content:t,phase:n,...r?{error:r}:{}}),w={submitting:[`accepted`,`failed`,`refused`],failed:[`submitting`],accepted:[],refused:[]},E=(e,t,n)=>w[e.phase].includes(t)?(e.phase=t,e.error=n,e===d&&g({submission:S(e)}),!0):!1,O=e=>e.submission===d&&y(e),k=e=>O(e)&&e.submission.phase===`submitting`,A=(e,t)=>e.delivery.state===`undispatched`?E(e,`refused`,t):E(e,`failed`,t??/* @__PURE__ */ Error(`This message may not have been sent. Retry to send it.`)),M=e=>{let t=d;return t?.phase===`submitting`&&A(t,t.delivery.state===`uncertain`?void 0:Error(e)),t?.phase===`refused`&&t.onRefused?.(),d=void 0,t},N=v({apiUrl:n.apiUrl,scope:`tenant`,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),F,ee,I,L=!1,R=0,te=0,ne=async e=>{for(;_(e);){let e=p;try{await e?.completion}catch(t){if(e===p)throw t}if(e===p)return}},B=async e=>{if(await ne(e).catch(()=>void 0),!k(e))return!1;if(l.history===`failed`)throw Error(Kl);return!0},ie=new AbortController,V,ae=!1,oe=[],H=/* @__PURE__ */ new Map,U=0,se=/* @__PURE__ */ new WeakMap,le=e=>{for(let t of e){if(t.role!==`user`||H.get(t.id)?.attachmentParts||!t.parts.some(e=>`fileId`in e))continue;let e=t.parts.map(e=>Object.freeze({...e}));Object.freeze(e),H.set(t.id,{...H.get(t.id),attachmentParts:e}),U++}},ue=Re(),de=()=>{d&&E(d,`accepted`)&&(l.thread&&g({thread:{...l.thread,hasMessages:!0}}),d.callbacks?.onAccepted?.())},pe=e=>{let t=[...G.getSnapshot().messages],n=t.findLastIndex(e=>e.role===`user`);n!==-1&&(t[n]=xe([e])[0],le([t[n]]),G.setMessagesManually(t),nt&&st())},he=/* @__PURE__ */ new Set,ge=/* @__PURE__ */ new Map,ve=/* @__PURE__ */ new Map,W=/* @__PURE__ */ new Map,be=/* @__PURE__ */ new Map,Se=e=>{let t=ge.get(e);return t?`live:${t}:${e}`:e},Ce=e=>{let t=/* @__PURE__ */ new Map;for(let n of e.pending_interactions){let e=`live:${n.source_message_id}:${n.tool_call_id}`,r=tt(n.source_message_id,n.source_part_id,n.response_target_id),i=W.get(e)??W.get(r);i&&(t.set(r,i),ge.get(n.tool_call_id)===n.source_message_id&&t.set(e,i))}W.clear();for(let[e,n]of t)W.set(e,n)},we=e=>{(l.auth.status!==`error`||l.auth.error!==e)&&n.streamCallbacks?.onError?.(e)},Te=e=>{if(e instanceof Error&&e.name===`AbortError`)return;let t=e instanceof Error?e:Error(String(e));g({error:t}),we(t)},De=e=>{g({unavailableMcpConnections:l.unavailableMcpConnections?.filter(t=>t!==e)??[]})},ke=async(e=!0)=>{let t=R,n=N.session.abortController.signal,r=await T(N);if(n.throwIfAborted(),e&&t!==R)throw new DOMException(`Conversation changed`,`AbortError`);return{apiUrl:N.apiUrl,astralBeamToken:r,cache:`no-store`,signal:e?AbortSignal.any([ie.signal,n]):n,fetchClient:(e,t)=>ot({...N,input:e,init:t})}},Ae=0,Me,Ne=async()=>{let e=++Ae,t=R;if(l.thread?.agentId===null){g({capabilities:{attachments:!1}});return}let r=l.thread?l.thread.agentId:n.agentId;try{let n=await ke();if(e!==Ae||t!==R)return;let a=await Oe(r?{agentId:r}:{},n);if(e!==Ae||t!==R)return;let o=a.capabilities?.attachments!==!1;g({capabilities:{attachments:o}}),i?.(`mount`,`agent capabilities resolved`,{attachments:o})}catch(e){i?.(`error`,`agent capabilities could not be resolved; keeping the defaults`,e)}},Fe=/* @__PURE__ */ new Map,Ie=/* @__PURE__ */ new Set,Le=/* @__PURE__ */ new Set,ze=0,Be=()=>{ze++;for(let e of Fe.values())e();Fe.clear(),Ie.clear(),Le.clear()},He=async(e,t)=>{if(!c().onRenderWidget)return{widget:e.widget,rendered:!1};let n=R,r=ze,i=c().widgets??{};if(!Object.hasOwn(i,e.widget))throw Error(`Unknown widget "${e.widget}"`);let a=i[e.widget],o=await Rl(a?.parameters,e.props??{});if(n!==R||r!==ze||l.thread?.role===`viewer`)return{widget:e.widget,rendered:!1};if(a!==c().widgets?.[e.widget])return He(e,t);if(o==null)throw Error(`Props for widget "${e.widget}" failed validation`);let s=c().onRenderWidget;if(!s)return{widget:e.widget,rendered:!1};Fe.get(t)?.(),Fe.delete(t);let u,d=s({widget:e.widget,props:o,toolCallId:t,release:()=>{Fe.get(t)===u&&Fe.delete(t)}});return d&&(u=d,Fe.set(t,d)),Ie.add(t),{widget:e.widget,rendered:!0}},Ue=e=>Object.freeze(e.map(e=>{let t=H.get(e.id),n=se.get(e);if(n&&n.presentation===t)return n.message;let r=t?.attachmentParts??e.parts,i=t?.renderIds,a=r.map(t=>{if(t.type!==`tool-call`||t.name!==`render_widget`||t.state!==`complete`||!t.input)return t;let n=t,r=tt(e.id,t.id),a=n.applicationPartId?tt(e.id,n.applicationPartId,n.responseTargetId):r,o=n.upstreamToolCallId,s=n.widgetRenderId??i?.get(r)??i?.get(a)??(o&&ge.get(o)===e.id&&Ie.has(o)?o:t.id);return(i?.get(r)!==s||i.get(a)!==s)&&(i=new Map(i).set(r,s).set(a,s)),n.widgetRenderId===s?t:Object.freeze({...t,widgetRenderId:s})});a.some((e,t)=>e!==r[t])&&(Object.freeze(a),r=a),i&&i!==t?.renderIds&&(t={...t,renderIds:i},H.set(e.id,t),U++);let o=r===e.parts?e:Object.freeze({...e,parts:r});return se.set(e,{presentation:t,message:o}),o})),We=e=>{if(l.thread?.role!==`viewer`)for(let t of e)for(let e of t.parts){if(e.type!==`tool-call`||e.name!==`render_widget`||e.state!==`complete`||!e.input)continue;let t=e.widgetRenderId??e.id;if(Ie.has(t)||Le.has(t))continue;Le.add(t);let n=R,r=ze,{widgets:a,onRenderWidget:o}=c();He(e.input,t).catch(e=>i?.(`error`,`Saved widget could not be rendered`,e)).finally(()=>{n===R&&r===ze&&(Le.delete(t),(a!==c().widgets||o!==c().onRenderWidget)&&We(l.messages))})}},Ge=()=>{let e=R;return Bl(c().widgets??{},n.tools??{},He,i,(t,r,i)=>{let a=te,o=G,s=I,c=N.apiUrl;return()=>{let u=n.tools&&Object.hasOwn(n.tools,t)?n.tools[t]:void 0;if(e!==R||a!==te||o!==G||s!==I||c!==N.apiUrl||l.thread?.role===`viewer`||!i||!he.has(i)||!u||u.parameters!==r.parameters)throw new DOMException(`Host tool authority changed`,`AbortError`);return u}}).map(e=>{if(!e.execute)return e;let t=e.execute;return{...e,execute:async(e,n)=>{let r=n?.toolCallId;if(!r||!he.has(r))throw Error(`A saved tool call cannot execute again. Send a new message to request it.`);let i=W,a=Se(r),o=I,s=N.apiUrl;try{let r=await t(e,n);return I===o&&N.apiUrl===s&&i.set(a,{outcome:`succeeded`,output:r??null}),r}catch(e){throw!(e instanceof Error&&zl in e)&&I===o&&N.apiUrl===s&&i.set(a,{outcome:`unknown`,output:{error:e instanceof Error?e.message:String(e)}}),e}}}})},Ke=()=>{let e=Ge(),t=e.map(e=>{let t=e.metadata?.title;return{name:e.name,title:typeof t==`string`&&t.length>0?t:void 0}});return ql(l.agentTools,t)||g({agentTools:t}),e},Je=()=>n.debug?{debug:!0}:{},Ye=async(e,t,n)=>{if(!y(n))throw new DOMException(`Request cancelled`,`AbortError`);let r=l.thread;if(!r||typeof e.body!=`string`)throw Error(`Open a conversation before sending.`);let i=JSON.parse(e.body),a=rt(),o,s=i.messages.at(-1)?.role===`user`&&n.kind===`submission`&&k(n)?n.submission:void 0,c=s?.delivery;if(s)o={...i,threadId:r.id,resume:void 0,parentRunId:void 0,messages:[i.messages.at(-1)],tools:c?.state===`uncertain`?c.tools:i.tools,forwardedProps:{...i.forwardedProps,clientId:ue}};else{ft();let e=await ct(r.id,t,void 0,ge);if(!y(n))throw new DOMException(`Request cancelled`,`AbortError`);g({thread:Ee(e.thread,e.messages.length>0)}),Ce(e);let s=e.pendingInteractions.filter(e=>W.has(Se(e.toolCallId))),c=s.find(e=>e.toolCallId===i.messages.at(-1)?.toolCallId)??s[0],l=e.pendingInteractions.flatMap(e=>{let t=W.get(Se(e.toolCallId));return t&&e.sourceMessageId===c?.sourceMessageId?[{source_message_id:e.sourceMessageId,source_part_id:e.sourcePartId,response_target_id:e.responseTargetId,...t}]:[]});if(l.length===0)return new Response(``,{headers:{"Content-Type":`text/event-stream`}});a=je(r.id),o={client_id:ue,run_id:i.runId,...i.parentRunId?{parent_run_id:i.parentRunId}:{},results:l}}he.clear(),g({activeToolCallIds:[]});let u=new Headers(e.headers);if(s&&u.set(`Idempotency-Key`,s.key),!y(n))throw new DOMException(`Request cancelled`,`AbortError`);s&&s.delivery.state===`undispatched`&&(s.delivery={state:`uncertain`,tools:i.tools});let d=await j(a,{...t,...e,headers:u,body:JSON.stringify(o)}).catch(e=>{if(!y(n))throw e;s&&c?.state===`undispatched`&&P(e)&&(e.status===400||e.status===413||e.status===429)&&(s.delivery={state:`undispatched`});let t=P(e)?e.body?.usage_limit:void 0;throw t&&g({usageLimitReached:{name:t.name,resetsAt:t.resets_at}}),e});if(!y(n))throw new DOMException(`Request cancelled`,`AbortError`);if(d.headers.get(`Content-Type`)?.includes(`application/json`)){let e=await d.json();if(!y(n))throw new DOMException(`Request cancelled`,`AbortError`);if(g({thread:{...l.thread,version:e.thread_version},...e.usage_limit?{usageLimitReached:{name:e.usage_limit.name,resetsAt:e.usage_limit.resets_at}}:{}}),s){let i=await ct(r.id,t,void 0,ge);if(!y(n))throw new DOMException(`Request cancelled`,`AbortError`);let a=i.messages.find(t=>t.id===e.accepted_message_id);a&&pe(a),de()}return new Response(``,{headers:{"Content-Type":`text/event-stream`}})}return d},Xe=wc(()=>z(rt(),N.apiUrl),async()=>{let e=h;if(!e||!y(e))throw new DOMException(`Request cancelled`,`AbortError`);let t=await ke();if(!y(e))throw new DOMException(`Request cancelled`,`AbortError`);return{fetchClient:(n,r)=>Ye(r??{},{...t,signal:r?.signal??t.signal},e)}}),Ze=Xe.connect;Xe.connect=async function*(...e){try{for await(let t of Ze(...e)){if(t.type===J.TOOL_CALL_START&&t.parentMessageId&&ge.set(t.toolCallId,t.parentMessageId),t.type!==J.MESSAGES_SNAPSHOT){yield t;continue}let e;yield{...t,messages:t.messages.map(t=>t.role===`assistant`?(e=ve.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&&P(e.cause)?e.cause:e}};let $e=()=>{let e=new Ml({connection:{...Xe,hydrate:(t,n)=>{let r=et;if(!r)return Promise.resolve({messages:[],activeRun:null,interrupts:null,page:{truncated:!1}});let i=n?.before!==void 0,a=i?p?.owner:{client:e,selection:R},o=()=>a!==void 0&&p?.owner===a&&_(a),s=(async()=>{let t=await ct(r,await ke(),n?.before,ge);for(;n?.before&&t.messages.every(e=>e.role===`tool`)&&t.page_after;){let e=await ct(r,await ke(),t.page_after,ge);t={...e,messages:[...e.messages,...t.messages]}}if(!o())throw new DOMException(`Conversation changed`,`AbortError`);i||Ce(t),oe=i?[...t.messages,...oe]:t.messages;let a=new Set(t.messages.map(e=>e.id)),s=xe(oe,i?l.pendingInteractions:t.pendingInteractions,ge).filter(e=>a.has(e.id));if(le(s),i)g({messagesCursor:t.page_after??void 0});else{t.thread.role===`viewer`&&Be();let n=l.thread?.agentId!==t.thread.agent_id;g({thread:Ee(t.thread,t.messages.length>0),messagesCursor:t.page_after??void 0,pendingInteractions:t.pendingInteractions}),n&&Ne(),s.length===0&&e.setMessagesManually([])}return{messages:s,activeRun:null,interrupts:null,page:t.page_after?{truncated:!0,cursor:t.page_after}:{truncated:!1}}})();if(!i&&a){let e=s.then(()=>`idle`,()=>`failed`).then(e=>(p&&o()&&(p.phase=e,nt&&st(),g({})),s));p={owner:a,phase:l.messages.length>0||l.thread?.hasMessages===!1?`refreshing`:`loading`,completion:e},e.catch(()=>void 0),g({olderMessagesLoading:!1})}return s}},threadId:et??ue,persistence:!0,history:{pageSize:100},queue:`drop`,tools:Ke(),forwardedProps:Je(),onInterruptStateChange:t=>{G===e&&i?.(`tool`,`interrupt state changed`,t)},onCustomEvent:(t,n)=>{if(G!==e)return;if(t===`astralbeam_thread`){let e=n;if(l.thread?.id===e.threadId){if(e.acceptedMessage&&d?.phase===`submitting`&&pe(e.acceptedMessage),e.acceptedMessageId&&de(),e.saved)for(let t of e.executableToolCallIds??[])he.has(t)||W.delete(Se(t)),he.add(t);g({thread:{...l.thread,version:e.version},activeToolCallIds:[...he]})}return}if(t===`astralbeam_mcp_tools`){let e=n,t={};for(let n of e.tools??[])typeof n.name==`string`&&typeof n.title==`string`&&(t[n.name]=n.title);g({serverToolTitles:t,unavailableMcpConnections:e.unavailable??[]});return}let r=n;if(t===`astralbeam.usage_limit.reached`&&typeof r?.name==`string`&&typeof r.resetsAt==`string`){g({usageLimitReached:{name:r.name,resetsAt:r.resetsAt}});return}let a=n?.state;t===`astralbeam.sandbox.status`&&(a===`starting`||a===`ready`||a===`error`)?(i?.(`sandbox`,`sandbox ${a}`),g({sandboxStatus:a})):i?.(`stream`,`custom event "${t}"`,n)},onChunk:t=>{G===e&&(t.type===J.RUN_STARTED&&g({serverToolTitles:{},unavailableMcpConnections:[]}),n.streamCallbacks?.onChunk?.(t))},onResponse:t=>{G===e&&n.streamCallbacks?.onResponse?.(t)},onFinish:t=>{G===e&&n.streamCallbacks?.onFinish?.(t)},onError:t=>{G===e&&(d?.phase!==`submitting`&&t.name!==`AbortError`&&g({error:t}),we(t))}});return e},et,G=$e(),nt,it,at=-1,st=()=>{let e=G.getSnapshot(),t=it!==e.messages||at!==U;if(!t&&m===e.status)return;let n={};m!==e.status&&e.status===`submitted`&&(n.usageLimitReached=void 0),m=e.status,t&&(n.messages=Ue(e.messages),n.sandbox=C(n.messages),it=e.messages,at=U),g(n),t&&We(l.messages)},lt=()=>{if(!nt){let e=G,t=R;nt=e.subscribeSnapshot(()=>{G===e&&t===R&&st()}),st(),We(l.messages)}G.attach()},ut=e=>{let t=G;h=void 0,p=void 0,nt?.(),nt=void 0,it=void 0,G=$e(),e&&G.setMessagesManually(e),m=`ready`,t.stop(),t.detach(),he.clear(),g({activeToolCallIds:[]}),L&&lt(),t.dispose()},ft=()=>{ve.clear(),G.setMessagesManually(G.getSnapshot().messages.map(e=>{let t=/* @__PURE__ */ 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(ge.get(i)===e.id&&!o(n))return n;let a=tt(e.id,r.applicationPartId??i,r.responseTargetId);return t.set(i,a),{...n,upstreamToolCallId:i,id:a,...n.name===`render_widget`?{widgetRenderId:r.widgetRenderId??H.get(e.id)?.renderIds?.get(tt(e.id,n.id))??n.id}:{}}});return t.size&&ve.set(e.id,t),{...e,parts:n}}))},pt=e=>{let t=l.thread?.id,n=M(`The conversation changed before this was sent.`);t&&(n?.phase===`failed`?f.set(t,n):f.delete(t),be.set(t,W)),R++,p=void 0,et=e,ie.abort(),ie=new AbortController,W=be.get(e??``)??/* @__PURE__ */ new Map,ve.clear(),ge.clear(),oe=[],H.clear(),se=/* @__PURE__ */ new WeakMap,U++,Be(),g({thread:void 0,messages:[],submission:void 0,error:void 0,sandbox:{files:[],commands:[]},sandboxStatus:void 0,usageLimitReached:void 0,pendingInteractions:[],serverToolTitles:{},unavailableMcpConnections:[],messagesCursor:void 0,olderMessagesLoading:!1}),ut()},mt=async(e,t=!1)=>{pt(e);let r=R;d=f.get(e),d&&g({submission:S(d)});try{if(L||lt(),await ne({client:G,selection:r}),r!==R)return;V&&dt(V,e)}catch(e){if(r!==R)return;t&&(n.threadId===void 0||n.threadId===`auto`)&&P(e)&&e.status===404?ht():Te(e)}},ht=()=>{pt(),L&&Ne(),V?dt(V,null):ae=!0},_t=(e=!1)=>{let t=n.threadId;if(t===void 0||t===`auto`){if(!V)return;t=dt(V)}t&&t!==`new`?t===l.thread?.id&&V?dt(V,t):mt(t,e):e||ht()},vt=async e=>{if(l.thread)return;let t=await ke();if(!k(e))throw new DOMException(`Send cancelled`,`AbortError`);let r=await qe(n.agentId?{agent_id:n.agentId}:{},t);if(!k(e))throw new DOMException(`Send cancelled`,`AbortError`);et=r.id,g({thread:Ee(r,!1)}),Ne(),V&&dt(V,r.id)},yt=async(e=!0)=>{if(!l.thread)return;let t=R;try{G.detach(),lt(),await ne({client:G,selection:t}),e&&t===R&&g({error:void 0})}catch(e){if(t!==R)return;P(e)&&e.status===404?ht():Te(e)}},bt=async()=>{if(!G.getHasOlderMessages()||l.olderMessagesLoading||l.history!==`idle`||d?.phase===`submitting`)return;let e=R;g({olderMessagesLoading:!0});try{await G.loadOlderMessages(),e===R&&nt&&st()}catch(t){e===R&&Te(t)}finally{e===R&&g({olderMessagesLoading:!1})}},xt=async e=>{let t=l.thread;if(!t||t.role!==`manager`)return!1;let n=R;try{let i=await r(t.id,{title:e,expected_version:t.version},await ke());if(n!==R)return!1;let a=Ee(i,t.hasMessages);return g({thread:a}),!0}catch(e){return n===R&&Te(e),!1}},St=async(e=l.thread)=>{if(!e||e.role!==`manager`)return!1;let t=R;try{return await gt(e.id,{expected_version:String(e.version)},await ke()),t===R&&l.thread?.id===e.id&&ht(),!0}catch(e){return t===R&&Te(e),!1}},Ct=async e=>{let t=R;if(h||d?.phase===`submitting`||G.getIsLoading()){Te(/* @__PURE__ */ Error(`Wait for this client's current request to finish before responding.`));return}let n=fe(N),r=Se(e.toolCallId),i=l.pendingInteractions.find(t=>t.toolCallId===e.toolCallId),a=!(`tool`in e)&&i&&(l.thread?.role===`manager`||n.status===`ready`&&i.targetTenantUserId===n.currentUser.user.id),o=`tool`in e&&e.tool===`ask_questionnaire`&&n.status===`ready`&&i?.targetTenantUserId===n.currentUser.user.id;if(l.thread?.role===`viewer`||!he.has(e.toolCallId)&&!o&&!a&&!W.has(r)){Te(/* @__PURE__ */ Error(`This tool call belongs to another session and cannot be executed here.`));return}if(!W.has(r)){if(a)W.set(r,{outcome:`unknown`,output:null});else if(`tool`in e){let t=e.output;W.set(r,{outcome:e.state===`output-error`?`failed`:`succeeded`,output:t??null})}}let s={kind:`tool-result`,client:G,selection:t};h=s;try{if(g({}),!y(s)||(ft(),!y(s)))return;if(i){if(s.client.stop(),await yt(!1),!y(s))return;await s.client.append({role:`tool`,toolCallId:e.toolCallId,content:JSON.stringify(W.get(Se(e.toolCallId)))})}else`tool`in e&&await s.client.addToolResult(e);y(s)&&await yt(!1)}finally{x(s)}},wt=e=>Ct({toolCallId:e}),Tt=async e=>{if(e!==d||e.phase!==`submitting`)return S(e);let t={kind:`submission`,submission:e,client:G,selection:R};h=t;try{if(await T(N),!await B(t)||(await vt(t),!k(t))||(e.callbacks?.onThreadReady?.(l.thread.id),!k(t))||(ft(),!await B(t))||(await t.client.sendMessage(e.content),!O(t)))return S(e);A(e,t.client.getError()),O(t)&&await yt(!1)}catch(n){if(!O(t))return S(e);let r=n instanceof Error?n:Error(String(n));r.name===`AbortError`?A(e):A(e,r)&&we(r)}finally{x(t)}return S(e)},Et=async(e,t)=>{let n=h||d?.phase===`submitting`||G.getIsLoading()?`Wait for this client's current request to finish before sending.`:l.history===`loading`?`Wait for this conversation to load before sending.`:l.history===`failed`?Kl:l.thread?.agentId===null?`This conversation’s agent is unavailable. Start a new conversation to continue.`:l.thread?.role===`viewer`?`You have read-only access to this conversation.`:d?.phase===`failed`?`The previous message’s acceptance is unconfirmed. Retry that message before sending different text, or start a new conversation.`:void 0;if(n)return{id:Re(),content:e,phase:`refused`,error:Error(n)};let r={id:Re(),content:e,phase:`submitting`,key:Re(),delivery:{state:`undispatched`},callbacks:t};d=r,g({submission:S(r),error:void 0,olderMessagesLoading:!1}),G.stop(),he.clear(),ft(),ge.clear(),g({activeToolCallIds:[]});let i=new Promise(e=>r.onRefused=e);return Promise.race([Tt(r),i.then(()=>S(r))])},Dt=async()=>{let e=d;if(!h&&!G.getIsLoading()&&e&&E(e,`submitting`))return g({error:void 0}),Tt(e)},Ot=()=>{let e=fe(N),t=l.auth;if(e.status===`ready`){let t=ce(e.currentUser);I!==void 0&&I!==t&&(M(`The account changed before this was sent.`),f.clear(),be.clear(),W.clear(),pt(),V=void 0),I=t;let r=JSON.stringify(Qe(n)),i=`astralbeam:thread:${n.apiUrl??`https://astralbeam.ai/api`}:${t}:session:${r}`;V!==i&&(V!==void 0&&pt(),V=i,ae?(dt(i,null),ae=!1):_t(!0)),Me!==t&&(Me=t,Ne())}g({auth:e}),e.status===`error`&&(t.status!==`error`||t.error!==e.error)&&n.streamCallbacks?.onError?.(e.error)},kt=()=>{if(L)return;L=!0;let e=ie.signal.aborted&&G.getIsHydrating();G.updateOptions({tools:Ke()}),ie.signal.aborted&&(ie=new AbortController),ee=me(N,Ot),Ot(),F=b(N),e?ut(G.getSnapshot().messages):lt()};return t||kt(),{start:kt,getState:()=>l,getOptions:()=>n,attachView:e=>{if(s)throw Error(`This chat session already has a view attached`);let t={options:e},n=()=>{G.updateOptions({tools:Ke()}),We(l.messages)};return Be(),s=t,n(),{update:e=>{if(s!==t)return;let r=t.options;t.options=e,(r.widgets!==e.widgets||r.onRenderWidget!==e.onRenderWidget)&&n()},dispose:()=>{s===t&&(Be(),s=void 0,n())}}},subscribe:e=>(a.add(e),()=>a.delete(e)),updateOptions:e=>{let t=n.agentId,r=n.apiUrl,a=n.threadId,o=Qe(n),{widgets:s,onRenderWidget:c}=n;n={...n,...e};let u=Qe(n)!==o;i=At(n.debug),_e(N,{apiUrl:n.apiUrl,fetchAstralBeamToken:n.fetchAstralBeamToken??{url:`/api/astralbeam/token`}}),N.debug=i,G.updateOptions({tools:Ke(),forwardedProps:Je()}),n.apiUrl===r?u?(ae=!1,l.thread&&n.threadId===l.thread.id||pt(),V=void 0,Ot()):n.threadId!==a&&_t():(M(`The chat service changed before this was sent.`),f.clear(),be.clear(),W.clear(),pt(),V=void 0,Ot()),(s!==n.widgets||c!==n.onRenderWidget)&&We(l.messages),L&&(n.agentId!==t||n.apiUrl!==r||u)&&Ne()},sendMessage:Et,retry:Dt,addToolResult:Ct,stop:()=>{te++;let e=d,t=h;e?.phase===`submitting`&&A(e),G.stop(),t&&x(t),e?.phase===`refused`&&e.onRefused?.()},retryAuthentication:()=>{T({...N,force:!0}).catch(()=>void 0)},reload:async()=>{let e=R;if(await yt(),e!==R||l.error)return;let t=/* @__PURE__ */ new Set;for(;e===R;){let e=l.pendingInteractions.find(e=>!t.has(e.sourceMessageId)&&W.has(Se(e.toolCallId)));if(!e||(t.add(e.sourceMessageId),await Ct({toolCallId:e.toolCallId}),l.error))return}},searchThreads:async(e=``,t,n)=>{let r=await ke(),i=await ye({q:e,page_size:50,...t?{page_after:t}:{}},{...r,signal:AbortSignal.any([r.signal,...n?[n]:[]])});return{items:i.items.map(e=>Ee(e)),page_after:i.page_after}},openThread:mt,renameThread:xt,deleteThread:St,refreshThread:()=>yt(),loadOlderMessages:bt,uploadAttachment:async({data:e,filename:t,mimeType:r})=>{let i=l.thread?l.thread.agentId:n.agentId,[a,o]=await Promise.all([e,ke(!1)]);return Ve({...i?{agentId:i}:{},type:r.startsWith(`image/`)?`image`:`document`,source:{type:`data`,value:a,mimeType:r},metadata:{filename:t}},o)},getThreadAttachment:async(e,t)=>{if(!e.threadId&&!t?.preview)throw Error(`A conversation ID is required to download files.`);return(await Pe({...e,delivery:`direct`},{...await ke(!!e.threadId||!t?.preview),headers:t?.preview?{"X-File-Preview":`true`}:{}})).blob()},getMcpCatalog:async()=>u(await ke(!1)),manageMcpConnection:async e=>{let t=await Wl(e,await ke(!1));return`id`in e?De(e.id):t&&`id`in t&&De(t.id),t},authorizeMcpConnection:async e=>{let t=await Gl(e,()=>ke(!1));De(t)},abandonToolCall:wt,reset:()=>{if(i?.(`status`,`conversation reset`),ht(),l.auth.status===`ready`){let e=JSON.stringify([I,Qe(n)]),t=n.apiUrl??`https://astralbeam.ai/api`;Z(t,e,``,``),Z(t,e,``,``,`sent`),Il({apiUrl:t,identity:e,threadId:``,update:()=>[]}).catch(e=>i?.(`error`,`Draft could not be cleared`,e))}s?.options.onReset()},dispose:()=>{M(`The chat closed before this was sent.`),h=void 0,p=void 0,nt?.(),nt=void 0,G.detach(),Be(),G.stop(),ie.abort(),R++,Ae++,Me=void 0,F?.(),ee?.(),D(N),L=!1,queueMicrotask(()=>{L||(G.dispose(),V=void 0,H.clear(),se=/* @__PURE__ */ new WeakMap)}),a.clear()}}}function Yl(e){if(e)return{onChunk:Zl(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 Xl(e){try{return JSON.parse(e)}catch{return e}}function Zl(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ 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 J.TEXT_MESSAGE_CONTENT:case J.TEXT_MESSAGE_CHUNK:r(a.messageId??`text`,a.delta??``);break;case J.TEXT_MESSAGE_END:e(`text`,i(a.messageId??`text`),{messageId:a.messageId});break;case J.REASONING_MESSAGE_CONTENT:case J.REASONING_MESSAGE_CHUNK:r(`reasoning:${a.messageId??`thinking`}`,a.delta??``);break;case J.REASONING_MESSAGE_END:e(`reasoning`,i(`reasoning:${a.messageId??`thinking`}`),{messageId:a.messageId});break;case J.TOOL_CALL_START:e(`tool`,`${a.toolCallName} call started`,t),n.set(a.toolCallId??``,{name:a.toolCallName??``,args:``});break;case J.TOOL_CALL_ARGS:{let e=n.get(a.toolCallId??``);e&&(e.args+=a.delta??``);break}case J.TOOL_CALL_END:{let t=n.get(a.toolCallId??``);n.delete(a.toolCallId??``),e(`tool`,`${t?.name??`tool`} input complete`,{toolCallId:a.toolCallId,input:Xl(t?.args??``)});break}case J.TOOL_CALL_RESULT:e(`tool`,`result for tool call ${a.toolCallId}`,{toolCallId:a.toolCallId,messageId:a.messageId,content:typeof a.content==`string`?Xl(a.content):a.content});break;case J.TEXT_MESSAGE_START:case J.REASONING_MESSAGE_START:break;case J.RUN_STARTED:e(`run`,`run ${a.runId} started`,t);break;case J.RUN_FINISHED:e(`run`,`run ${a.runId} finished`,t);break;case J.RUN_ERROR:e(`error`,`run failed: ${a.message}`,t);break;default:e(`stream`,a.type,t)}}}var Q=/* @__PURE__ */ Yn(cn(),1);const Ql=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M200,112H56l72-72Z`,opacity:`0.2`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),$l=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M228,48V96a12,12,0,0,1-12,12H168a12,12,0,0,1,0-24h19l-7.8-7.8a75.55,75.55,0,0,0-53.32-22.26h-.43A75.49,75.49,0,0,0,72.39,75.57,12,12,0,1,1,55.61,58.41a99.38,99.38,0,0,1,69.87-28.47H126A99.42,99.42,0,0,1,196.2,59.23L204,67V48a12,12,0,0,1,24,0ZM183.61,180.43a75.49,75.49,0,0,1-53.09,21.63h-.43A75.55,75.55,0,0,1,76.77,179.8L69,172H88a12,12,0,0,0,0-24H40a12,12,0,0,0-12,12v48a12,12,0,0,0,24,0V189l7.8,7.8A99.42,99.42,0,0,0,130,226.06h.56a99.38,99.38,0,0,0,69.87-28.47,12,12,0,0,0-16.78-17.16Z`}))],[`duotone`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),/* @__PURE__ */ Q.createElement(`path`,{d:`M224,48V96a8,8,0,0,1-8,8H168a8,8,0,0,1,0-16h28.69L182.06,73.37a79.56,79.56,0,0,0-56.13-23.43h-.45A79.52,79.52,0,0,0,69.59,72.71,8,8,0,0,1,58.41,61.27a96,96,0,0,1,135,.79L208,76.69V48a8,8,0,0,1,16,0ZM186.41,183.29a80,80,0,0,1-112.47-.66L59.31,168H88a8,8,0,0,0,0-16H40a8,8,0,0,0-8,8v48a8,8,0,0,0,16,0V179.31l14.63,14.63A95.43,95.43,0,0,0,130,222.06h.53a95.36,95.36,0,0,0,67.07-27.33,8,8,0,0,0-11.18-11.44Z`}))],[`fill`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M224,48V96a8,8,0,0,1-8,8H168a8,8,0,0,1-5.66-13.66L180.65,72a79.48,79.48,0,0,0-54.72-22.09h-.45A79.52,79.52,0,0,0,69.59,72.71,8,8,0,0,1,58.41,61.27,96,96,0,0,1,192,60.7l18.36-18.36A8,8,0,0,1,224,48ZM186.41,183.29A80,80,0,0,1,75.35,184l18.31-18.31A8,8,0,0,0,88,152H40a8,8,0,0,0-8,8v48a8,8,0,0,0,13.66,5.66L64,195.3a95.42,95.42,0,0,0,66,26.76h.53a95.36,95.36,0,0,0,67.07-27.33,8,8,0,0,0-11.18-11.44Z`}))],[`light`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M222,48V96a6,6,0,0,1-6,6H168a6,6,0,0,1,0-12h33.52L183.47,72a81.51,81.51,0,0,0-57.53-24h-.46A81.5,81.5,0,0,0,68.19,71.28a6,6,0,1,1-8.38-8.58,93.38,93.38,0,0,1,65.67-26.76H126a93.45,93.45,0,0,1,66,27.53l18,18V48a6,6,0,0,1,12,0ZM187.81,184.72a81.5,81.5,0,0,1-57.29,23.34h-.46a81.51,81.51,0,0,1-57.53-24L54.48,166H88a6,6,0,0,0,0-12H40a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V174.48l18,18.05a93.45,93.45,0,0,0,66,27.53h.52a93.38,93.38,0,0,0,65.67-26.76,6,6,0,1,0-8.38-8.58Z`}))],[`regular`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M224,48V96a8,8,0,0,1-8,8H168a8,8,0,0,1,0-16h28.69L182.06,73.37a79.56,79.56,0,0,0-56.13-23.43h-.45A79.52,79.52,0,0,0,69.59,72.71,8,8,0,0,1,58.41,61.27a96,96,0,0,1,135,.79L208,76.69V48a8,8,0,0,1,16,0ZM186.41,183.29a80,80,0,0,1-112.47-.66L59.31,168H88a8,8,0,0,0,0-16H40a8,8,0,0,0-8,8v48a8,8,0,0,0,16,0V179.31l14.63,14.63A95.43,95.43,0,0,0,130,222.06h.53a95.36,95.36,0,0,0,67.07-27.33,8,8,0,0,0-11.18-11.44Z`}))],[`thin`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M220,48V96a4,4,0,0,1-4,4H168a4,4,0,0,1,0-8h38.34L184.89,70.54A84,84,0,0,0,66.8,69.85a4,4,0,1,1-5.6-5.72,92,92,0,0,1,129.34.76L212,86.34V48a4,4,0,0,1,8,0ZM189.2,186.15a83.44,83.44,0,0,1-58.68,23.91h-.47a83.52,83.52,0,0,1-58.94-24.6L49.66,164H88a4,4,0,0,0,0-8H40a4,4,0,0,0-4,4v48a4,4,0,0,0,8,0V169.66l21.46,21.45A91.43,91.43,0,0,0,130,218.06h.51a91.45,91.45,0,0,0,64.28-26.19,4,4,0,1,0-5.6-5.72Z`}))]]),eu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M208,160H48l80-80Z`,opacity:`0.2`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),tu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),nu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),ru=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),iu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M216,48V208H40V48A16,16,0,0,1,56,32H200A16,16,0,0,1,216,48Z`,opacity:`0.2`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),au=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M251,123.13c-.37-.81-9.13-20.26-28.48-39.61C196.63,57.67,164,44,128,44S59.37,57.67,33.51,83.52C14.16,102.87,5.4,122.32,5,123.13a12.08,12.08,0,0,0,0,9.75c.37.82,9.13,20.26,28.49,39.61C59.37,198.34,92,212,128,212s68.63-13.66,94.48-39.51c19.36-19.35,28.12-38.79,28.49-39.61A12.08,12.08,0,0,0,251,123.13Zm-46.06,33C183.47,177.27,157.59,188,128,188s-55.47-10.73-76.91-31.88A130.36,130.36,0,0,1,29.52,128,130.45,130.45,0,0,1,51.09,99.89C72.54,78.73,98.41,68,128,68s55.46,10.73,76.91,31.89A130.36,130.36,0,0,1,226.48,128,130.45,130.45,0,0,1,204.91,156.12ZM128,84a44,44,0,1,0,44,44A44.05,44.05,0,0,0,128,84Zm0,64a20,20,0,1,1,20-20A20,20,0,0,1,128,148Z`}))],[`duotone`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M128,56C48,56,16,128,16,128s32,72,112,72,112-72,112-72S208,56,128,56Zm0,112a40,40,0,1,1,40-40A40,40,0,0,1,128,168Z`,opacity:`0.2`}),/* @__PURE__ */ Q.createElement(`path`,{d:`M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z`}))],[`fill`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,168a40,40,0,1,1,40-40A40,40,0,0,1,128,168Z`}))],[`light`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M245.48,125.57c-.34-.78-8.66-19.23-27.24-37.81C201,70.54,171.38,50,128,50S55,70.54,37.76,87.76c-18.58,18.58-26.9,37-27.24,37.81a6,6,0,0,0,0,4.88c.34.77,8.66,19.22,27.24,37.8C55,185.47,84.62,206,128,206s73-20.53,90.24-37.75c18.58-18.58,26.9-37,27.24-37.8A6,6,0,0,0,245.48,125.57ZM128,194c-31.38,0-58.78-11.42-81.45-33.93A134.77,134.77,0,0,1,22.69,128,134.56,134.56,0,0,1,46.55,95.94C69.22,73.42,96.62,62,128,62s58.78,11.42,81.45,33.94A134.56,134.56,0,0,1,233.31,128C226.94,140.21,195,194,128,194Zm0-112a46,46,0,1,0,46,46A46.06,46.06,0,0,0,128,82Zm0,80a34,34,0,1,1,34-34A34,34,0,0,1,128,162Z`}))],[`regular`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z`}))],[`thin`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M243.66,126.38c-.34-.76-8.52-18.89-26.83-37.2C199.87,72.22,170.7,52,128,52S56.13,72.22,39.17,89.18c-18.31,18.31-26.49,36.44-26.83,37.2a4.08,4.08,0,0,0,0,3.25c.34.77,8.52,18.89,26.83,37.2,17,17,46.14,37.17,88.83,37.17s71.87-20.21,88.83-37.17c18.31-18.31,26.49-36.43,26.83-37.2A4.08,4.08,0,0,0,243.66,126.38Zm-32.7,35c-23.07,23-51,34.62-83,34.62s-59.89-11.65-83-34.62A135.71,135.71,0,0,1,20.44,128,135.69,135.69,0,0,1,45,94.62C68.11,71.65,96,60,128,60s59.89,11.65,83,34.62A135.79,135.79,0,0,1,235.56,128,135.71,135.71,0,0,1,211,161.38ZM128,84a44,44,0,1,0,44,44A44.05,44.05,0,0,0,128,84Zm0,80a36,36,0,1,1,36-36A36,36,0,0,1,128,164Z`}))]]),ou=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M208,88H152V32Z`,opacity:`0.2`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),su=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M208,88H152V32Z`,opacity:`0.2`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),cu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M200,88l-72,72H96V128l72-72Z`,opacity:`0.2`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),lu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),uu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),du=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M244,128a12,12,0,0,1-12,12H207.42l-36.69,73.37A12,12,0,0,1,160,220h-.6a12,12,0,0,1-10.61-7.72L95,71.15,66.92,133A12,12,0,0,1,56,140H24a12,12,0,0,1,0-24H48.27L85.08,35a12,12,0,0,1,22.13.7l54.28,142.46,27.78-55.56A12,12,0,0,1,200,116h32A12,12,0,0,1,244,128Z`}))],[`duotone`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M96,40l33.52,88H56Zm104,88H129.52L160,208Z`,opacity:`0.2`}),/* @__PURE__ */ Q.createElement(`path`,{d:`M240,128a8,8,0,0,1-8,8H204.94l-37.78,75.58A8,8,0,0,1,160,216h-.4a8,8,0,0,1-7.08-5.14L95.35,60.76,63.28,131.31A8,8,0,0,1,56,136H24a8,8,0,0,1,0-16H50.85L88.72,36.69a8,8,0,0,1,14.76.46l57.51,151,31.85-63.71A8,8,0,0,1,200,120h32A8,8,0,0,1,240,128Z`}))],[`fill`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M216,40H40A16,16,0,0,0,24,56V200a16,16,0,0,0,16,16H216a16,16,0,0,0,16-16V56A16,16,0,0,0,216,40Zm-8,96H188.64L159,188a8,8,0,0,1-6.95,4h-.46a8,8,0,0,1-6.89-4.84L103,89.92,79,132a8,8,0,0,1-7,4H48a8,8,0,0,1,0-16H67.36L97.05,68a8,8,0,0,1,14.3.82L153,166.08l24-42.05a8,8,0,0,1,6.95-4h24a8,8,0,0,1,0,16Z`}))],[`light`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M238,128a6,6,0,0,1-6,6H203.71l-38.34,76.68A6,6,0,0,1,160,214h-.3a6,6,0,0,1-5.31-3.85L95.51,55.57,61.46,130.48A6,6,0,0,1,56,134H24a6,6,0,0,1,0-12H52.14l38.4-84.48a6,6,0,0,1,11.07.34L160.74,193.1l33.89-67.78A6,6,0,0,1,200,122h32A6,6,0,0,1,238,128Z`}))],[`regular`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M240,128a8,8,0,0,1-8,8H204.94l-37.78,75.58A8,8,0,0,1,160,216h-.4a8,8,0,0,1-7.08-5.14L95.35,60.76,63.28,131.31A8,8,0,0,1,56,136H24a8,8,0,0,1,0-16H50.85L88.72,36.69a8,8,0,0,1,14.76.46l57.51,151,31.85-63.71A8,8,0,0,1,200,120h32A8,8,0,0,1,240,128Z`}))],[`thin`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M236,128a4,4,0,0,1-4,4H202.47l-38.89,77.79A4,4,0,0,1,160,212h-.2a4,4,0,0,1-3.54-2.58l-60.59-159-36,79.28A4,4,0,0,1,56,132H24a4,4,0,0,1,0-8H53.42L92.36,38.35a4,4,0,0,1,7.38.23L160.5,198.06l35.92-71.85A4,4,0,0,1,200,124h32A4,4,0,0,1,236,128Z`}))]]),fu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M140,32V64a12,12,0,0,1-24,0V32a12,12,0,0,1,24,0Zm84,84H192a12,12,0,0,0,0,24h32a12,12,0,0,0,0-24Zm-42.26,48.77a12,12,0,1,0-17,17l22.63,22.63a12,12,0,0,0,17-17ZM128,180a12,12,0,0,0-12,12v32a12,12,0,0,0,24,0V192A12,12,0,0,0,128,180ZM74.26,164.77,51.63,187.4a12,12,0,0,0,17,17l22.63-22.63a12,12,0,1,0-17-17ZM76,128a12,12,0,0,0-12-12H32a12,12,0,0,0,0,24H64A12,12,0,0,0,76,128ZM68.6,51.63a12,12,0,1,0-17,17L74.26,91.23a12,12,0,0,0,17-17Z`}))],[`duotone`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z`,opacity:`0.2`}),/* @__PURE__ */ Q.createElement(`path`,{d:`M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm88,88H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z`}))],[`fill`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24ZM48,136a8,8,0,0,1,0-16H72a8,8,0,0,1,0,16Zm46.06,37.25-17,17a8,8,0,0,1-11.32-11.32l17-17a8,8,0,0,1,11.31,11.31Zm0-79.19a8,8,0,0,1-11.31,0l-17-17A8,8,0,0,1,77.09,65.77l17,17A8,8,0,0,1,94.06,94.06ZM136,208a8,8,0,0,1-16,0V184a8,8,0,0,1,16,0Zm0-136a8,8,0,0,1-16,0V48a8,8,0,0,1,16,0Zm54.23,118.23a8,8,0,0,1-11.32,0l-17-17a8,8,0,0,1,11.31-11.31l17,17A8,8,0,0,1,190.23,190.23ZM208,136H184a8,8,0,0,1,0-16h24a8,8,0,0,1,0,16Z`}))],[`light`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M134,32V64a6,6,0,0,1-12,0V32a6,6,0,0,1,12,0Zm90,90H192a6,6,0,0,0,0,12h32a6,6,0,0,0,0-12Zm-46.5,47A6,6,0,0,0,169,177.5l22.63,22.62a6,6,0,0,0,8.48-8.48ZM128,186a6,6,0,0,0-6,6v32a6,6,0,0,0,12,0V192A6,6,0,0,0,128,186ZM78.5,169,55.88,191.64a6,6,0,1,0,8.48,8.48L87,177.5A6,6,0,1,0,78.5,169ZM70,128a6,6,0,0,0-6-6H32a6,6,0,0,0,0,12H64A6,6,0,0,0,70,128ZM64.36,55.88a6,6,0,0,0-8.48,8.48L78.5,87A6,6,0,1,0,87,78.5Z`}))],[`regular`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M136,32V64a8,8,0,0,1-16,0V32a8,8,0,0,1,16,0Zm88,88H192a8,8,0,0,0,0,16h32a8,8,0,0,0,0-16Zm-45.09,47.6a8,8,0,0,0-11.31,11.31l22.62,22.63a8,8,0,0,0,11.32-11.32ZM128,184a8,8,0,0,0-8,8v32a8,8,0,0,0,16,0V192A8,8,0,0,0,128,184ZM77.09,167.6,54.46,190.22a8,8,0,0,0,11.32,11.32L88.4,178.91A8,8,0,0,0,77.09,167.6ZM72,128a8,8,0,0,0-8-8H32a8,8,0,0,0,0,16H64A8,8,0,0,0,72,128ZM65.78,54.46A8,8,0,0,0,54.46,65.78L77.09,88.4A8,8,0,0,0,88.4,77.09Z`}))],[`thin`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ Q.createElement(`path`,{d:`M132,32V64a4,4,0,0,1-8,0V32a4,4,0,0,1,8,0Zm92,92H192a4,4,0,0,0,0,8h32a4,4,0,0,0,0-8Zm-47.92,46.43a4,4,0,1,0-5.65,5.65l22.62,22.63a4,4,0,0,0,5.66-5.66ZM128,188a4,4,0,0,0-4,4v32a4,4,0,0,0,8,0V192A4,4,0,0,0,128,188ZM79.92,170.43,57.29,193.05A4,4,0,0,0,63,198.71l22.62-22.63a4,4,0,1,0-5.65-5.65ZM68,128a4,4,0,0,0-4-4H32a4,4,0,0,0,0,8H64A4,4,0,0,0,68,128ZM63,57.29A4,4,0,0,0,57.29,63L79.92,85.57a4,4,0,1,0,5.65-5.65Z`}))]]),pu=/* @__PURE__ */ new Map([[`bold`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}),/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`,/* @__PURE__ */ Q.createElement(Q.Fragment,null,/* @__PURE__ */ 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`}))]]),mu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:Ql}));mu.displayName=`ArrowUpIcon`;const hu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:$l}));hu.displayName=`ArrowsClockwiseIcon`;const gu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:eu}));gu.displayName=`CaretUpIcon`;const _u=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:tu}));_u.displayName=`ClockCounterClockwiseIcon`;const vu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:nu}));vu.displayName=`CubeIcon`;const yu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:ru}));yu.displayName=`DotsThreeIcon`;const bu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:iu}));bu.displayName=`DownloadSimpleIcon`;const xu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:au}));xu.displayName=`EyeIcon`;const Su=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:ou}));Su.displayName=`FileCodeIcon`;const Cu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:su}));Cu.displayName=`FileCsvIcon`;const wu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:cu}));wu.displayName=`NotePencilIcon`;const Tu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:lu}));Tu.displayName=`PaperclipIcon`;const Eu=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:uu}));Eu.displayName=`PencilSimpleIcon`;const Du=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:du}));Du.displayName=`PulseIcon`;const Ou=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:fu}));Ou.displayName=`SpinnerGapIcon`;const ku=Q.forwardRef((e,t)=>/* @__PURE__ */ Q.createElement(hn,{ref:t,...e,weights:pu}));ku.displayName=`StopIcon`;var Au=Ut(),$=dr();const ju={reading:`uploading`,ready:`done`,error:`error`};function Mu({attachments:t,onRemove:n}){let r=(0,Q.useRef)(null),i=t.at(-1)?.id;(0,Q.useEffect)(()=>{let e=r.current;e&&(e.scrollLeft=e.scrollWidth)},[i]);let a=t.filter(e=>e.status===`error`);return t.length===0?null:/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`w-full min-w-0`,children:[a.length>0&&/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 text-sm text-destructive`,children:[/* @__PURE__ */ (0,$.jsxs)(`span`,{children:[a.length,` `,a.length===1?`file could`:`files could`,` not be attached.`]}),/* @__PURE__ */ (0,$.jsx)(K,{type:`button`,variant:`ghost`,size:`icon-sm`,tooltip:`Review files`,onClick:()=>{let e=r.current?.querySelector(`[role="alert"]`);e?.scrollIntoView({block:`nearest`,inline:`nearest`}),e?.querySelector(`button`)?.focus()},children:/* @__PURE__ */ (0,$.jsx)(xu,{})})]}),/* @__PURE__ */ (0,$.jsx)(ze,{ref:r,className:`w-full`,children:t.map(t=>/* @__PURE__ */ (0,$.jsxs)(Ae,{size:`sm`,state:ju[t.status],role:t.status===`error`?`alert`:void 0,children:[/* @__PURE__ */ (0,$.jsx)(e,{id:t.fileId,title:t.name,kind:t.kind,mimeType:t.mimeType}),/* @__PURE__ */ (0,$.jsxs)($e,{children:[/* @__PURE__ */ (0,$.jsx)(Se,{title:t.name,children:t.name}),/* @__PURE__ */ (0,$.jsx)(lt,{children:t.error??Ie(t.size)})]}),/* @__PURE__ */ (0,$.jsx)(mt,{children:/* @__PURE__ */ (0,$.jsx)(K,{"data-slot":`attachment-action`,type:`button`,variant:`ghost`,size:`icon-xs`,"aria-label":`Remove ${t.name}`,tooltip:`Remove attachment`,onClick:()=>n(t.id),children:/* @__PURE__ */ (0,$.jsx)(L,{})})})]},t.id))})]})}function Nu({title:e,actionsSlot:t,draft:n,onDraftChange:r,onSend:i,onStop:a,onRetry:o,retryLabel:s,showError:c,error:u,streamBusy:d,isBusy:f,threadLoading:m,authPending:h,authError:_,onAuthRetry:v,attachments:y,attachmentLimits:b,onAddFiles:x,onRemoveAttachment:S}){let C=(0,Q.useId)(),w=(0,Q.useRef)(null),[T,E]=(0,Q.useState)(!1),D=h||_!==void 0||m,O=y.some(e=>e.status===`reading`),k=y.some(e=>e.status===`ready`),A=y.filter(e=>e.status!==`error`).length>=b.maxFiles,j=b.enabled&&!D,M=f||D||O||n.trim().length===0&&!k,N=e=>{j&&e&&e.length!==0&&x([...e])},F=e=>j&&(e?.types.includes(`Files`)??!1);return/* @__PURE__ */ (0,$.jsxs)(`form`,{className:`w-full`,onSubmit:e=>{e.preventDefault(),M||i()},onDragOver:e=>{F(e.dataTransfer)&&(e.preventDefault(),E(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||E(!1)},onDrop:e=>{F(e.dataTransfer)&&(e.preventDefault(),E(!1),N(e.dataTransfer.files))},children:[c&&/* @__PURE__ */ (0,$.jsxs)(St,{variant:`destructive`,className:`mb-1.5 flex items-center gap-2 border-destructive/30 bg-destructive/5 py-1 has-data-[slot=alert-action]:pe-2.5`,children:[/* @__PURE__ */ (0,$.jsxs)(p,{className:`min-w-0 flex-1 text-xs text-pretty wrap-anywhere`,children:[/* @__PURE__ */ (0,$.jsx)(`div`,{children:Me(u)}),P(u)&&u.body?.reference&&/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`mt-0.5 text-muted-foreground`,children:[`Support reference: `,u.body.reference]})]}),o&&/* @__PURE__ */ (0,$.jsx)(U,{className:`static shrink-0`,children:/* @__PURE__ */ (0,$.jsx)(K,{type:`button`,variant:`outline`,size:`icon-sm`,tooltip:s,onClick:o,children:/* @__PURE__ */ (0,$.jsx)(g,{})})})]}),_&&/* @__PURE__ */ (0,$.jsxs)(St,{variant:`destructive`,className:`mb-1.5 flex items-center gap-2 border-destructive/30 bg-destructive/5 py-1 has-data-[slot=alert-action]:pe-2.5`,children:[/* @__PURE__ */ (0,$.jsx)(p,{className:`min-w-0 flex-1 text-xs text-pretty wrap-anywhere`,children: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.`}),v&&/* @__PURE__ */ (0,$.jsx)(U,{className:`static shrink-0`,children:/* @__PURE__ */ (0,$.jsx)(K,{type:`button`,variant:`outline`,size:`icon-sm`,tooltip:`Retry`,onClick:v,children:/* @__PURE__ */ (0,$.jsx)(g,{})})})]}),b.enabled&&/* @__PURE__ */ (0,$.jsx)(`input`,{ref:w,type:`file`,multiple:!0,className:`sr-only`,accept:ft(b),onChange:e=>{N(e.currentTarget.files),e.currentTarget.value=``}}),/* @__PURE__ */ (0,$.jsxs)(wt,{className:Qt(`cursor-text`,T&&`border-ring ring-3 ring-ring/50`),children:[y.length>0&&/* @__PURE__ */ (0,$.jsx)(ae,{align:`block-start`,className:`py-1`,children:/* @__PURE__ */ (0,$.jsx)(Mu,{attachments:y,onRemove:S})}),/* @__PURE__ */ (0,$.jsx)(l,{"aria-label":`Message`,"aria-describedby":C,className:`max-h-24 min-h-8 py-1.5 any-pointer-coarse:text-base`,placeholder:h?`Verifying your session…`:m?`Loading conversation…`:T?`Drop files to attach…`:`Message ${e}…`,disabled:D,value:n,onChange:e=>r(e.currentTarget.value),onPaste:e=>{j&&e.clipboardData.files.length!==0&&(e.preventDefault(),N(e.clipboardData.files))},onKeyDown:e=>{e.nativeEvent.isComposing||e.nativeEvent.keyCode===229||e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),M||i())}}),/* @__PURE__ */ (0,$.jsxs)(ae,{align:`block-end`,className:`pt-0 pb-1`,children:[b.enabled&&/* @__PURE__ */ (0,$.jsx)(K,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":`Attach files`,tooltip:A?`Up to ${b.maxFiles} files per message`:`Attach files`,disabled:D||A,onClick:()=>w.current?.click(),children:/* @__PURE__ */ (0,$.jsx)(Tu,{})}),t&&/* @__PURE__ */ (0,$.jsx)(`slot`,{name:t}),d?/* @__PURE__ */ (0,$.jsx)(K,{type:`button`,variant:`default`,size:`icon`,className:`ml-auto`,tooltip:`Stop`,onClick:e=>{e.detail<2&&a()},children:/* @__PURE__ */ (0,$.jsx)(ku,{})}):/* @__PURE__ */ (0,$.jsx)(K,{type:`submit`,variant:`default`,size:`icon`,className:`ml-auto`,tooltip:`Send`,disabled:M,children:/* @__PURE__ */ (0,$.jsx)(mu,{})})]})]}),/* @__PURE__ */ (0,$.jsxs)(`p`,{className:`mt-1 text-center text-xs text-muted-foreground`,children:[/* @__PURE__ */ (0,$.jsx)(`span`,{id:C,children:`Enter to send, Shift+Enter for a new line.`}),` AI can make mistakes.`]})]})}const Pu=/*#__PURE__*/ Q.forwardRef(function(e,t){let{className:n,render:r,orientation:i=`horizontal`,style:a,...o}=e;return Cn(`div`,e,{state:{orientation:i},ref:t,props:[{role:`separator`,"aria-orientation":i},o]})});function Fu({sizing:e,panelId:t}){return e.enabled?/* @__PURE__ */ (0,$.jsx)(Pu,{orientation:`vertical`,tabIndex:0,"aria-label":`Resize chat`,"aria-controls":t,"aria-valuemin":e.minimum,"aria-valuemax":e.maximum,"aria-valuenow":e.width,"aria-valuetext":`${e.width} pixels`,className:`absolute inset-y-0 start-0 z-20 w-2 touch-none cursor-col-resize border-s border-transparent hover:border-primary/20 focus-visible:[outline:2px_solid_var(--ring)] focus-visible:-outline-offset-2 any-pointer-coarse:inset-y-14 any-pointer-coarse:w-11`,onPointerDown:e.onPointerDown,onPointerMove:e.onPointerMove,onPointerUp:e.onPointerUp,onPointerCancel:e.cancelDrag,onLostPointerCapture:e.cancelDrag,onKeyDown:e.onKeyDown}):null}function Iu(e){try{let t=JSON.parse(localStorage.getItem(e)??`null`);if(t&&typeof t==`object`&&`width`in t&&typeof t.width==`number`&&Number.isFinite(t.width)&&t.width>0)return t.width}catch{}return null}function Lu(e,t,n,r){e.style.setProperty(`width`,`${t}px`),e.setAttribute(`data-astralbeam-full-width`,String(t>=n)),r?.setAttribute(`aria-valuenow`,String(t)),r?.setAttribute(`aria-valuetext`,`${t} pixels`)}function Ru(e,t){let n=`astralbeam:chat-size:v1${t.id?`:component:${encodeURIComponent(t.id)}`:``}${e.agentId?`:agent:${encodeURIComponent(e.agentId)}`:``}`,[r,i]=(0,Q.useState)(()=>({key:n,value:Iu(n)}));r.key!==n&&i({key:n,value:Iu(n)});let a=r.key===n?r.value:null,[o,s]=(0,Q.useState)({maximum:0,fallback:null,mobile:!1}),c=(0,Q.useRef)(null),{resizeContainer:l,onClose:u,defaultWidth:d}=e,f=!!u;(0,Q.useLayoutEffect)(()=>{let e=l?.()??t.parentElement;if(!e)return;let n=matchMedia(`(max-width: 900px)`),r=()=>{let r=getComputedStyle(e),i=f&&n.matches?window.innerWidth:e.clientWidth-parseFloat(r.paddingLeft)-parseFloat(r.paddingRight),a=o.fallback??(t.getClientRects().length>0&&(t.offsetWidth>0||d!==void 0)?t.offsetWidth:null);i<=0||s(e=>{let t={maximum:i,fallback:e.fallback??a,mobile:f&&n.matches};return t.maximum===e.maximum&&t.fallback===e.fallback&&t.mobile===e.mobile?e:t})};r();let i=new ResizeObserver(r);return i.observe(e),o.fallback===null&&i.observe(t),n.addEventListener(`change`,r),()=>{i.disconnect(),n.removeEventListener(`change`,r)}},[t,l,f,d,o.fallback]);let p=Math.floor(o.maximum),m=Math.min(320,p),h=d===`100%`?p:d&&Number.isFinite(d)&&d>0?d:o.fallback??0,g=a??h,_=e=>Math.round(Math.min(p,Math.max(m,e))),v=o.mobile?p:_(g),y=e.resizable!==!1&&!o.mobile&&p>m,b=()=>{let e=c.current;e&&(c.current=null,Lu(t,v,p,e.element),e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId))};(0,Q.useLayoutEffect)(()=>{let e=t.style.getPropertyValue(`width`),n=t.style.getPropertyPriority(`width`),r=t.style.boxSizing,i=t.getAttribute(`data-astralbeam-full-width`);return t.style.setProperty(`box-sizing`,`border-box`),()=>{let a=c.current;c.current=null,a?.element.hasPointerCapture(a.pointerId)&&a.element.releasePointerCapture(a.pointerId),t.style.setProperty(`width`,e,n),t.style.setProperty(`box-sizing`,r),i===null?t.removeAttribute(`data-astralbeam-full-width`):t.setAttribute(`data-astralbeam-full-width`,i)}},[t]),(0,Q.useLayoutEffect)(()=>{let e=c.current;e&&(!y||e.key!==n)&&(c.current=null,e.element.hasPointerCapture(e.pointerId)&&e.element.releasePointerCapture(e.pointerId));let r=c.current?Math.round(Math.min(p,Math.max(m,c.current.next))):v;p>0&&o.fallback!==null&&Lu(t,r,p,e?.element)},[t,v,m,p,o.fallback,y,n]);let x=e=>{if(!y||!Number.isFinite(e))return;let t=_(e),r=t===_(h)?null:t;if(t!==v||r===null&&a!==null){i({key:n,value:r});try{r===null?localStorage.removeItem(n):localStorage.setItem(n,JSON.stringify({width:r}))}catch{}}};return{enabled:y,width:v,minimum:m,maximum:p,onPointerDown:e=>{y&&e.isPrimary&&e.button===0&&(e.preventDefault(),e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId),c.current={element:e.currentTarget,key:n,pointerId:e.pointerId,x:e.clientX,width:v,next:v,direction:getComputedStyle(t).direction===`rtl`?1:-1,scale:t.getBoundingClientRect().width/t.offsetWidth})},onPointerMove:e=>{let n=c.current;n&&n.pointerId===e.pointerId&&(n.next=n.width+(e.clientX-n.x)*n.direction/n.scale,Lu(t,_(n.next),p,n.element))},onPointerUp:e=>{let t=c.current;t&&t.pointerId===e.pointerId&&(c.current=null,e.currentTarget.releasePointerCapture(e.pointerId),t.next!==t.width&&x(t.next))},cancelDrag:b,onKeyDown:e=>{let n=getComputedStyle(t).direction===`rtl`?1:-1,r=e.shiftKey?50:10;if(e.key===`ArrowLeft`)x(v-r*n);else if(e.key===`ArrowRight`)x(v+r*n);else if(e.key===`Home`)x(m);else if(e.key===`End`)x(p);else if(e.key===`Escape`&&c.current)b();else return;e.preventDefault()}}}function zu({store:e,parentContext:t,isDrawer:n}){let r=e.useState(`open`),i=e.useState(`mounted`),a=e.useState(`disablePointerDismissal`),o=e.useState(`modal`),s=e.useState(`popupElement`),c=e.useState(`floatingRootContext`),[l,u]=Q.useState(0),[d,f]=Q.useState(0),p=l===0,m=ln(c,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?`intentional`:{mouse:o===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}},outsidePress(t){if(!e.context.outsidePressEnabledRef.current||`button`in t&&t.button!==0)return!1;if(`touches`in t){if(t.type===`touchend`){if(t.changedTouches.length!==1||t.touches.length!==0)return!1}else if(t.touches.length!==1)return!1}let n=sn(t);if(p&&!a){if(o){let t=e.context.internalBackdropRef.current,r=e.context.backdropRef.current;return t||r?t===n||r===n||Bt(n,s)&&!n?.hasAttribute(`data-base-ui-portal`):!0}return!0}return!1},escapeKey:p});return O(r&&o===!0,s),e.useContextCallback(`onNestedDialogOpen`,(t,n)=>{(e.select(`open`)||e.select(`mounted`))&&(u(t),f(n))}),Rn(()=>{!r&&!i&&(u(0),f(0))},[r,i]),Rn(()=>(t?.onNestedDialogOpen&&r&&t.onNestedDialogOpen(l+1,d+ +!!n),()=>{t?.onNestedDialogOpen&&r&&t.onNestedDialogOpen(0,0)}),[n,r,l,d,t]),on(e,{activeTriggerProps:m.reference,inactiveTriggerProps:m.trigger,popupProps:m.floating,nestedOpenDialogCount:l,nestedOpenDrawerCount:d}),null}const Bu=/*#__PURE__*/ Q.createContext(void 0);function Vu(e){let t=Q.useContext(Bu);if(!e&&t===void 0)throw Error(er(27));return t}const Hu={...Un,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role};var Uu=class extends Tn{constructor(e,t,n){let r=new kr,i=Wu(e,r,t,n);super(i,Gu(r),Hu)}setOpen=(e,t)=>{t.preventUnmountOnClose=()=>{this.set(`preventUnmountingOnClose`,!0)},!e&&t.trigger==null&&this.state.activeTriggerId!=null&&(t.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(e,t),t.isCanceled||(this.state.floatingRootContext.dispatchOpenChange(e,t),this.update(pn(this.state,e,t.trigger)))}};function Wu(e,t,n,r=!1){return{...nr(t,n,r),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:`dialog`,...e}}function Gu(e){return{popupRef:/*#__PURE__*/ Q.createRef(),backdropRef:/*#__PURE__*/ Q.createRef(),internalBackdropRef:/*#__PURE__*/ Q.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function Ku(e,t){let{children:n,open:r,defaultOpen:i=!1,onOpenChange:a,onOpenChangeComplete:o,disablePointerDismissal:s=!1,modal:c=!0,actionsRef:l,handle:u,triggerId:d,defaultTriggerId:f=null}=t,p=e===`drawer`,m=e===`alert-dialog`,h=m?!0:c,g=m||s,_=m?`alertdialog`:`dialog`,v=Vu(!0),y={modal:h,disablePointerDismissal:g,nested:v!=null,role:_},b=Zn((e,t)=>new Uu({open:i,openProp:r,activeTriggerId:f,triggerIdProp:d,...y},e,t),!0);b.useControlledProp(`openProp`,r),b.useControlledProp(`triggerIdProp`,d),b.useSyncedValues(y),b.useContextCallback(`onOpenChange`,a),b.useContextCallback(`onOpenChangeComplete`,o);let x=b.useState(`open`),S=b.useState(`mounted`),C=b.useState(`payload`);Nt(b,x),Ht(b);let{forceUnmount:w}=zt(x,b);Q.useImperativeHandle(l,()=>({unmount:w,close:()=>b.setOpen(!1,gn(tr))}),[w,b]);let T=x||S||u!=null;return/*#__PURE__*/ (0,$.jsxs)(Bu.Provider,{value:b,children:[u&&/*#__PURE__*/ (0,$.jsx)(Er,{handle:u,store:b}),T&&/*#__PURE__*/ (0,$.jsx)(zu,{store:b,parentContext:v?.context,isDrawer:p}),typeof n==`function`?n({payload:C}):n]})}function qu(e){return Ku(`alert-dialog`,e)}const Ju=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,forceRender:a=!1,...o}=e,s=Vu(),c=s.useState(`open`),l=s.useState(`nested`),u=s.useState(`mounted`),d={open:c,transitionStatus:s.useState(`transitionStatus`)};return Cn(`div`,e,{state:d,ref:[s.context.backdropRef,t],stateAttributesMapping:$n,props:[{role:`presentation`,hidden:!u,style:{userSelect:`none`,WebkitUserSelect:`none`}},o],enabled:a||!l})}),Yu=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,...s}=e,c=Vu(),l=c.useState(`open`),{getButtonProps:u,buttonRef:d}=Kn({disabled:a,native:o}),f={disabled:a};function p(e){l&&c.setOpen(!1,gn(An,e.nativeEvent))}return Cn(`button`,e,{state:f,ref:[t,d],props:[{onClick:p},s,u]})}),Xu=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,s=Vu(),c=tn(a);return s.useSyncedValueWithCleanup(`descriptionElementId`,c),Cn(`p`,e,{ref:t,props:[{id:c},o]})}),Zu=/*#__PURE__*/ Q.createContext(void 0);function Qu(){let e=Q.useContext(Zu);if(e===void 0)throw Error(er(26));return e}const $u=`ArrowUp`,ed=`ArrowDown`,td=`ArrowLeft`,nd=`ArrowRight`,rd=/* @__PURE__ */ new Set([$u,ed,td,nd,`Home`,`End`]),id=[`Shift`,`Control`,`Alt`,`Meta`];function ad(e){return Mn(e)&&e.tagName===`INPUT`}function od(e){return!!(ad(e)&&e.selectionStart!=null||Mn(e)&&e.tagName===`TEXTAREA`)}function sd(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=cd(e,t,`left`),a=ld(e),o=ld(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=cd(e,t,`top`),r=ld(e),i=ld(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 cd(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 ld(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 ud={...Nn,...Cr,nestedDialogOpen(e){return e?{"data-nested-dialog-open":``}:null}},dd=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,initialFocus:o,...s}=e,c=Vu(),l=c.useState(`descriptionElementId`),u=c.useState(`disablePointerDismissal`),d=c.useState(`floatingRootContext`),f=c.useState(`popupProps`),p=c.useState(`modal`),m=c.useState(`mounted`),h=c.useState(`nested`),g=c.useState(`nestedOpenDialogCount`),_=c.useState(`open`),v=c.useState(`openMethod`),y=c.useState(`titleElementId`),b=c.useState(`transitionStatus`),x=c.useState(`role`),S=d.useState(`floatingId`);Qu(),Xn({open:_,ref:c.context.popupRef,onComplete(){_&&c.context.onOpenChangeComplete?.(!0)}});let C=o===void 0?Tr(c.context.popupRef):o,w=g>0,T=c.useStateSetter(`popupElement`),E=Cn(`div`,e,{state:{open:_,nested:h,transitionStatus:b,nestedDialogOpen:w},props:[f,{id:S,"aria-labelledby":y,"aria-describedby":l,role:x,...jn,hidden:!m,onKeyDown(e){rd.has(e.key)&&e.stopPropagation()},style:{"--nested-dialogs":g}},s],ref:[t,c.context.popupRef,T],stateAttributesMapping:ud});return/*#__PURE__*/ (0,$.jsx)(ge,{context:d,openInteractionType:v,disabled:!m,closeOnFocusOut:!u,initialFocus:C,returnFocus:a,modal:p!==!1,restoreFocus:`popup`,children:E})}),fd=/*#__PURE__*/ Q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,i=Vu(),a=i.useState(`mounted`),o=i.useState(`modal`),s=i.useState(`open`);return a||n?/*#__PURE__*/ (0,$.jsx)(Zu.Provider,{value:n,children:/*#__PURE__*/ (0,$.jsxs)(vn,{ref:t,...r,children:[a&&o===!0&&/*#__PURE__*/ (0,$.jsx)(x,{ref:i.context.internalBackdropRef,inert:at(!s)}),e.children]})}):null}),pd=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,id:a,...o}=e,s=Vu(),c=tn(a);return s.useSyncedValueWithCleanup(`titleElementId`,c),Cn(`h2`,e,{ref:t,props:[{id:c},o]})});function md({...e}){return/* @__PURE__ */ (0,$.jsx)(qu,{"data-slot":`alert-dialog`,...e})}function hd({...e}){return/* @__PURE__ */ (0,$.jsx)(fd,{"data-slot":`alert-dialog-portal`,...e})}function gd({className:e,...t}){return/* @__PURE__ */ (0,$.jsx)(Ju,{"data-slot":`alert-dialog-overlay`,className:Qt(`fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,e),...t})}function _d({className:e,size:t=`default`,container:n,...r}){return/* @__PURE__ */ (0,$.jsxs)(hd,{container:n,children:[/* @__PURE__ */ (0,$.jsx)(gd,{}),/* @__PURE__ */ (0,$.jsx)(dd,{"data-slot":`alert-dialog-content`,"data-size":t,className:Qt(`group/alert-dialog-content fixed top-1/2 start-1/2 z-50 grid w-[calc(100%-2rem)] max-h-[calc(100dvh-2rem)] overflow-y-auto -translate-x-1/2 rtl:translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,e),...r})]})}function vd({className:e,...t}){return/* @__PURE__ */ (0,$.jsx)(`div`,{"data-slot":`alert-dialog-footer`,className:Qt(`-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end`,e),...t})}function yd({className:e,...t}){return/* @__PURE__ */ (0,$.jsx)(pd,{"data-slot":`alert-dialog-title`,className:Qt(`font-heading text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2`,e),...t})}function bd({className:e,...t}){return/* @__PURE__ */ (0,$.jsx)(Xu,{"data-slot":`alert-dialog-description`,className:Qt(`text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground`,e),...t})}function xd({className:e,variant:t=`outline`,size:n=`default`,...r}){return/* @__PURE__ */ (0,$.jsx)(Yu,{"data-slot":`alert-dialog-cancel`,className:Qt(e),render:/* @__PURE__ */ (0,$.jsx)(qt,{variant:t,size:n}),...r})}function Sd({title:e,container:t,finalFocus:n,onDelete:r,onClose:i}){let[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1);return/* @__PURE__ */ (0,$.jsx)(md,{open:!0,onOpenChange:e=>{!e&&!a&&i()},children:/* @__PURE__ */ (0,$.jsxs)(_d,{container:t,finalFocus:n,className:`absolute max-h-[min(calc(100%-2rem),calc(100dvh-2rem))]`,children:[/* @__PURE__ */ (0,$.jsx)(yd,{children:`Delete conversation?`}),/* @__PURE__ */ (0,$.jsxs)(bd,{className:`break-words`,children:[`Delete “`,e,`” and its messages? This cannot be undone.`]}),s&&/* @__PURE__ */ (0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:`Could not delete this conversation. Try again.`}),/* @__PURE__ */ (0,$.jsxs)(vd,{children:[/* @__PURE__ */ (0,$.jsx)(xd,{className:`any-pointer-coarse:min-h-11 any-pointer-coarse:min-w-11`,disabled:a,children:`Cancel`}),/* @__PURE__ */ (0,$.jsx)(qt,{variant:`destructive`,className:`any-pointer-coarse:min-h-11 any-pointer-coarse:min-w-11`,disabled:a,onClick:()=>{o(!0),c(!1),r().then(e=>{o(!1),e?i():c(!0)})},children:a?`Deleting…`:`Delete conversation`})]})]})})}const Cd=/*#__PURE__*/ Q.createContext(void 0);function wd(e){let t=Q.useContext(Cd);if(t===void 0&&!e)throw Error(er(33));return t}const Td=/*#__PURE__*/ Q.createContext(void 0);function Ed(e){let t=Q.useContext(Td);if(t===void 0&&!e)throw Error(er(36));return t}const Dd=/*#__PURE__*/ Q.createContext(void 0);function Od(e=!0){let t=Q.useContext(Dd);if(t===void 0&&!e)throw Error(er(25));return t}const kd=/*#__PURE__*/ Q.createContext(null);function Ad(e=`root`){let t=Q.useContext(kd),n=Q.useContext(Td);return t===null||n===void 0?null:(e===`submenu-trigger`?n.virtualFocus||n.parentVirtualFocus:n.virtualFocus)?t:null}const jd={visible:!0,ref:null};function Md(){return jd}function Nd(e,t,n=`root`){let r=Ad(n),i=((n===`submenu-trigger`?r?.useSubmenuTrigger:r?.useItem)??Md)({label:e.label,children:e.children,render:e.render}),a=mr(t,i.ref);return{visible:i.visible,ref:a,props:i.props}}function Pd(e){e.preventDefault()}function Fd(e){let{closeOnClick:t,highlighted:n,id:r,nodeId:i,store:a,typingRef:o,itemRef:s,itemMetadata:c}=e,l=Ed(),u=Od(!0),d=c.type===`submenu-trigger`,f=d?l.parentVirtualFocus:l.virtualFocus,p=(d&&l.parent.type===`menu`?l.parent.store:l.store).useState(`webkitAriaSelected`,n),{events:m}=a.useState(`floatingTreeRoot`),h=a.useState(`open`),g=u!==void 0,_=!f&&h&&n?0:-1;return Q.useMemo(()=>({id:r,role:`menuitem`,tabIndex:_,"aria-selected":p,onMouseDown:f?Pd:void 0,onKeyDown(e){e.key===` `&&o?.current&&e.preventDefault()},onMouseMove(e){i&&m.emit(`itemhover`,{nodeId:i,target:e.currentTarget})},onClick(e){t&&m.emit(`close`,{domEvent:e.nativeEvent,reason:rr})},onMouseUp(e){if(u){let t=u.initialCursorPointRef.current;if(u.initialCursorPointRef.current=null,g&&t&&Math.abs(e.clientX-t.x)<=1&&Math.abs(e.clientY-t.y)<=1||g&&!un&&e.button===2)return}s.current&&a.context.allowMouseUpTriggerRef.current&&(!g||e.button===2)&&c.type===`regular-item`&&kn(s.current,e,{detail:1,pointerType:`mouse`})}}),[t,_,r,m,i,a.context.allowMouseUpTriggerRef,o,s,u,g,c.type,p,f])}const Id={type:`regular-item`};function Ld(e){let{closeOnClick:t,disabled:n,highlighted:r,id:i,store:a,typingRef:o=a.context.typingRef,nativeButton:s,itemMetadata:c,nodeId:l}=e,u=Q.useRef(null),{getButtonProps:d,buttonRef:f}=Kn({disabled:n,focusableWhenDisabled:!0,native:s,composite:!0}),p=Fd({closeOnClick:t,highlighted:r,id:i,nodeId:l,store:a,typingRef:o,itemRef:u,itemMetadata:c}),m=Q.useCallback(e=>xr(p,{onMouseEnter(e){c.type===`submenu-trigger`&&c.setActive(e.nativeEvent)}},e,d),[p,d,c]),h=mr(u,f);return Q.useMemo(()=>({getItemProps:m,itemRef:h}),[m,h])}const Rd=/*#__PURE__*/ 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,{store:d}=Ed(),f=N({guess:!0,label:a}),p=tn(i),m=d.useState(`disabled`),h=d.useState(`isActive`,f.index),g=d.useState(`floatingNodeId`),_=d.useState(`itemProps`),v=s||m,{getItemProps:y,itemRef:b}=Ld({closeOnClick:c,disabled:v,highlighted:h,id:p,store:d,nativeButton:o,nodeId:g,itemMetadata:Id});return Cn(`div`,e,{state:{disabled:v,highlighted:h},props:[_,u,y],ref:[b,t,f.ref]})}),zd=/*#__PURE__*/ Q.forwardRef(function(e,t){let n=Nd(e,t);return n.visible?/*#__PURE__*/ (0,$.jsx)(Rd,{...e,ref:n.ref}):null}),Bd=/*#__PURE__*/ Q.createContext(void 0);function Vd(e){let t=Q.useContext(Bd);if(t===void 0&&!e)throw Error(er(69));return t}const Hd=/*#__PURE__*/ Q.createContext(void 0);function Ud(){return Q.useContext(Hd)}function Wd(e,t){let n=xn(e.render);if(/*#__PURE__*/ Q.isValidElement(n)){let e=n.props;if(Object.hasOwn(e,`id`))return e.id??``}return e.id??t}function Gd(e,t,n){let r=Wd(e,t),i=r===t?void 0:r;return[r,Q.useCallback(e=>n?.(e?i:void 0),[i,n])]}function Kd(e,t,n){let r=xn(e.render),i=/*#__PURE__*/ Q.isValidElement(r)?r.props:void 0,a=e[`aria-label`]??i?.[`aria-label`],o=e[`aria-labelledby`]??i?.[`aria-labelledby`];return o==null&&!a&&(o=t?t.id||void 0:n||void 0),o}const qd=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,finalFocus:a,id:o,initialFocus:s,...c}=e,{store:l,defaultFloatingId:u,setRenderedFloatingId:d,virtualFocus:f,orientation:p}=Ed(),m=Ud(),{side:h,align:g}=wd(),_=Vd(!0)!=null,v=l.useState(`open`),y=l.useState(`transitionStatus`),b=l.useState(`popupProps`),x=l.useState(`mounted`),S=l.useState(`instantType`),C=l.useState(`activeTriggerElement`),w=l.useState(`parent`),T=l.useState(`lastOpenChangeReason`),E=l.useState(`rootId`),D=l.useState(`floatingRootContext`),O=l.useState(`floatingTreeRoot`),k=l.useState(`closeDelay`),A=l.useState(`hoverEnabled`),j=l.useState(`disabled`),M=l.useState(`openMethod`),N=l.useState(`activeTriggerId`),P=l.useState(`listElement`),[F,ee]=Gd(e,u,d),I=Kd(e,C,N),L=w.type===`menu`?m:void 0,R=w.type===`context-menu`,z=s??w.type!==`menu`;s===void 0&&P&&w.type!==`menu`&&(z=()=>l.state.activeIndex===null&&P),Xn({open:v,ref:l.context.popupRef,onComplete(){v&&l.context.onOpenChangeComplete?.(!0)}}),Q.useEffect(()=>{function e(e){l.setOpen(!1,gn(e.reason,e.domEvent))}return O.events.on(`close`,e),()=>{O.events.off(`close`,e)}},[O.events,l]),In(D,{enabled:A&&!j&&!R&&w.type!==`menubar`,closeDelay:k});let te=l.useStateSetter(`popupElement`),{parentVirtualFocusRef:ne,handleFocus:B}=(Q.useContext(kd)?.useParentHandoff??Yd)(l,w,v,f),re={transitionStatus:y,side:h,align:g,open:v,nested:w.type===`menu`,instant:S},ie=Cn(`div`,e,{state:re,ref:[t,l.context.popupRef,te,ee],stateAttributesMapping:$n,props:[b,{id:F,...P?{role:`presentation`}:{role:`menu`,"aria-orientation":p===`horizontal`?`horizontal`:void 0,"aria-labelledby":I},onKeyDown(e){L?.onPopupKeyDown?.(e),_&&rd.has(e.key)&&e.stopPropagation()},onFocus:B},On(y),c,{"data-rootownerid":E}]}),V=w.type===void 0||R;(C||w.type===`menubar`&&T!==`outside-press`)&&(V=!0);let ae=L?.getReturnElement??ne;return/*#__PURE__*/ (0,$.jsx)(ge,{context:D,openInteractionType:M,modal:R,disabled:!x,returnFocus:a??ae??V,explicitReturnFocus:a===void 0&&ae?!1:void 0,initialFocus:z,restoreFocus:!0,getInsideElements:w.type===void 0?()=>[l.context.beforeTriggerFocusGuardRef.current]:void 0,externalTree:w.type===`menubar`?void 0:O,previousFocusableElement:C,nextFocusableElement:w.type===void 0?l.context.triggerFocusTargetRef:void 0,beforeContentFocusGuardRef:l.context.beforeContentFocusGuardRef,children:ie})}),Jd={parentVirtualFocusRef:void 0,handleFocus:void 0};function Yd(){return Jd}const Xd=/*#__PURE__*/ Q.forwardRef(function(e,t){let n=Ad()?.Popup??qd;return/*#__PURE__*/ (0,$.jsx)(n,{...e,ref:t})}),Zd=/*#__PURE__*/ Q.createContext(void 0);function Qd(){let e=Q.useContext(Zd);if(e===void 0)throw Error(er(32));return e}const $d=/*#__PURE__*/ Q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e,{store:i,parent:a}=Ed();if(!(i.useState(`mounted`)||n))return null;let o=a.type===`menu`||a.type===`menubar`?`group`:void 0;return/*#__PURE__*/ (0,$.jsx)(Zd.Provider,{value:n,children:/*#__PURE__*/ (0,$.jsx)(vn,{ref:t,...r,portalOwnerRole:o})})});function ef(e){let{store:t,domReference:n,positionerElement:r,open:i}=e,a=Q.useRef(null),o=Q.useRef(null),s=rn(r);Rn(()=>{i||(o.current?.abort(),o.current=null,t.state.instantType===`trigger-change`&&t.set(`instantType`,void 0))},[i,t]),Rn(()=>{let e=n,r=a.current;if(e&&(a.current=e),!r||!e||e===r||!t.select(`open`))return;t.set(`instantType`,void 0);let i=new AbortController;return o.current=i,s(()=>{t.select(`open`)&&t.set(`instantType`,`trigger-change`)},i.signal),()=>{i.abort()}},[n,s,t])}const tf=/*#__PURE__*/ 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=bn,style:g,..._}=e,{store:v,virtualFocus:y,syncHighlightedItem:b}=Ed(),S=Qd(),C=Od(!0),w=v.useState(`parent`),T=v.useState(`floatingRootContext`),E=v.useState(`floatingTreeRoot`),D=v.useState(`mounted`),O=v.useState(`open`),k=v.useState(`modal`),j=v.useState(`openMethod`),M=v.useState(`activeTriggerElement`),N=v.useState(`transitionStatus`),P=v.useState(`positionerElement`),F=v.useState(`instantType`),ee=v.useState(`adaptiveOrigin`),I=v.useState(`lastOpenChangeReason`),L=v.useState(`floatingNodeId`),R=v.useState(`floatingParentNodeId`),z=T.useState(`domReferenceElement`),te=n,ne=c,B=l,re=s,ie=h;w.type===`context-menu`&&(te=n??w.context?.anchor,re??=`start`,!o&&re!==`center`&&(B=e.alignOffset??2,ne=e.sideOffset??-5));let V=o,ae=re;w.type===`menu`?(V??=`inline-end`,ae??=`start`,ie=e.collisionAvoidance??Kt):w.type===`menubar`&&(V??=w.context.orientation===`vertical`?`inline-end`:`bottom`,ae??=`start`);let oe=w.type===`context-menu`,H=ar({anchor:te,floatingRootContext:T,positionMethod:C?`fixed`:r,mounted:D,side:V,sideOffset:ne,align:ae,alignOffset:B,arrowPadding:oe?0:f,collisionBoundary:u,collisionPadding:d,sticky:p,nodeId:L,keepMounted:S,disableAnchorTracking:m,collisionAvoidance:ie,shift:oe?{crossAxis:!(`side`in ie&&ie.side===`flip`),rootBoundary:`layoutViewport`}:void 0,externalTree:E,adaptiveOrigin:ee,lazyFlip:y?`placement`:!1});Q.useEffect(()=>{function e(e){e.open&&(e.parentNodeId===L&&v.set(`hoverEnabled`,!1),e.nodeId!==L&&e.parentNodeId===v.select(`floatingParentNodeId`)&&v.setOpen(!1,gn(Or)))}return E.events.on(`menuopenchange`,e),()=>{E.events.off(`menuopenchange`,e)}},[v,E.events,L]),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,gn(t))}return E.events.on(`menuopenchange`,e),()=>{E.events.off(`menuopenchange`,e)}},[E.events,v]);let U=nn();Q.useEffect(()=>{O||U.clear()},[O,U]),Q.useEffect(()=>{function e(e){if(O&&e.nodeId===v.select(`floatingParentNodeId`)){if(e.target&&M&&M!==e.target){let e=v.select(`closeDelay`);e>0?U.isStarted()||U.start(e,()=>{v.setOpen(!1,gn(Or))}):v.setOpen(!1,gn(Or))}else U.clear()}}return E.events.on(`itemhover`,e),()=>{E.events.off(`itemhover`,e)}},[E.events,O,M,v,U]),Q.useEffect(()=>{let e={open:O,nodeId:L,parentNodeId:R,reason:v.select(`lastOpenChangeReason`)};E.events.emit(`menuopenchange`,e)},[E.events,O,v,L,R]),ef({store:v,domReference:z,positionerElement:P,open:O});let se={open:O,side:H.side,align:H.align,anchorHidden:H.anchorHidden,nested:w.type===`menu`,instant:F},ce=w.type===`menubar`&&w.context.modal;Be(O&&(ce||k&&I!==`trigger-hover`),j===`touch`,P,M);let le=Gn(e,se,{styles:H.positionerStyles,transitionStatus:N,props:_,refs:[t,v.useStateSetter(`positionerElement`)],hidden:!D,inert:!O}),ue=D&&w.type!==`menu`&&(w.type!==`menubar`&&k&&I!==`trigger-hover`||w.type===`menubar`&&w.context.modal),de=null;return w.type===`menubar`?de=w.context.contentElement:w.type===void 0&&(de=M),/*#__PURE__*/ (0,$.jsxs)(Cd.Provider,{value:H,children:[ue&&/*#__PURE__*/ (0,$.jsx)(x,{ref:w.type===`context-menu`||w.type===`nested-context-menu`?w.context.internalBackdropRef:null,inert:at(!O),cutout:de}),/*#__PURE__*/ (0,$.jsx)(Gt,{id:L,children:/*#__PURE__*/ (0,$.jsx)(A,{elementsRef:v.context.itemDomElements,labelsRef:v.context.itemLabels,onMapChange:b,children:le})})]})}),nf=/*#__PURE__*/ Q.createContext(null);function rf(e){let t=Q.useContext(nf);if(t===null&&!e)throw Error(er(5));return t}const af={...Un,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,keyboardOpen:e=>e.keyboardOpen,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,listElement:e=>e.listElement,triggerControlsId:(e,t)=>{let n=Un.triggerPopupId(e,t);return n?e.listElement?.id||n:void 0},filterTriggerProps:e=>e.filterTriggerProps,inputProps:e=>e.inputProps,webkitAriaSelected:(e,t)=>Jn&&e.inputFocused&&t?!0:void 0,highlightedItemId:e=>e.highlightedItem?.id||void 0,isActive:(e,t)=>e.activeIndex===t,hoverEnabled:e=>e.hoverEnabled,instantType:e=>e.instantType===`trigger-change`&&!Un.open(e)?void 0: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 of=class extends Tn{constructor(e,t,n=!1){let r=new kr,i=cf(r,t,n,e);super(i,sf(r),af),this.observe(`parent`,e=>{e.type===`menu`?this.context.allowMouseUpTriggerRef=e.store.context.allowMouseUpTriggerRef:e.type!==void 0&&(this.context.allowMouseUpTriggerRef=e.context.allowMouseUpTriggerRef)})}subscribeToParentMenu(){let e=this.state.parent;if(e.type!==`menu`)return;let t=e.store.select(`rootId`),n=e.store.select(`floatingTreeRoot`),r=e.store.select(`keyboardEventRelay`);return 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())})}setOpen(e,t){this.state.floatingRootContext.context.events.emit(`setOpen`,{open:e,eventDetails:t})}setActiveIndex(e,t,n){if(this.state.activeIndex!==e){let r=(e===null?void 0:this.context.itemDomElements.current[e])===this.context.reportedItem;this.context.highlightReason=r?`none`:t,this.context.highlightEvent=r?void 0:n}this.set(`activeIndex`,e)}highlightItem(e,t,n){let r=this.context.itemDomElements.current.indexOf(e);r>-1&&this.setActiveIndex(r,t,n)}};function sf(e){return{positionerRef:/*#__PURE__*/ Q.createRef(),popupRef:/*#__PURE__*/ Q.createRef(),typingRef:{current:!1},itemDomElements:{current:[]},itemLabels:{current:[]},highlightReason:`none`,highlightEvent:void 0,reportedItem:void 0,allowMouseUpTriggerRef:{current:!1},virtualFocusRef:void 0,triggerFocusTargetRef:/*#__PURE__*/ Q.createRef(),beforeTriggerFocusGuardRef:/*#__PURE__*/ Q.createRef(),beforeContentFocusGuardRef:/*#__PURE__*/ Q.createRef(),onOpenChangeComplete:void 0,triggerElements:e}}function cf(e,t,n=!1,r){return{...nr(e,t,n),disabled:!1,modal:!0,openMethod:null,keyboardOpen:!1,allowMouseEnter:!1,highlightItemOnHover:!0,parent:{type:void 0},rootId:void 0,activeIndex:null,listElement:null,filterTriggerProps:zn,inputProps:zn,inputFocused:!1,highlightedItem:void 0,hoverEnabled:!0,instantType:void 0,openChangeReason:null,floatingTreeRoot:new It,floatingNodeId:void 0,floatingParentNodeId:null,itemProps:zn,keyboardEventRelay:void 0,closeDelay:0,adaptiveOrigin:void 0,...r}}const lf=/*#__PURE__*/ Q.createContext(null);function uf(e,t){return(e===`trigger-press`||e===`item-press`)&&t?.detail===0}function df(e,t){return e===`list-navigation`||uf(e,t)}const ff=jt(function(e){let{children:t,open:r,onOpenChange:i,onOpenChangeComplete:a,onItemHighlighted:o,defaultOpen:s=!1,disabled:c=!1,modal:l,loopFocus:u=!0,orientation:d=`vertical`,actionsRef:f,closeParentOnEsc:p=!1,handle:m,triggerId:h,defaultTriggerId:g=null,highlightItemOnHover:_=!0,isSubmenu:v=!1,virtualFocus:y=!1,virtualFocusRef:b,allowEscape:x=!0,resetOnPointerLeave:S=!0}=e,C=Od(!0),T=Ed(!0),E=rf(!0),D=T?.store,O=T?.virtualFocus??!1,k=Q.useMemo(()=>v&&D?{type:`menu`,store:D}:E?{type:`menubar`,context:E}:C&&!D?{type:`context-menu`,context:C}:{type:void 0},[C,D,E,v]),A=tn(),j=tn(),[M,N]=Q.useState(void 0),P=(M??j)||void 0,F=fn(),ee=k.type===`menu`?k.store:void 0,I=(r??s)&&ee?.state.transitionStatus===`starting`,L=lr(()=>I?ee?.state.instantType:void 0).current,z=lr(()=>{let e=new of({open:s,openProp:r,activeTriggerId:g,triggerIdProp:h,parent:k,disabled:c,highlightItemOnHover:_,modal:k.type===void 0?l:void 0,rootId:A,instantType:L},P,F!=null);return e.context.virtualFocusRef=b,e}).current;z.useControlledProp(`openProp`,r),z.useControlledProp(`triggerIdProp`,h),z.useContextCallback(`onOpenChangeComplete`,a);let te=z.useState(`floatingTreeRoot`),ne=en(te),B=z.useState(`open`),re=z.useState(`activeTriggerElement`),ie=z.useState(`positionerElement`),V=z.useState(`hoverEnabled`),ae=z.useState(`disabled`),oe=z.useState(`lastOpenChangeReason`),H=z.useState(`parent`),U=z.useState(`activeIndex`),se=z.useState(`keyboardOpen`),ce=z.useState(`payload`),le=z.useState(`floatingParentNodeId`),ue=Q.useRef(null),de=Q.useRef(H.type!==`context-menu`),fe=nn(),pe=Q.useRef(!0),me=nn(),ge=le!=null,{openMethod:_e,triggerProps:ve}=R(B);z.useSyncedValues({disabled:c,highlightItemOnHover:_,modal:H.type===void 0?l:void 0,openMethod:_e,rootId:A}),Ht(z);let{forceUnmount:ye,transitionStatus:W}=zt(B,z,()=>{z.set(`allowMouseEnter`,!1)},I),be=rn(z.context.popupRef);Q.useEffect(()=>{if(L===void 0)return;let e=()=>{z.state.instantType===L&&z.set(`instantType`,void 0)};if(!B){e();return}if(W!==void 0)return;if(z.context.popupRef.current==null){e();return}let t=new AbortController;return be(e,t.signal),()=>{t.abort()}},[L,B,W,be,z]),Rn(()=>{C&&!T?z.update({parent:{type:`context-menu`,context:C},floatingNodeId:ne,floatingParentNodeId:F}):(T||!z.select(`activeTriggerElement`))&&z.update({floatingNodeId:ne,floatingParentNodeId:F})},[C,T,ne,F,re,z]),Q.useEffect(()=>{B||(ue.current=null),H.type===`context-menu`&&(B?fe.start(500,()=>{de.current=!0}):(fe.clear(),de.current=!1))},[fe,B,H.type]),Rn(()=>{!B&&!V&&z.set(`hoverEnabled`,!0)},[B,V,z]);let xe=Hn((e,t)=>{let n=t.reason;if(!e&&!z.select(`open`)||B===e&&t.trigger===re&&oe===n)return;let r=Lt(t);if(!e&&t.trigger==null&&(t.trigger=re??void 0),i?.(e,t),t.isCanceled)return;z.state.floatingRootContext.dispatchOpenChange(e,t);let a=t.event;if(e===!1&&n!==`item-press`&&a?.type===`click`&&a.pointerType===`touch`&&!pe.current)return;e&&n===`trigger-focus`?(pe.current=!1,me.start(300,()=>{pe.current=!0})):(pe.current=!0,me.clear());let o=!e&&(n===`escape-key`||n==null);ue.current=t.event;let s=pn(z.state,e,t.trigger,r());s.openChangeReason=n,s.keyboardOpen=e&&df(n,a),s.instantType=H.type===`menubar`&&(n===`trigger-focus`||n===`focus-out`||n===`trigger-hover`||n===`list-navigation`||n===`sibling-open`)?`group`:uf(n,a)?`click`:o?`dismiss`:void 0,z.update(s)}),Se=an({popupStore:z,floatingRootContext:z.state.floatingRootContext,floatingId:P,nested:F!=null,onOpenChange:xe}),Ce=Se.context.events;Rn(()=>{let e=({open:e,eventDetails:t})=>xe(e,t);return Ce.on(`setOpen`,e),()=>{Ce?.off(`setOpen`,e)}},[Ce,xe]),Rn(()=>z.subscribeToParentMenu(),[z]);let we=Q.useCallback(()=>{z.setOpen(!1,gn(tr))},[z]);Q.useImperativeHandle(f,()=>({unmount:ye,close:we}),[ye,we]);let Te;H.type===`context-menu`&&(Te=H.context),Q.useImperativeHandle(Te?.positionerRef,()=>ie,[ie]),Q.useImperativeHandle(Te?.actionsRef,()=>({setOpen:xe}),[xe]);let Ee=ln(Se,{enabled:!ae,bubbles:{escapeKey:p&&H.type===`menu`},outsidePress(){return H.type!==`context-menu`||ue.current?.type===`contextmenu`||de.current},externalTree:ge?te:void 0}),De=gr(),Oe=he(Se,{enabled:!ae,listRef:z.context.itemDomElements,activeIndex:U,virtual:y,nested:H.type===`menubar`||!y&&H.type!==void 0,parentOrientation:H.type===`menubar`?H.context.orientation:void 0,loopFocus:u,focusItemOnOpen:y?se:void 0,allowEscape:y&&u&&x,orientation:d,triggerOrientation:y?`vertical`:d,rtl:De===`rtl`,disabledIndices:Mt,onNavigate(e,t){z.setActiveIndex(e,n(t),t?.nativeEvent)},openOnArrowKeyDown:H.type!==`context-menu`&&!(y&&v),externalTree:!y&&ge?te:void 0,nestedReturnFocusRef:ee?.context.virtualFocusRef,focusItemOnHover:_,resetOnPointerLeave:S}),ke=Q.useCallback(e=>{z.context.typingRef.current=e},[z]),Ae=w(Se,{enabled:!ae&&!y,listRef:z.context.itemLabels,elementsRef:z.context.itemDomElements,activeIndex:U,resetMs:500,onMatch:(e,t)=>{B&&e!==U&&z.setActiveIndex(e,Wn,t.nativeEvent)},onTyping:ke}),je=Hn(o),Me=Q.useRef(-1),Ne=Hn(()=>{let e=z.state.activeIndex,t=e===null?void 0:z.context.itemDomElements.current[e]??void 0;if(t?.isConnected===!1)return;let n=t===void 0?-1:e;if(Me.current===n&&z.context.reportedItem===t)return;Me.current=n,z.context.reportedItem=t,y&&z.set(`highlightedItem`,t);let{highlightReason:r,highlightEvent:i}=z.context;z.context.highlightReason=wr,z.context.highlightEvent=void 0,o&&je(t,Wt(r,i,{label:t===void 0?void 0:z.context.itemLabels.current[n]??void 0}))});Rn(()=>{Ne()},[U,Ne]);let Pe=Q.useMemo(()=>{if(!y)return Oe.reference;if(!Oe.trigger)return zn;let{onFocus:e,...t}=Oe.trigger;return t},[y,Oe.reference,Oe.trigger]);z.useSyncedValue(`inputProps`,y?Oe.reference??zn:zn);let Fe=Q.useMemo(()=>{let e=xr(Ae.reference,Pe,Ee.reference,{onMouseMove(){z.set(`allowMouseEnter`,!0)}},ve);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=B,e},[z,Ae.reference,Pe,Ee.reference,ve,B]),Ie=Q.useMemo(()=>{let e=xr(Oe.trigger,Ee.trigger,ve);return e[`aria-haspopup`]=`menu`,e[`aria-expanded`]=!1,e},[Oe.trigger,Ee.trigger,ve]);lr(()=>(z.update({inactiveTriggerProps:Ie}),null));let Le=Q.useMemo(()=>xr(jn,{onMouseMove(){z.set(`allowMouseEnter`,!0),H.type===`menu`&&z.set(`hoverEnabled`,!1)},onClick(){z.select(`hoverEnabled`)&&z.set(`hoverEnabled`,!1)},onKeyDown(e){let t=z.select(`keyboardEventRelay`);t&&!e.isPropagationStopped()&&t(e)}},Ae.floating,Oe.floating,Ee.floating),[H.type,z,Ae.floating,Oe.floating,Ee.floating]),Re=Oe.item??zn;on(z,{floatingRootContext:Se,activeTriggerProps:Fe,inactiveTriggerProps:Ie,popupProps:Le,itemProps:Re});let ze=Q.useMemo(()=>({store:z,parent:k,orientation:d,loopFocus:u,allowEscape:x,defaultFloatingId:j,setRenderedFloatingId:N,virtualFocus:y,parentVirtualFocus:O,syncHighlightedItem:Ne}),[z,k,d,u,x,j,y,O,Ne]),Be=typeof t==`function`?t({payload:ce}):t,Ve=/*#__PURE__*/ (0,$.jsxs)(Td.Provider,{value:ze,children:[m&&/*#__PURE__*/ (0,$.jsx)(Er,{handle:m,store:z}),Be]});return(H.type===void 0||H.type===`context-menu`)&&(Ve=/*#__PURE__*/ (0,$.jsx)(Xt,{externalTree:te,children:Ve})),Ve});function pf(e){let t=Q.useContext(lf);if(t===null)return/*#__PURE__*/ (0,$.jsx)(ff,{...e});let n=t.Root;return/*#__PURE__*/ (0,$.jsx)(lf.Provider,{value:null,children:/*#__PURE__*/ (0,$.jsx)(n,{...t.options,...e})})}function mf(e={}){let{highlightItemOnHover:t,highlightedIndex:n,onHighlightedIndexChange:r}=Pn(),{ref:i,index:a}=N(e),o=n===a,s=Q.useRef(null),c=mr(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 hf(e){let{render:t,className:n,style:r,state:i=zn,props:a=Mt,refs:o=Mt,metadata:s,stateAttributesMapping:c,tag:l=`div`,...u}=e,{compositeProps:d,compositeRef:f}=mf({metadata:s});return Cn(l,e,{state:i,ref:[f,...o],props:[d,...a,u],stateAttributesMapping:c})}function gf(e){if(Mn(e)&&e.hasAttribute(`data-rootownerid`))return e.getAttribute(`data-rootownerid`);if(!Dr(e))return gf(En(e))}var _f=/* @__PURE__ */ Yn(Vt(),1);function vf(e,t){function n(n,r,i){let a=n.currentTarget;_f.flushSync(()=>{e.setOpen(!1,gn(Fn,n.nativeEvent,a))}),yn(a.isConnected?a:t.current,r,i)?.focus()}function r(t){n(t,-1,e.select(`positionerElement`))}function i(t){let r=e.select(`positionerElement`);r&&Yt(t,r)?e.context.beforeContentFocusGuardRef.current?.focus():n(t,1,r)}return{handlePreFocusGuardFocus:r,handleFocusTargetFocus:i}}function yf(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,or(e.currentTarget).addEventListener(`click`,()=>{i.current=!1},{once:!0}))},onClick:e=>{i.current&&(i.current=!1,e.preventBaseUIHandler())}}:zn,[t,n,r])}const bf=Bn(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,id:s,openOnHover:c,delay:l=100,closeDelay:u=0,handle:d,payload:f,...p}=e,m=Ed(!0),h=cr(d)??m?.store;if(!h)throw Error(er(85));let g=tn(s),_=h.useState(`isTriggerActive`,g),v=h.useState(`floatingRootContext`),y=h.useState(`isOpenedByTrigger`,g),b=h.useState(`triggerControlsId`,g),x=Q.useRef(null),S=Sf(),C=Pn(!0),w=Ar(),T=Q.useMemo(()=>w??new It,[w]),E=en(T),D=fn(),{registerTrigger:O,isMountedByThisTrigger:k}=qn(g,x,h,{payload:f,closeDelay:u,parent:S,floatingTreeRoot:T,floatingNodeId:E,floatingParentNodeId:D,keyboardEventRelay:C?.relayKeyboardEvent}),A=S.type===`menubar`,j=h.useState(`disabled`),M=a||j||A&&S.context.disabled,{getButtonProps:N,buttonRef:P}=Kn({disabled:M,native:o});Q.useEffect(()=>{!y&&S.type===void 0&&(h.context.allowMouseUpTriggerRef.current=!1)},[h,y,S.type]);let F=Q.useRef(null),ee=nn(),I=Hn(e=>{if(!F.current)return;ee.clear(),h.context.allowMouseUpTriggerRef.current=!1;let t=e.target;Bt(F.current,t)||Bt(h.select(`positionerElement`),t)||t===F.current||t!=null&&gf(t)===h.select(`rootId`)||Ue(e,F.current)||T.events.emit(`close`,{domEvent:e,reason:hr})});Q.useEffect(()=>{let e=or(F.current);if(y&&h.select(`lastOpenChangeReason`)===`trigger-hover`)return e.addEventListener(`mouseup`,I,{once:!0}),()=>{e.removeEventListener(`mouseup`,I)}},[y,I,h]);let L=A&&S.context.hasSubmenuOpen,R=yr(v,{enabled:(c??L)&&!M&&(!A||L&&!k),handleClose:Qn({blockPointerEvents:!A}),mouseOnly:!0,move:!1,restMs:S.type===void 0?l:void 0,delay:{close:u},triggerElementRef:x,externalTree:T,isActiveTrigger:_,isClosing:()=>h.select(`transitionStatus`)===`ending`}),z=xf(y,h.select(`lastOpenChangeReason`)),te=pe(v,{enabled:!M,event:y&&A?`click`:`mousedown`,toggle:!0,ignoreMouse:!1,stickIfOpen:S.type===void 0&&z}),ne=Vn(v,{enabled:!M&&L}),B=yf({open:y,enabled:A,mouseDownAction:`open`}),re=Q.useMemo(()=>xr(ne.reference,te.reference),[ne.reference,te.reference]),ie=h.useState(`triggerProps`,k),V=h.useState(`filterTriggerProps`),{handlePreFocusGuardFocus:ae,handleFocusTargetFocus:oe}=vf(h,x),H={disabled:M,open:y},U=[F,t,P,O,x],se=[re,R??zn,ie,{"aria-haspopup":`menu`,"aria-controls":b,id:g,onMouseDown:e=>{h.select(`open`)||(ee.start(200,()=>{h.context.allowMouseUpTriggerRef.current=!0}),or(e.currentTarget).addEventListener(`mouseup`,I,{once:!0}))}},V,A?{role:`menuitem`}:{},B,p,N],ce=Cn(`button`,e,{enabled:!A,stateAttributesMapping:br,state:H,ref:U,props:se});return A?/*#__PURE__*/ (0,$.jsx)(hf,{tag:`button`,render:n,className:r,style:i,state:H,refs:U,props:se,stateAttributesMapping:br}):y?/*#__PURE__*/ (0,$.jsxs)(Q.Fragment,{children:[/*#__PURE__*/ (0,$.jsx)(ur,{ref:h.context.beforeTriggerFocusGuardRef,onFocus:ae},`${g}-pre-focus-guard`),/*#__PURE__*/ (0,$.jsx)(Q.Fragment,{children:ce},g),/*#__PURE__*/ (0,$.jsx)(ur,{ref:h.context.triggerFocusTargetRef,onFocus:oe},`${g}-post-focus-guard`)]}):/*#__PURE__*/ (0,$.jsx)(Q.Fragment,{children:ce},g)});function xf(e,t){let n=nn(),[r,i]=Q.useState(!1);return Rn(()=>{e&&t===`trigger-hover`?(i(!0),n.start(500,()=>{i(!1)})):e||(n.clear(),i(!1))},[e,t,n]),r}function Sf(){let e=rf(!0);return Q.useMemo(()=>e?{type:`menubar`,context:e}:{type:void 0},[e])}function Cf(e){return e==null||e.hasAttribute(`disabled`)||e.getAttribute(`aria-disabled`)===`true`}function wf({...e}){return/* @__PURE__ */ (0,$.jsx)(pf,{"data-slot":`dropdown-menu`,...e})}function Tf({...e}){return/* @__PURE__ */ (0,$.jsx)(bf,{"data-slot":`dropdown-menu-trigger`,...e})}function Ef({align:e=`start`,alignOffset:t=0,side:n=`bottom`,sideOffset:r=4,className:i,container:a,...o}){return/* @__PURE__ */ (0,$.jsx)($d,{container:a,children:/* @__PURE__ */ (0,$.jsx)(tf,{className:`isolate z-50 outline-none`,align:e,alignOffset:t,side:n,sideOffset:r,children:/* @__PURE__ */ (0,$.jsx)(Xd,{"data-slot":`dropdown-menu-content`,className:Qt(`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 Df({className:e,inset:t,variant:n=`default`,...r}){return/* @__PURE__ */ (0,$.jsx)(zd,{"data-slot":`dropdown-menu-item`,"data-inset":t,"data-variant":n,className:Qt(`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 Of({className:e,...t}){return/* @__PURE__ */ (0,$.jsx)(Pu,{"data-slot":`dropdown-menu-separator`,className:Qt(`-mx-1 my-1 h-px bg-border`,e),...t})}function kf({chat:e,state:t,thread:n,onDelete:r}){let i=(0,Q.useRef)(null),[a,o]=(0,Q.useState)(!1),s=(0,Q.useRef)(null),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(!1),[h,g]=(0,Q.useState)(!1),_=n.title??``,v=n.role===`manager`&&t.status!==`submitted`&&t.status!==`streaming`;return(0,Q.useEffect)(()=>{l&&requestAnimationFrame(()=>c.current?.select())},[l]),(0,Q.useEffect)(()=>{if(!h)return;let e=setTimeout(()=>g(!1),2e3);return()=>clearTimeout(e)},[h]),/* @__PURE__ */ (0,$.jsxs)(`div`,{ref:s,"data-slot":`conversation-title`,className:`shrink-0 border-b`,children:[a&&/* @__PURE__ */ (0,$.jsx)(Sd,{title:_||`Untitled`,container:s,finalFocus:i,onClose:()=>o(!1),onDelete:async()=>{let t=await e.deleteThread();return t&&r(n.id),t}}),/* @__PURE__ */ (0,$.jsx)(`div`,{className:`flex h-10 items-center gap-1 px-4 any-pointer-coarse:min-h-11`,children:l?/* @__PURE__ */ (0,$.jsxs)(`form`,{className:`flex min-w-0 flex-1 gap-1`,onSubmit:t=>{t.preventDefault(),d.trim()&&(m(!0),e.renameThread(d.trim()).then(e=>{m(!1),e&&(u(!1),requestAnimationFrame(()=>i.current?.focus()))}))},children:[/* @__PURE__ */ (0,$.jsx)(ir,{ref:c,"aria-label":`Conversation title`,className:`h-7 any-pointer-coarse:min-h-11`,value:d,maxLength:200,disabled:p,onChange:e=>f(e.currentTarget.value),onKeyDown:e=>{e.key===`Escape`&&(u(!1),requestAnimationFrame(()=>i.current?.focus()))}}),/* @__PURE__ */ (0,$.jsx)(K,{type:`button`,size:`icon-sm`,variant:`ghost`,tooltip:`Cancel`,disabled:p,onClick:()=>{u(!1),requestAnimationFrame(()=>i.current?.focus())},children:/* @__PURE__ */ (0,$.jsx)(L,{})}),/* @__PURE__ */ (0,$.jsx)(K,{type:`submit`,size:`icon-sm`,tooltip:p?`Saving…`:`Save`,disabled:!d.trim()||p,children:p?/* @__PURE__ */ (0,$.jsx)(se,{}):/* @__PURE__ */ (0,$.jsx)(F,{})})]}):/* @__PURE__ */ (0,$.jsxs)($.Fragment,{children:[/* @__PURE__ */ (0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-sm font-medium`,title:_,children:_}),h&&/* @__PURE__ */ (0,$.jsx)(`span`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Copied`}),/* @__PURE__ */ (0,$.jsxs)(wf,{children:[/* @__PURE__ */ (0,$.jsx)(Tf,{ref:i,render:/* @__PURE__ */ (0,$.jsx)(K,{tooltip:`Conversation actions`,variant:`ghost`,size:`icon-sm`}),children:/* @__PURE__ */ (0,$.jsx)(yu,{})}),/* @__PURE__ */ (0,$.jsxs)(Ef,{container:s,align:`end`,className:`w-40`,children:[/* @__PURE__ */ (0,$.jsxs)(Df,{className:`any-pointer-coarse:min-h-11`,disabled:!v,onClick:()=>{f(n.title??``),u(!0)},children:[/* @__PURE__ */ (0,$.jsx)(Eu,{}),`Rename`]}),/* @__PURE__ */ (0,$.jsxs)(Df,{className:`any-pointer-coarse:min-h-11`,disabled:t.messages.length===0,onClick:()=>{navigator.clipboard.writeText(Et(_,t.messages)).then(()=>g(!0))},children:[/* @__PURE__ */ (0,$.jsx)(M,{}),`Copy Markdown`]}),/* @__PURE__ */ (0,$.jsx)(Of,{}),/* @__PURE__ */ (0,$.jsxs)(Df,{className:`any-pointer-coarse:min-h-11`,variant:`destructive`,disabled:!v,onClick:()=>o(!0),children:[/* @__PURE__ */ (0,$.jsx)(Fr,{}),`Delete`]})]})]})]})})]})}var Af=class extends ie{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),oe(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&s(t.mutationKey)!==s(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Ce();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){Ct.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function jf(e,t){let n=ee(t),[r]=Q.useState(()=>new Af(n,e));Q.useEffect(()=>{r.setOptions(e)},[r,e]);let i=Q.useSyncExternalStore(Q.useCallback(e=>r.subscribe(Ct.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=Q.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(bt)},[r]);if(i.error&&d(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}const Mf=/*#__PURE__*/ Q.createContext(void 0);function Nf(e){let t=Q.useContext(Mf);if(t===void 0&&!e)throw Error(er(47));return t}const Pf={...Un,disabled:e=>e.disabled,instantType:e=>e.instantType===`trigger-change`&&!Un.open(e)?void 0:e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,isPressOpenedByTrigger:(e,t)=>e.openChangeReason===`trigger-press`&&Un.isOpenedByTrigger(e,t),isTouchPressOpen:(e,t)=>t&&e.openMethod===`touch`&&e.openChangeReason===`trigger-press`,hasTriggerFocusGuards:(e,t)=>Un.isOpenedByTrigger(e,t)&&!e.focusManagerModal,modal:e=>e.modal,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};var Ff=class extends Tn{constructor(e,t,n){let r=new kr;super(If(e,r,t,n),Lf(r),Pf)}setOpen=(e,t)=>{let n=t.reason===Rt,r=t.reason===`trigger-press`&&t.event.detail===0,i=!e&&(t.reason===`escape-key`||t.reason==null),a=Lt(t),o=this.select(`activeTriggerId`);if(!e&&t.reason===`close-press`&&t.trigger==null&&o!=null&&(t.trigger=this.context.triggerElements.getById(o)??this.select(`activeTriggerElement`)??void 0),this.context.onOpenChange?.(e,t),t.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(e,t);let s=()=>{let n=pn(this.state,e,t.trigger,a());n.openChangeReason=t.reason,this.update(n)};n?(this.context.stickIfOpen=!0,this.context.stickIfOpenTimeout.start(500,()=>{this.context.stickIfOpen=!1}),_f.flushSync(s)):s();let c;r?c=`click`:i?c=`dismiss`:t.reason===`focus-out`&&(c=`focus`),this.set(`instantType`,c)}};function If(e,t,n,r=!1){let i={...nr(t,n,r),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return i.open&&e?.mounted===void 0&&(i.mounted=!0),i}function Lf(e){return{popupRef:/*#__PURE__*/ Q.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:/*#__PURE__*/ Q.createRef(),beforeTriggerFocusGuardRef:/*#__PURE__*/ Q.createRef(),beforeContentFocusGuardRef:/*#__PURE__*/ Q.createRef(),stickIfOpenTimeout:new Zt,stickIfOpen:!0,triggerElements:e}}const Rf=jt(function({props:e}){let{children:t,open:n,defaultOpen:r=!1,onOpenChange:i,onOpenChangeComplete:a,modal:o=!1,handle:s,triggerId:c,defaultTriggerId:l=null}=e,u=Bf(s,{modal:o,open:r,openProp:n,activeTriggerId:l,triggerIdProp:c});u.useControlledProp(`openProp`,n),u.useControlledProp(`triggerIdProp`,c);let d=u.useState(`open`),f=u.useState(`mounted`),p=u.useState(`payload`);u.useContextCallback(`onOpenChange`,i),u.useContextCallback(`onOpenChangeComplete`,a),Nt(u,d),Ht(u);let{forceUnmount:m}=zt(d,u,()=>{u.context.stickIfOpen=!0,u.set(`openChangeReason`,null)});u.useSyncedValues({modal:o}),Q.useEffect(()=>{d||u.context.stickIfOpenTimeout.clear()},[u,d]),Q.useImperativeHandle(e.actionsRef,()=>({unmount:m,close:()=>u.setOpen(!1,gn(tr))}),[m,u]);let h=d||f||s!=null;return/*#__PURE__*/ (0,$.jsxs)(Mf.Provider,{value:u,children:[s&&/*#__PURE__*/ (0,$.jsx)(Er,{handle:s,store:u}),h&&/*#__PURE__*/ (0,$.jsx)(Vf,{store:u,modal:o}),typeof t==`function`?t({payload:p}):t]})});function zf(e){return Nf(!0)?/*#__PURE__*/ (0,$.jsx)(Rf,{props:e}):/*#__PURE__*/ (0,$.jsx)(Xt,{children:/*#__PURE__*/ (0,$.jsx)(Rf,{props:e})})}function Bf(e,t){let n=Zn((e,n)=>new Ff(t,e,n));return Q.useEffect(()=>n.context.stickIfOpenTimeout.disposeEffect(),[n]),n}function Vf({store:e,modal:t}){let n=e.useState(`floatingRootContext`),r=ln(n,{outsidePressEvent:{mouse:t===`trap-focus`?`sloppy`:`intentional`,touch:`sloppy`}}),i=r.reference,a=r.floating;return on(e,{activeTriggerProps:i,inactiveTriggerProps:i,popupProps:a}),null}const Hf=Bn(function(e,t){let{render:n,className:r,style:i,disabled:a=!1,nativeButton:o=!0,handle:s,payload:c,openOnHover:l=!1,delay:u=300,closeDelay:d=0,id:f,...p}=e,h=Nf(!0),g=cr(s)??h;if(!g)throw Error(er(74));let _=tn(f),v=g.useState(`isTriggerActive`,_),y=g.useState(`floatingRootContext`),b=g.useState(`isOpenedByTrigger`,_),x=g.useState(`triggerPopupId`,_),S=Q.useRef(null),{registerTrigger:C,isMountedByThisTrigger:w}=qn(_,S,g,{payload:c,disabled:a,openOnHover:l,closeDelay:d}),T=g.useState(`isPressOpenedByTrigger`,_),E=g.useState(`isTouchPressOpen`,l),D=g.useState(`hasTriggerFocusGuards`,_),O=yr(y,{enabled:!a&&l&&!E,mouseOnly:!0,move:!1,handleClose:Qn(),restMs:u,delay:{close:d},triggerElementRef:S,isActiveTrigger:v,isClosing:()=>g.select(`transitionStatus`)===`ending`}),k=Hn(()=>g.context.stickIfOpen),A=pe(y,{stickIfOpen:k}),j=m(()=>g.select(`open`),e=>{g.set(`openMethod`,e)}),M=g.useState(`triggerProps`,w),{getButtonProps:N,buttonRef:P}=Kn({disabled:a,native:o}),F={open(e){return T?br.open(e):Ln.open(e)}},{handlePreFocusGuardFocus:ee,handleFocusTargetFocus:I}=vf(g,S),L=Cn(`button`,e,{state:{disabled:a,open:b},ref:[P,t,C,S],props:[A.reference,O,M,j,{[_n]:``,id:_,"aria-haspopup":`dialog`,"aria-expanded":b,"aria-controls":x},p,N],stateAttributesMapping:F}),R=/*#__PURE__*/ (0,$.jsx)(Q.Fragment,{children:L},_);return D?/*#__PURE__*/ (0,$.jsxs)(Q.Fragment,{children:[/*#__PURE__*/ (0,$.jsx)(ur,{ref:g.context.beforeTriggerFocusGuardRef,onFocus:ee}),R,/*#__PURE__*/ (0,$.jsx)(ur,{ref:g.context.triggerFocusTargetRef,onFocus:I})]}):R}),Uf=/*#__PURE__*/ Q.createContext(void 0);function Wf(){let e=Q.useContext(Uf);if(e===void 0)throw Error(er(45));return e}const Gf=/*#__PURE__*/ Q.forwardRef(function(e,t){let{keepMounted:n=!1,...r}=e;return Nf().useState(`mounted`)||n?/*#__PURE__*/ (0,$.jsx)(Uf.Provider,{value:n,children:/*#__PURE__*/ (0,$.jsx)(vn,{ref:t,...r})}):null}),Kf=/*#__PURE__*/ Q.createContext(void 0);function qf(){let e=Q.useContext(Kf);if(!e)throw Error(er(46));return e}const Jf=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,anchor:a,positionMethod:o,side:s,align:c,sideOffset:l,alignOffset:u,collisionBoundary:d=`clipping-ancestors`,collisionPadding:f,arrowPadding:p,sticky:m,disableAnchorTracking:h=!1,collisionAvoidance:g=Kt,..._}=e,v=Nf(),y=Wf(),b=en(),S=v.useState(`floatingRootContext`),C=v.useState(`mounted`),w=v.useState(`open`),T=v.useState(`openChangeReason`),E=v.useState(`activeTriggerElement`),D=v.useState(`modal`),O=v.useState(`openMethod`),k=v.useState(`positionerElement`),A=v.useState(`instantType`),j=v.useState(`transitionStatus`),M=v.useState(`adaptiveOrigin`),N=ar({anchor:a,floatingRootContext:S,positionMethod:o,mounted:C,side:s,sideOffset:l,align:c,alignOffset:u,arrowPadding:p,collisionBoundary:d,collisionPadding:f,sticky:m,disableAnchorTracking:h,keepMounted:y,nodeId:b,collisionAvoidance:g,adaptiveOrigin:M});ef({store:v,domReference:S.useState(`domReferenceElement`),positionerElement:k,open:w});let P=D===!0&&T!==`trigger-hover`;Be(w&&P,O===`touch`,k,E);let F=v.useStateSetter(`positionerElement`),ee={open:w,side:N.side,align:N.align,anchorHidden:N.anchorHidden,instant:A},I=Gn(e,ee,{styles:N.positionerStyles,transitionStatus:j,props:_,refs:[t,F],hidden:!C,inert:!w});return/*#__PURE__*/ (0,$.jsxs)(Kf.Provider,{value:N,children:[C&&P&&/*#__PURE__*/ (0,$.jsx)(x,{inert:at(!w),cutout:E}),/*#__PURE__*/ (0,$.jsx)(Gt,{id:b,children:I})]})}),Yf=/*#__PURE__*/ Q.createContext(void 0);function Xf(){let[e,t]=Q.useState(0),n=Hn(()=>(t(e=>e+1),()=>{t(e=>Math.max(0,e-1))}));return{context:Q.useMemo(()=>({register:n}),[n]),hasClosePart:e>0}}const Zf=/*#__PURE__*/ Q.forwardRef(function(e,t){let{render:n,className:r,style:i,initialFocus:a,finalFocus:o,...s}=e,c=Nf(),l=qf(),u=Vd(!0)!=null,{context:d,hasClosePart:f}=Xf(),p=c.useState(`open`),m=c.useState(`openMethod`),h=c.useState(`instantType`),g=c.useState(`transitionStatus`),_=c.useState(`popupProps`),v=c.useState(`titleElementId`),y=c.useState(`descriptionElementId`),b=c.useState(`modal`),x=c.useState(`mounted`),S=c.useState(`openChangeReason`),C=c.useState(`activeTriggerElement`),w=c.useState(`floatingRootContext`),T=w.useState(`floatingId`),E=c.useState(`disabled`),D=c.useState(`openOnHover`),O=c.useState(`closeDelay`);Xn({open:p,ref:c.context.popupRef,onComplete(){p&&c.context.onOpenChangeComplete?.(!0)}}),In(w,{enabled:D&&!E,closeDelay:O});let k=a===void 0?Tr(c.context.popupRef):a,A=b!==!1&&f;c.useSyncedValue(`focusManagerModal`,A);let j=c.useStateSetter(`popupElement`),M={open:p,side:l.side,align:l.align,instant:h,transitionStatus:g},N=Cn(`div`,e,{state:M,ref:[t,c.context.popupRef,j],props:[_,{id:T,role:`dialog`,...jn,"aria-labelledby":v,"aria-describedby":y,onKeyDown(e){u&&rd.has(e.key)&&e.stopPropagation()}},On(g),s],stateAttributesMapping:$n});return/*#__PURE__*/ (0,$.jsx)(ge,{context:w,openInteractionType:m,modal:A,disabled:!x||S===`trigger-hover`,initialFocus:k,returnFocus:o,restoreFocus:`popup`,getInsideElements:()=>[c.context.beforeTriggerFocusGuardRef.current],previousFocusableElement:Mn(C)?C:void 0,nextFocusableElement:c.context.triggerFocusTargetRef,beforeContentFocusGuardRef:c.context.beforeContentFocusGuardRef,children:/*#__PURE__*/ (0,$.jsx)(Yf.Provider,{value:d,children:N})})});function Qf({...e}){return/* @__PURE__ */ (0,$.jsx)(zf,{"data-slot":`popover`,...e})}function $f({...e}){return/* @__PURE__ */ (0,$.jsx)(Hf,{"data-slot":`popover-trigger`,...e})}function ep({className:e,align:t=`center`,alignOffset:n=0,side:r=`bottom`,sideOffset:i=4,container:a,collisionBoundary:o,...s}){return/* @__PURE__ */ (0,$.jsx)(Gf,{container:a,children:/* @__PURE__ */ (0,$.jsx)(Jf,{align:t,alignOffset:n,side:r,sideOffset:i,collisionBoundary:o,className:`isolate z-50`,children:/* @__PURE__ */ (0,$.jsx)(Zf,{"data-slot":`popover-content`,className:Qt(`z-50 flex w-72 origin-(--transform-origin) flex-col gap-2.5 rounded-lg bg-popover p-2.5 text-sm text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 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:fade-out-0 data-closed:zoom-out-95`,e),...s})})})}function tp({chat:e,state:t}){let n=(0,Q.useId)(),r=(0,Q.useRef)(null),[i]=(0,Q.useState)(()=>new Tt),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(),[l,u]=(0,Q.useState)(null),d=t.auth.status===`ready`&&t.auth.currentUser.scope===`tenant`?t.auth.currentUser:null,f=vt({queryKey:[`mcp-connections`,d?.organization.id,d?.tenant.id,d?.user.id],enabled:a&&!!d,queryFn:()=>e.getMcpCatalog(),retry:!1},i),p=jf({mutationFn:t=>t.action===`authorize`?e.authorizeMcpConnection(t):e.manageMcpConnection(t),onMutate:e=>`mcpServerId`in e?e.mcpServerId:f.data?.connections.find(t=>t.id===e.id)?.mcp_server_id,onSuccess:()=>u(null),onSettled:()=>f.refetch()},i);if(!d)return null;let m=p.isPending,h=f.isError?void 0:f.data?.servers,g=m?{authorize:`Waiting for sign-in…`,test:`Testing connection…`,disconnect:`Disconnecting…`,connect:`Enabling…`,headers:`Saving credentials…`}[p.variables.action]:null,_=p.isError?p.error.message:p.isSuccess?p.variables.action===`test`&&p.data&&`tool_count`in p.data?`${p.data.tool_count} tools available.`:p.variables.action===`disconnect`?`Disconnected locally.`:`Connection saved.`:null;return/* @__PURE__ */ (0,$.jsx)(`div`,{ref:r,children:/* @__PURE__ */ (0,$.jsxs)(Qf,{open:a,onOpenChange:e=>{o(e),e&&c(r.current?.closest(`[data-slot="chat"]`)??void 0)},children:[/* @__PURE__ */ (0,$.jsx)($f,{render:/* @__PURE__ */ (0,$.jsx)(K,{variant:`ghost`,size:`icon-sm`,tooltip:`MCP connections`}),children:/* @__PURE__ */ (0,$.jsx)(Pr,{})}),/* @__PURE__ */ (0,$.jsxs)(ep,{container:r,collisionBoundary:s,align:`end`,"aria-labelledby":`${n}-title`,className:`max-h-(--available-height) w-[min(24rem,85vw)] max-w-(--available-width) gap-0 overflow-hidden p-0`,children:[/* @__PURE__ */ (0,$.jsx)(`header`,{className:`shrink-0 border-b px-3 py-2`,children:/* @__PURE__ */ (0,$.jsx)(`h2`,{id:`${n}-title`,className:`font-semibold`,children:`MCP connections`})}),/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`max-h-[24rem] min-h-0 divide-y overflow-y-auto overscroll-contain`,children:[f.isPending&&/* @__PURE__ */ (0,$.jsx)(`p`,{role:`status`,className:`px-3 py-2 text-xs`,children:`Loading servers…`}),f.isError&&/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`px-3 py-2`,children:[/* @__PURE__ */ (0,$.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:f.error.message}),/* @__PURE__ */ (0,$.jsx)(qt,{size:`sm`,className:`any-pointer-coarse:min-h-11 any-pointer-coarse:min-w-11`,onClick:()=>void f.refetch(),children:`Try again`})]}),h?.length===0&&/* @__PURE__ */ (0,$.jsx)(`p`,{className:`px-3 py-2 text-xs text-muted-foreground`,children:`No MCP servers are available.`}),h?.map(e=>{let r=f.data?.connections.find(t=>t.mcp_server_id===e.id),i=r?.auth_state===`connected`,a=e.auth_kind===`none`,o=p.context===e.id,s=m&&o?Ou:Pr,c=new URL(e.endpoint_url),d=a?`Disable`:r?.auth_state===`disconnected`?`Remove connection`:`Disconnect`,h=e.auth_kind?{none:[`Enable`,`Enable`],oauth:[`Connect`,`Reconnect`],static_headers:[`Connect`,`Replace credentials`]}[e.auth_kind]:null;return/* @__PURE__ */ (0,$.jsxs)(Wr,{render:/* @__PURE__ */ (0,$.jsx)(`article`,{}),size:`xs`,"data-slot":`mcp-connection`,className:`rounded-none border-0 py-1.5`,children:[/* @__PURE__ */ (0,$.jsx)(jr,{variant:`icon`,className:`text-muted-foreground`,children:/* @__PURE__ */ (0,$.jsx)(s,{"aria-hidden":`true`,className:m&&o?`animate-spin`:void 0})}),/* @__PURE__ */ (0,$.jsxs)(Hr,{className:`min-w-0`,title:e.endpoint_url,children:[/* @__PURE__ */ (0,$.jsx)(`h3`,{className:`truncate text-sm font-medium`,children:c.hostname}),/* @__PURE__ */ (0,$.jsxs)(Ir,{role:`status`,className:`line-clamp-none truncate`,children:[o&&g?g:o&&p.isError&&p.variables.action===`test`?`Connection failed`:i?a?`Enabled`:`Connected`:r?.auth_state===`reauthorization_required`?`Reconnect needed`:a?`Disabled`:`Not connected`,` · `,c.pathname,c.search]})]}),l!==e.id&&/* @__PURE__ */ (0,$.jsxs)(zr,{className:`shrink-0 gap-0.5`,children:[h&&!(a&&i)&&/* @__PURE__ */ (0,$.jsx)(K,{size:i?`icon-sm`:`xs`,variant:i?`ghost`:`outline`,"aria-label":`${h[+!!i]}: ${c.hostname}`,tooltip:h[+!!i],disabled:m,onClick:()=>e.auth_kind===`oauth`?p.mutate({action:`authorize`,mcpServerId:e.id,...r?{id:r.id}:{}}):e.auth_kind===`static_headers`?u(e.id):p.mutate({action:`connect`,mcpServerId:e.id}),children:i?/* @__PURE__ */ (0,$.jsx)(hu,{}):h[0]}),i&&r&&/* @__PURE__ */ (0,$.jsx)(K,{size:`icon-sm`,variant:`ghost`,"aria-label":`Test connection: ${c.hostname}`,tooltip:`Test connection`,disabled:m,onClick:()=>p.mutate({action:`test`,id:r.id}),children:/* @__PURE__ */ (0,$.jsx)(Du,{})}),r&&/* @__PURE__ */ (0,$.jsx)(K,{size:`icon-sm`,variant:`ghost`,"aria-label":`${d}: ${c.hostname}`,tooltip:d,disabled:m,onClick:()=>p.mutate({action:`disconnect`,id:r.id}),children:/* @__PURE__ */ (0,$.jsx)(L,{})})]}),!e.auth_kind&&/* @__PURE__ */ (0,$.jsx)(`p`,{className:`basis-full text-xs text-destructive`,children:`Configuration unavailable. Contact your administrator.`}),l===e.id&&/* @__PURE__ */ (0,$.jsx)(`form`,{className:`grid basis-full gap-2`,onSubmit:t=>{t.preventDefault();let n=new FormData(t.currentTarget);p.mutate({action:`headers`,mcpServerId:e.id,headers:Object.fromEntries(e.header_names.map(e=>[e,n.get(e)]))})},children:/* @__PURE__ */ (0,$.jsxs)(`fieldset`,{disabled:m,className:`grid gap-2`,children:[e.header_names.map(t=>/* @__PURE__ */ (0,$.jsxs)(Br,{className:`gap-1`,children:[/* @__PURE__ */ (0,$.jsxs)(Lr,{className:`text-xs`,htmlFor:`${n}-${e.id}-${t}`,children:[t,` value`]}),/* @__PURE__ */ (0,$.jsx)(ir,{className:`any-pointer-coarse:min-h-11 any-pointer-coarse:text-base`,id:`${n}-${e.id}-${t}`,name:t,type:`password`,autoComplete:`off`,required:!0,"aria-describedby":t.toLowerCase()===`authorization`?`${n}-authorization-help`:void 0}),t.toLowerCase()===`authorization`&&/* @__PURE__ */ (0,$.jsx)(Ur,{id:`${n}-authorization-help`,className:`text-xs`,children:`Enter the full value, including Bearer before the token when required.`})]},t)),/* @__PURE__ */ (0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Saved secrets are never shown. Enter every value to replace them.`}),/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`flex gap-2`,children:[/* @__PURE__ */ (0,$.jsx)(qt,{type:`submit`,size:`sm`,className:`any-pointer-coarse:min-h-11 any-pointer-coarse:min-w-11`,children:`Save credentials`}),/* @__PURE__ */ (0,$.jsx)(qt,{type:`button`,size:`sm`,className:`any-pointer-coarse:min-h-11 any-pointer-coarse:min-w-11`,variant:`outline`,onClick:()=>u(null),children:`Cancel`})]})]})}),o&&_&&/* @__PURE__ */ (0,$.jsx)(`p`,{"data-slot":`mcp-notice`,role:p.isError?`alert`:`status`,className:p.isError?`basis-full text-xs text-destructive`:`basis-full text-xs text-muted-foreground`,children:_}),i&&r&&t.unavailableMcpConnections?.includes(r.id)&&/* @__PURE__ */ (0,$.jsx)(`p`,{className:`basis-full text-xs text-muted-foreground`,children:`Unavailable in the last chat. Test the connection or reconnect.`})]},e.id)})]})]})]})})}function np(e){let{loopFocus:t=!0,orientation:n=`both`,grid:r,onLoop:i,direction:a,highlightedIndex:o,onHighlightedIndexChange:s,rootRef:c,enableHomeAndEndKeys:l=!1,stopEventPropagation:u,disabledIndices:d,modifierKeys:f=Mt}=e,[p,m]=Q.useState(0),h=r!=null,g=Q.useRef(null),_=mr(g,c),v=Q.useRef([]),y=Q.useRef(!1),b=Q.useRef(null),x=o??p,S=Hn((e,t=!1)=>{if(b.current=v.current[e]??null,(s??m)(e),t){let t=v.current[e];sd(g.current,t,a,n)}}),C=Hn(e=>{if(e.size===0)return;if(y.current){let e=v.current,t=e.indexOf(b.current);if(t===-1){let t=e[x];!t||dn(e,x,d)?S(rp(e,d)):b.current=t}else t!==x&&S(t);return}y.current=!0;let t=Array.from(e.keys()),r=t.find(e=>e?.hasAttribute(`data-composite-item-active`))??null,i=r?e.get(r)?.index??-1:-1;if(i!==-1)S(i);else if(dn(t,x,d)){let e=Jt(t,{disabledIndices:d});wn(t,e)||S(e)}sd(g.current,r,a,n)});Rn(()=>{if(d==null||o!=null||!y.current)return;let e=v.current;if(dn(e,x,d)){let t=Jt(e,{disabledIndices:d});wn(e,t)||S(t)}},[d,o,x,v,S]);let w=Hn((e,t,n)=>i?i(e,t,n,v):n),T=Hn(e=>{let o=e.key===`Home`||e.key===`End`;if(!rd.has(e.key)||!l&&o||ip(e,f)||!g.current)return;let s=a===`rtl`,c=s?td:nd,p=s?nd:td,m=n===`vertical`?ed:c,_=n===`vertical`?$u:p,y=sn(e.nativeEvent);if(y!=null&&od(y)&&!Cf(y)){let t=y.selectionStart,n=y.selectionEnd,r=y.value;if(t==null||e.shiftKey||t!==n||e.key!==_&&t<r.length||e.key!==m&&t>0)return}let b=x,C=$t(v,d),T=fr(v,d);r!=null&&(b=r({disabledIndices:d,elementsRef:v,event:e,highlightedIndex:x,loopFocus:t,maxIndex:T,minIndex:C,onLoop:w,orientation:n,rtl:s}));let E=n!==`vertical`&&e.key===c||n!==`horizontal`&&e.key===`ArrowDown`,D=n!==`vertical`&&e.key===p||n!==`horizontal`&&e.key===`ArrowUp`;l&&(e.key===`Home`?b=C:e.key===`End`&&(b=T)),b===x&&(E||D)&&(t&&b===T&&E?(b=C,i&&(b=i(e,x,b,v))):t&&b===C&&D?(b=T,i&&(b=i(e,x,b,v))):b=Jt(v.current,{startingIndex:b,decrement:D,disabledIndices:d})),b!==x&&!wn(v.current,b)&&(u&&e.stopPropagation(),(h||o||E||D)&&e.preventDefault(),S(b,!0),queueMicrotask(()=>{v.current[b]?.focus()}))});return{props:{ref:_,onFocus(e){let t=g.current,n=sn(e.nativeEvent);t&&n!=null&&od(n)&&n.setSelectionRange(0,n.value.length)},onKeyDown:T},highlightedIndex:x,onHighlightedIndexChange:S,elementsRef:v,onMapChange:C,relayKeyboardEvent:T}}function rp(e,t){let n=-1;for(let r=0;r<e.length;r+=1){let i=e[r];if(i&&!dn(e,r,t)){if(i.hasAttribute(`data-composite-item-active`))return r;n===-1&&(n=r)}}return Math.max(n,0)}function ip(e,t){for(let n of id)if(!t.includes(n)&&e.getModifierState(n))return!0;return!1}function ap(e){let{render:t,className:n,style:r,refs:i=Mt,props:a=Mt,state:o=zn,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}=np({grid:d,loopFocus:f,onLoop:p,orientation:u,highlightedIndex:c,onHighlightedIndexChange:l,rootRef:_,stopEventPropagation:g,enableHomeAndEndKeys:m,direction:gr(),disabledIndices:v,modifierKeys:y}),k=Cn(x,e,{state:o,ref:i,props:[C,...a,S],stateAttributesMapping:s}),j=Q.useMemo(()=>({highlightedIndex:w,onHighlightedIndexChange:T,highlightItemOnHover:b,relayKeyboardEvent:O}),[w,T,b,O]);return/*#__PURE__*/ (0,$.jsx)(_r.Provider,{value:j,children:/*#__PURE__*/ (0,$.jsx)(A,{elementsRef:E,onMapChange:e=>{h?.(e),D(e)},children:k})})}const op=/*#__PURE__*/ Q.createContext(void 0);function sp(){let e=Q.useContext(op);if(e===void 0)throw Error(er(64));return e}const cp={tabActivationDirection:e=>({"data-activation-direction":e})},lp=/*#__PURE__*/ 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(()=>/* @__PURE__ */ new Map),[m,h]=y({controlled:s,default:r,name:`Tabs`,state:`value`}),g=s!==void 0,[_,v]=Q.useState(()=>/* @__PURE__ */ new Map),b=Q.useRef(void 0),x=Q.useCallback(e=>up(_,e),[_]),[S,C]=Q.useState(()=>({previousValue:m,tabActivationDirection:`none`})),{previousValue:w,tabActivationDirection:T}=S,E=T,D=!1;w!==m&&(E=dp(w,m,a,_),D=w!=null&&m!=null&&x(m)==null);let O=D?w:m,k=w!==O||T!==E;Rn(()=>{k&&C({previousValue:O,tabActivationDirection:E})},[O,k,E]);let j=Hn((e,t)=>{t.activationDirection=dp(m,e,a,_),i?.(e,t),t.isCanceled||h(()=>e)}),M=Hn((e,t)=>{i?.(e,gn(t,void 0,void 0,{activationDirection:`none`}))}),N=Hn((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})})),P=Q.useCallback(e=>f.get(e),[f]),F=Q.useCallback(e=>{for(let t of _.values())if(e===t.value)return t.id},[_]),ee=Q.useMemo(()=>({getTabElementBySelectedValue:x,getTabIdByPanelValue:F,getTabPanelIdByValue:P,onValueChange:j,orientation:a,registerMountedTabPanel:N,setTabMap:v,tabActivationDirection:E,value:m}),[x,F,P,j,a,N,v,E,m]),I=Q.useMemo(()=>{for(let e of _.values())if(e.value===m)return e},[_,m]),L=Q.useMemo(()=>{for(let e of _.values())if(!e.disabled)return e.value},[_]),R=Q.useRef(!u),z=Q.useRef(r),te=Q.useRef(u),ne=Q.useRef(!1);Rn(()=>{if(g)return;function e(e,t){h(()=>e),C({previousValue:e,tabActivationDirection:`none`}),M(e,t),R.current=!1}if(_.size===0){ne.current&&m!==null&&!b.current?.isConnected&&e(null,Dn);return}ne.current=!0,b.current=_.keys().next().value;let t=I?.disabled,n=I==null&&m!==null;if(!t&&m===z.current&&(te.current=!1),te.current&&t&&m===z.current)return;let r=R.current;if(t||n){let n=L??null;if(m===n){R.current=!1;return}let i=Dn;r?i=Sr:t&&(i=sr),e(n,i)}else r&&I!=null&&(M(m,Sr),R.current=!1)},[L,g,M,I,h,_,m]);let B=Cn(`div`,e,{state:{orientation:a,tabActivationDirection:E},ref:t,props:l,stateAttributesMapping:cp});return/*#__PURE__*/ (0,$.jsx)(op.Provider,{value:ee,children:/*#__PURE__*/ (0,$.jsx)(A,{elementsRef:d,children:B})})});function up(e,t){for(let[n,r]of e.entries())if(t===r.value)return n;return null}function dp(e,t,n,r){if(e==null||t==null)return`none`;let[i,a,o]=n===`horizontal`?[`left`,`left`,`right`]:[`top`,`up`,`down`],s=up(r,e),c=up(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 fp=/*#__PURE__*/ Q.createContext(void 0);function pp(){let e=Q.useContext(fp);if(e===void 0)throw Error(er(65));return e}const mp=/*#__PURE__*/ Q.forwardRef(function(e,t){let{className:n,disabled:r=!1,render:i,value:a,id:o,nativeButton:s=!0,style:c,...l}=e,{value:u,getTabPanelIdByValue:d,onValueChange:f,orientation:p,tabActivationDirection:m}=sp(),{activateOnFocus:h,registerTabResizeObserverElement:g,tabsListElement:_}=pp(),{highlightedIndex:v,onHighlightedIndexChange:y}=Pn(),b=tn(o),{compositeProps:x,compositeRef:S,index:C}=mf({metadata:Q.useMemo(()=>({disabled:r,id:b,value:a}),[r,b,a])}),w=a===u,T=Q.useRef(!1),E=Q.useRef(null),D=Hn(e=>{E.current?.(),E.current=e?g(e):null});Rn(()=>{if(T.current){T.current=!1;return}if(!(w&&C>-1&&v!==C))return;let e=_;if(e!=null){let t=mn(or(e));if(t&&Bt(e,t))return}r||y(C)},[w,C,v,y,r,_]);let{getButtonProps:O,buttonRef:k}=Kn({disabled:r,native:s,focusableWhenDisabled:!0}),A=d(a),j=Q.useRef(!1),M=Q.useRef(!1);function N(e){f(a,gn(wr,e.nativeEvent,void 0,{activationDirection:`none`}))}function P(e){w||r||N(e)}function F(e){w||r||h&&(!j.current||M.current)&&N(e)}function ee(e){if(w||r)return;j.current=!0,M.current=e.button===0;let t=or(e.currentTarget);function n(){j.current=!1,M.current=!1,t.removeEventListener(`pointerup`,n),t.removeEventListener(`pointercancel`,n)}t.addEventListener(`pointerup`,n),t.addEventListener(`pointercancel`,n)}return Cn(`button`,e,{state:{disabled:r,active:w,orientation:p,tabActivationDirection:m},ref:[t,k,S,D],props:[x,{role:`tab`,"aria-controls":A,"aria-selected":w,id:b,onClick:P,onFocus:F,onPointerDown:ee,"data-composite-item-active":w?``:void 0,onKeyDownCapture(){T.current=!0}},l,O],stateAttributesMapping:cp})}),hp={...cp,...Cr},gp=/*#__PURE__*/ 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}=sp(),p=tn(),{ref:m,index:h}=N(),g=r===c,{mounted:_,transitionStatus:v,setMounted:y}=Ft(g),b=!_,x=l(r),S={hidden:b,orientation:u,tabActivationDirection:d,transitionStatus:v},C=Q.useRef(null),w=Cn(`div`,e,{state:S,ref:[t,m,C],props:[{"aria-labelledby":x,hidden:b,id:p,role:`tabpanel`,tabIndex:g?0:-1,inert:at(!g),"data-index":h},s],stateAttributesMapping:hp});return Xn({open:g,ref:C,onComplete(){g||y(!1)}}),Rn(()=>{if(!(p==null||b&&!a))return f(r,p)},[b,a,r,p,f]),a||_?w:null}),_p=/*#__PURE__*/ 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}=sp(),[d,f]=Q.useState(0),[p,m]=Q.useState(null),h=Q.useRef(/* @__PURE__ */ new Set),g=Q.useRef(/* @__PURE__ */ new Set),_=Q.useRef(null);Rn(()=>{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=Hn(e=>(h.current.add(e),()=>{h.current.delete(e)})),y=Hn(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/*#__PURE__*/ (0,$.jsx)(fp.Provider,{value:S,children:/*#__PURE__*/ (0,$.jsx)(ap,{render:a,className:r,style:o,state:b,refs:[t,m],props:[x,s],stateAttributesMapping:cp,highlightedIndex:d,enableHomeAndEndKeys:!0,loopFocus:i,orientation:c,onHighlightedIndexChange:f,onMapChange:l,disabledIndices:Mt})})});function vp(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 yp(e){let t=/* @__PURE__ */ new Date,n=[];for(let r of e){let e=vp(r.updatedAt,t),i=n.at(-1);i?.value===e?i.items.push(r):n.push({value:e,items:[r]})}return n}const bp=e=>e.title||`Untitled`,xp=e=>e.stopPropagation();function Sp({chat:e,state:t,onSelect:n,onDelete:r}){let i=(0,Q.useRef)(null),[a,o]=(0,Q.useState)(null),s=(0,Q.useRef)(null),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(!1),[h,_]=(0,Q.useState)(),[v]=Ye(l.trim(),{wait:300}),[y]=(0,Q.useState)(()=>new Tt);(0,Q.useEffect)(()=>(y.mount(),()=>{y.unmount(),y.clear()}),[y]);let b=t.auth.status===`ready`,x=ve({queryKey:[`thread-history`,v],enabled:d&&b&&!p,initialPageParam:void 0,queryFn:({signal:t,pageParam:n})=>e.searchThreads(v,n,t).catch(e=>{throw P(e)&&[401,403,404].includes(e.status)&&m(!0),e}),getNextPageParam:e=>e.page_after??void 0,retry:!1,staleTime:3e4,gcTime:3e5},y),S=t.thread?.id,C=t.thread?.version,w=t.status===`submitted`||t.status===`streaming`;(0,Q.useEffect)(()=>{(t.auth.status===`error`||p)&&y.removeQueries({queryKey:[`thread-history`]})},[y,t.auth.status,p]),(0,Q.useEffect)(()=>{w||y.invalidateQueries({queryKey:[`thread-history`]})},[y,S,C,w]);let T=!p&&(l.trim()!==v||x.isPending),E=p||!T&&x.isError;nt({list:c,enabled:d&&!T,query:x});let D=!b||p||T?[]:yp(x.data?.pages.flatMap(e=>e.items)??[]);return/* @__PURE__ */ (0,$.jsxs)(`div`,{ref:s,"data-slot":`thread-history`,children:[a&&/* @__PURE__ */ (0,$.jsx)(Sd,{title:bp(a),container:s,finalFocus:i,onClose:()=>o(null),onDelete:async()=>{let t=await e.deleteThread(a);return t&&(r(a.id),y.invalidateQueries({queryKey:[`thread-history`]})),t}}),/* @__PURE__ */ (0,$.jsxs)(pt,{open:d,items:D,filteredItems:D,value:null,onValueChange:t=>{t&&t.id!==S&&e.openThread(t.id).then(n)},itemToStringLabel:bp,itemToStringValue:e=>e.id,isItemEqualToValue:(e,t)=>e.id===t.id,onInputValueChange:(e,t)=>{u(t.reason===`input-change`?e:``)},onOpenChange:e=>{f(e),e?(m(!1),_(s.current?.closest(`[data-slot="chat"]`)??void 0)):u(``)},children:[/* @__PURE__ */ (0,$.jsx)(Ne,{ref:i,render:/* @__PURE__ */ (0,$.jsx)(K,{tooltip:`Show older chats`,variant:`ghost`,size:`icon-sm`,disabled:!b}),children:/* @__PURE__ */ (0,$.jsx)(_u,{})}),/* @__PURE__ */ (0,$.jsxs)(st,{container:s,collisionBoundary:h,align:`end`,"aria-label":`Chat history`,"aria-busy":T||x.isFetching?!0:void 0,className:`w-80 min-w-0`,children:[/* @__PURE__ */ (0,$.jsx)(et,{"aria-label":`Search chats`,placeholder:`Search chats…`,maxLength:255,showTrigger:!1}),/* @__PURE__ */ (0,$.jsx)(ht,{className:`text-center text-sm text-muted-foreground [&:not(:empty)]:py-2`,children:!E&&(T||x.isFetchingNextPage)?`Loading…`:null}),/* @__PURE__ */ (0,$.jsx)(Le,{children:b&&!T&&!E?`No chats found.`:null}),/* @__PURE__ */ (0,$.jsx)(Ke,{ref:c,className:`max-h-[min(24rem,calc(var(--available-height)---spacing(9)))]`,children:e=>/* @__PURE__ */ (0,$.jsxs)(be,{items:e.items,children:[/* @__PURE__ */ (0,$.jsx)(Te,{children:e.value}),/* @__PURE__ */ (0,$.jsx)(Ze,{children:e=>{let t=e.id===S;return/* @__PURE__ */ (0,$.jsxs)(ut,{value:e,"aria-label":bp(e),"aria-current":t?`true`:void 0,className:Qt(`group/thread ps-2 pe-1 any-pointer-coarse:min-h-11`,t&&`bg-muted font-semibold`),children:[/* @__PURE__ */ (0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:bp(e)}),e.role===`manager`&&/* @__PURE__ */ (0,$.jsx)(K,{variant:`ghost`,size:`icon-xs`,"aria-label":`Delete ${bp(e)}`,tooltip:`Delete chat`,disabled:t&&w,className:`opacity-0 group-hover/thread:opacity-100 group-data-highlighted/thread:opacity-100 focus-visible:opacity-100 any-pointer-coarse:opacity-100`,onPointerDown:xp,onMouseDown:xp,onClick:t=>{t.stopPropagation(),f(!1),o(e)},children:/* @__PURE__ */ (0,$.jsx)(Fr,{})})]},e.id)}})]},e.value)}),E&&/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`p-2 text-xs`,role:`alert`,children:[`Could not load chats.`,/* @__PURE__ */ (0,$.jsx)(K,{variant:`ghost`,size:`icon-sm`,tooltip:`Retry`,disabled:x.isFetching,onClick:()=>void(!p&&x.isFetchNextPageError?x.fetchNextPage():x.refetch()).then(e=>{e.isSuccess&&m(!1)}),children:/* @__PURE__ */ (0,$.jsx)(g,{})})]})]})]})]})}function Cp({className:e,orientation:t=`horizontal`,...n}){return/* @__PURE__ */ (0,$.jsx)(lp,{"data-slot":`tabs`,"data-orientation":t,className:Qt(`group/tabs flex gap-2 data-horizontal:flex-col`,e),...n})}const wp=Sn(`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 Tp({className:e,variant:t=`default`,...n}){return/* @__PURE__ */ (0,$.jsx)(_p,{"data-slot":`tabs-list`,"data-variant":t,className:Qt(wp({variant:t}),e),...n})}function Ep({className:e,...t}){return/* @__PURE__ */ (0,$.jsx)(mp,{"data-slot":`tabs-trigger`,className:Qt(`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 Dp({className:e,...t}){return/* @__PURE__ */ (0,$.jsx)(gp,{"data-slot":`tabs-content`,className:Qt(`flex-1 text-sm outline-none`,e),...t})}const Op=/* @__PURE__ */ new Set([`c`,`cpp`,`css`,`go`,`html`,`js`,`json`,`jsx`,`mjs`,`py`,`rb`,`rs`,`sh`,`sql`,`toml`,`ts`,`tsx`,`yaml`,`yml`]);function kp(e){let t=e.slice(e.lastIndexOf(`.`)+1).toLowerCase();return Op.has(t)?/* @__PURE__ */ (0,$.jsx)(Su,{}):t===`csv`||t===`tsv`?/* @__PURE__ */ (0,$.jsx)(Cu,{}):/* @__PURE__ */ (0,$.jsx)(He,{})}function Ap(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function jp({file:e}){return/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`flex items-start gap-1`,children:[/* @__PURE__ */ (0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:/* @__PURE__ */ (0,$.jsx)(Dt,{icon:kp(e.path),label:/* @__PURE__ */ (0,$.jsxs)($.Fragment,{children:[/* @__PURE__ */ (0,$.jsx)(`span`,{className:`font-mono wrap-anywhere`,children:e.label}),/* @__PURE__ */ (0,$.jsxs)(`span`,{className:`text-muted-foreground`,children:[` · `,e.lines===1?`1 line`:`${e.lines} lines`]})]}),children:/* @__PURE__ */ (0,$.jsx)(`div`,{className:`flex min-w-0 flex-col`,children:/* @__PURE__ */ (0,$.jsx)(le,{emptyLabel:`Empty file`,caption:e.label===e.path?void 0:e.path,language:e.path.split(`.`).at(-1),children:e.content})})})}),/* @__PURE__ */ (0,$.jsx)(K,{variant:`ghost`,size:`icon-sm`,"aria-label":`Download ${e.label}`,tooltip:`Download file`,onClick:()=>Xe(Ap(e.path),e.content),children:/* @__PURE__ */ (0,$.jsx)(bu,{})})]})}function Mp({run:e}){let t=e.timedOut||e.exitCode!==void 0&&e.exitCode!==0;return/* @__PURE__ */ (0,$.jsx)(Dt,{icon:/* @__PURE__ */ (0,$.jsx)(i,{}),running:!e.finished,failed:t,label:/* @__PURE__ */ (0,$.jsxs)($.Fragment,{children:[/* @__PURE__ */ (0,$.jsx)(`span`,{className:`font-mono wrap-anywhere`,children:e.command}),e.finished&&/* @__PURE__ */ (0,$.jsx)(`span`,{className:Qt(`ms-1`,t?`text-destructive`:`text-muted-foreground`),children:k(e)})]}),children:/* @__PURE__ */ (0,$.jsx)(`div`,{className:`flex min-w-0 flex-col`,children:/* @__PURE__ */ (0,$.jsx)(a,{run:e})})})}function Np({activity:e}){let t=(0,Q.useRef)(null),n=e.files.length,r=e.commands.length;return/* @__PURE__ */ (0,$.jsx)(`div`,{ref:t,className:`w-full`,children:/* @__PURE__ */ (0,$.jsxs)(Qf,{children:[/* @__PURE__ */ (0,$.jsxs)($f,{render:/* @__PURE__ */ (0,$.jsx)(qt,{variant:`outline`,size:`sm`,className:`group w-full justify-start rounded-full bg-muted/50 text-xs text-muted-foreground any-pointer-coarse:min-h-11 any-pointer-coarse:min-w-11`}),children:[/* @__PURE__ */ (0,$.jsx)(vu,{}),/* @__PURE__ */ (0,$.jsxs)(`span`,{className:`flex-1 text-start`,children:[`Sandbox · `,n,` `,n===1?`file`:`files`,` · `,r,` `,r===1?`command`:`commands`]}),/* @__PURE__ */ (0,$.jsx)(gu,{className:`transition-transform group-aria-expanded:rotate-180`})]}),/* @__PURE__ */ (0,$.jsx)(ep,{container:t,side:`top`,sideOffset:4,"aria-label":`Sandbox files and command history`,className:`max-h-[min(20rem,var(--available-height))] w-(--anchor-width) max-w-(--available-width) gap-0 overflow-hidden p-0`,children:/* @__PURE__ */ (0,$.jsxs)(Cp,{defaultValue:`files`,className:`flex min-h-0 flex-col gap-0`,children:[/* @__PURE__ */ (0,$.jsxs)(Tp,{variant:`line`,className:`w-full shrink-0 px-2 any-pointer-coarse:h-auto any-pointer-coarse:[&_[data-slot=tabs-trigger]]:min-h-11 any-pointer-coarse:[&_[data-slot=tabs-trigger]]:min-w-11`,children:[/* @__PURE__ */ (0,$.jsxs)(Ep,{value:`files`,children:[/* @__PURE__ */ (0,$.jsx)(He,{}),`Files`,n>0&&/* @__PURE__ */ (0,$.jsx)(`span`,{className:`text-muted-foreground`,children:n})]}),/* @__PURE__ */ (0,$.jsxs)(Ep,{value:`log`,children:[/* @__PURE__ */ (0,$.jsx)(i,{}),`Log`,r>0&&/* @__PURE__ */ (0,$.jsx)(`span`,{className:`text-muted-foreground`,children:r})]})]}),/* @__PURE__ */ (0,$.jsx)(Dp,{value:`files`,className:`min-h-0 overflow-y-auto px-2 py-1`,children:n===0?/* @__PURE__ */ (0,$.jsx)(Pp,{children:`The agent has not written any files yet.`}):e.files.map(e=>/* @__PURE__ */ (0,$.jsx)(jp,{file:e},e.toolCallId))}),/* @__PURE__ */ (0,$.jsx)(Dp,{value:`log`,className:`min-h-0 overflow-y-auto px-2 py-1`,children:r===0?/* @__PURE__ */ (0,$.jsx)(Pp,{children:`The agent has not run any commands yet.`}):e.commands.map(e=>/* @__PURE__ */ (0,$.jsx)(Mp,{run:e},e.toolCallId))})]})})]})})}function Pp({children:e}){return/* @__PURE__ */ (0,$.jsx)(`p`,{className:`px-1 py-2 text-xs text-muted-foreground italic`,children:e})}function Fp({status:e}){if(e===`ready`)return null;let t=e===`starting`;return/* @__PURE__ */ (0,$.jsxs)(de,{role:`status`,className:`w-full rounded-full border bg-muted/50 px-3 py-1.5`,children:[/* @__PURE__ */ (0,$.jsx)(E,{children:t?/* @__PURE__ */ (0,$.jsx)(se,{}):/* @__PURE__ */ (0,$.jsx)(Ge,{})}),/* @__PURE__ */ (0,$.jsx)(_,{className:t?`shimmer`:void 0,children:t?`Starting the sandbox…`:`The sandbox could not be started`})]})}const Ip=[`header`,`headerActions`,`empty`,`composerActions`];function Lp(e){return`${we}${e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}function Rp(e,t,n){let[r,i]=(0,Q.useState)(/* @__PURE__ */ new Set),a=(0,Q.useRef)(/* @__PURE__ */ new Map);return(0,Q.useEffect)(()=>{for(let r of Ip){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=Lp(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}const zp=[],Bp={text:``,attachments:zp,settledAttachments:zp,savedAttachments:zp,attachmentsLoaded:!1,storageError:!1},Vp=(e,t)=>e&&t?`${e}\n\n${t}`:e||t,Hp=(e,t,n)=>({...Bp,text:Z(e,t,n)});function Up({apiUrl:e,verifiedIdentity:t,threadId:n,canLoad:r,debug:i}){let[a,o]=(0,Q.useState)({apiUrl:e,identity:``,threads:/* @__PURE__ */ new Map}),s=t??a.identity;(a.apiUrl!==e||a.identity!==s)&&o({apiUrl:e,identity:s,threads:/* @__PURE__ */ new Map});let c=a.threads.get(n)??Hp(e,s,n),l=(0,Q.useCallback)((t,n)=>o(r=>{if(r.apiUrl!==e||r.identity!==s)return r;let i=r.threads.get(t)??Hp(e,s,t),a=n(i,r.threads);if(a===i)return r;let o=new Map(r.threads);return a?o.set(t,a):o.delete(t),{...r,threads:o}}),[e,s]);(0,Q.useEffect)(()=>{if(!r||c.attachmentsLoaded)return;let t=!1;return Il({apiUrl:e,identity:s,threadId:n}).then(e=>({attachments:e,storageError:!1}),()=>({attachments:zp,storageError:!0})).then(({attachments:r,storageError:i})=>{if(t)return;let a=Z(e,s,n,void 0,`sent`),o=Vp(a,Z(e,s,n));a&&(Z(e,s,n,o),Z(e,s,n,``,`sent`)),l(n,(e,t)=>{if(e.attachmentsLoaded)return e;let s=e.attachments.filter(e=>!r.some(t=>t.id===e.id));return{...e,text:t.has(n)?Vp(a,e.text):o,attachments:s.length?[...r,...s]:r,settledAttachments:r,savedAttachments:r,attachmentsLoaded:!0,storageError:i}})}),()=>{t=!0}},[e,s,n,r,c.attachmentsLoaded,l]);let u=(0,Q.useRef)(/* @__PURE__ */ new Set);(0,Q.useEffect)(()=>{for(let[e,t]of a.threads){if(!t.attachmentsLoaded||t.attachments===t.settledAttachments)continue;let n=JSON.stringify([a.apiUrl,a.identity,e]);if(u.current.has(n))continue;u.current.add(n);let r=r=>{u.current.delete(n),l(e,(n,i)=>i.has(e)?{...n,settledAttachments:t.attachments,savedAttachments:r?n.savedAttachments:t.attachments,storageError:r}:n)};Il({apiUrl:a.apiUrl,identity:a.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))}},[a,l]);let d=t=>{Z(e,s,t,``),Z(e,s,t,``,`sent`),Il({apiUrl:e,identity:s,threadId:t,update:()=>[]}).catch(e=>i?.(`error`,`Draft files could not be cleared`,e)),l(t,()=>void 0)},f=(t,n)=>{let r=new Set(t.map(e=>e.id)),a=n;return{onThreadReady:t=>{if(a===``){a=t;for(let n of[`draft`,`sent`]){let r=Z(e,s,``,void 0,n);r&&Z(e,s,t,r,n),Z(e,s,``,``,n)}Il({apiUrl:e,identity:s,threadId:``,moveTo:t}).catch(e=>i?.(`error`,`Draft files could not be moved`,e)),l(t,(e,n)=>{let r=n.get(``),i=n.get(t);return r?{...r,text:r.text||i?.text||``,attachments:[...new Map([...i?.attachments??[],...r.attachments].map(e=>[e.id,e])).values()],settledAttachments:zp,savedAttachments:[...i?.savedAttachments??[],...r.savedAttachments]}:e}),l(``,()=>void 0)}},onAccepted:()=>{Z(e,s,a,``,`sent`),Il({apiUrl:e,identity:s,threadId:a,update:e=>e.filter(e=>!r.has(e.id))}).catch(e=>i?.(`error`,`Accepted draft files could not be cleared`,e))},restore:n=>{let r=typeof n==`string`?n:n.content,i=typeof r==`string`?r:r.flatMap(e=>e.type===`text`?[e.content]:[]).join(``);Z(e,s,a,Vp(i,Z(e,s,a))),Z(e,s,a,``,`sent`),l(a,e=>({...e,text:Vp(i,e.text),attachments:[...t.filter(t=>!e.attachments.some(e=>e.id===t.id)),...e.attachments]}))}}};return{identity:s,text:c.text,attachments:c.attachments,attachmentsLoaded:c.attachmentsLoaded,saving:c.attachments!==c.settledAttachments,storageError:c.storageError,setText:t=>{Z(e,s,n,t),l(n,e=>({...e,text:t}))},updateAttachments:e=>l(n,t=>({...t,attachments:e(t.attachments)})),settleAttachment:(t,n)=>o(r=>{if(r.apiUrl!==e||r.identity!==s)return r;for(let[e,i]of r.threads){if(!i.attachments.some(e=>e.id===t))continue;let a=i.attachments.map(e=>e.id===t?{...e,...n}:e);return{...r,threads:new Map(r.threads).set(e,{...i,attachments:a})}}return r}),submit:t=>{let r=new Set(t.map(e=>e.id));Z(e,s,n,c.text,`sent`),Z(e,s,n,``);let i=e=>e.filter(e=>!r.has(e.id));return l(n,e=>{let t=i(e.attachments);return{...e,text:``,attachments:t,settledAttachments:e.settledAttachments===e.attachments?t:i(e.settledAttachments),savedAttachments:i(e.savedAttachments)}}),f(t,n)},reset:()=>l(``,()=>({...Bp,attachmentsLoaded:!0})),forget:e=>d(e)}}function Wp(e,t,n){let[r,i]=(0,Q.useState)(/* @__PURE__ */ new Map),a=(0,Q.useRef)(/* @__PURE__ */ 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(yt(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=Fe(l.current,e);if(!f)throw Error(`Unknown widget "${e}"`);if(!c.current)throw Error(`The chat is no longer mounted`);let p=yt(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])=>Fe(e,t)));return n.size===t.size?t:n})),(0,Q.useEffect)(()=>{let t=o(t=>!Fe(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 Gp={},Kp=[];function qp({chat:e,options:t,host:n}){let r=(0,Q.useId)(),i=(0,Q.useSyncExternalStore)(e.subscribe,e.getState,e.getState),a=e.getOptions(),o=Ru({...t,agentId:a.agentId},n),s=!!t.onClose,c=t.widgets??Gp,l=(0,Q.useMemo)(()=>At(a.debug),[a.debug]),{activeSlots:u,renderWidget:d}=Wp(c,n,l),f=Rp(t.slots,n,l),p=(0,Q.useMemo)(()=>({getThreadAttachment:e.getThreadAttachment,threadId:i.thread?.id}),[e,i.thread?.id]),{messages:m,status:h,auth:_,capabilities:v,sandbox:y,sandboxStatus:b,agentTools:x}=i,{history:S,submission:C}=i,w=i.usageLimitReached,T=w?Error(it(w)):C?.phase===`failed`||C?.phase===`refused`?C.error:i.error,E=(0,Q.useMemo)(()=>new Set(x.map(e=>e.name)),[x]),D=(0,Q.useMemo)(()=>{let e=new Set(i.activeToolCallIds);if(_.status===`ready`&&i.thread?.role!==`viewer`)for(let t of i.pendingInteractions)t.targetTenantUserId===_.currentUser.user.id&&m.some(e=>e.parts.some(e=>e.type===`tool-call`&&e.id===t.toolCallId&&e.name===`ask_questionnaire`))&&e.add(t.toolCallId);return[...e].join(`
26
- `)},[i.activeToolCallIds,i.pendingInteractions,i.thread?.role,_,m]),O=(0,Q.useMemo)(()=>new Set(D?D.split(`
27
- `):[]),[D]),k=(0,Q.useMemo)(()=>{let e={...i.serverToolTitles};for(let t of x)t.title!==void 0&&(e[t.name]=t.title);return e},[x,i.serverToolTitles]);(0,Q.useEffect)(()=>{l?.(`mount`,`tool set declared to the agent`,{tools:[...E],widgets:Object.keys(c)})},[l,E,c]);let A=a.apiUrl??`https://astralbeam.ai/api`,j=y.files.length>0||y.commands.length>0;(0,Q.useEffect)(()=>{l?.(`status`,`chat status is "${h}"`)},[l,h]);let M=Up({apiUrl:A,verifiedIdentity:_.status===`ready`?JSON.stringify([ce(_.currentUser),Qe(a)]):void 0,threadId:i.thread?.id??``,canLoad:_.status===`ready`&&(S===`idle`||S===`failed`),debug:l}),N=M.identity,P=(0,Q.useMemo)(()=>_t(v.attachments&&M.attachmentsLoaded?t.attachments:!1),[t.attachments,v.attachments,M.attachmentsLoaded]),F=[];for(let e of P.enabled?M.attachments:Kp){if(e.status===`error`){F.push(e);continue}let[t]=G({files:[{name:e.name,size:e.size,type:e.mimeType}],existing:F,limits:P,createId:()=>e.id});F.push(t.draft.status===`error`?t.draft:e)}let ee=h===`submitted`||h===`streaming`,I=ee&&!ue(m),R=_.status===`loading`,z=_.status===`error`?_.error:void 0,re=R||z!==void 0||ee||!M.attachmentsLoaded||M.saving||S===`loading`||S===`failed`||i.thread?.role===`viewer`||i.thread?.agentId===null||kt(m.map(e=>({...e,parts:e.parts.filter(e=>e.type!==`tool-call`||O.has(e.id))})),E),ie=t=>{let n=G({files:t,existing:F,limits:P,createId:Re});M.updateAttachments(e=>[...e,...n.map(({draft:e})=>e)]);for(let{draft:t,file:r}of n){if(t.status===`error`){l?.(`attachment`,`rejected "${t.name}"`,{reason:t.error,size:t.size,type:r.type});continue}l?.(`attachment`,`attached "${t.name}"`,{kind:t.kind,mimeType:t.mimeType,size:t.size});let n=Je(r);e.uploadAttachment({data:n,filename:t.name,mimeType:t.mimeType}).then(e=>{M.settleAttachment(t.id,{status:`ready`,fileId:e.fileId,mimeType:e.mimeType,size:e.byteSize})}).catch(e=>{l?.(`error`,`attachment "${t.name}" could not be uploaded`,e),M.settleAttachment(t.id,{status:`error`,error:`The file could not be uploaded`})})}},V=e=>{l?.(`attachment`,`attachment removed`,{id:e}),M.updateAttachments(t=>t.filter(t=>t.id!==e))},ae=()=>{let t=M.text.trim(),n=De(F),r=F.some(e=>e.status===`reading`);if(re||r||t.length===0&&n.length===0)return;l?.(`send`,t.length>0?t:`${n.length} attachment(s), no message text`,n.length===0?void 0:{attachments:F.filter(e=>e.status===`ready`).map(e=>({name:e.name,kind:e.kind,size:e.size}))});let{restore:i,...a}=M.submit(F.filter(e=>e.status===`ready`));e.sendMessage(n.length===0?t:{content:[...n,...t.length>0?[{type:`text`,content:t}]:[]]},a).then(e=>{e.phase===`refused`&&i(e.content)})},oe=(0,Q.useCallback)((t,n)=>{l?.(`questionnaire`,`answers submitted`,{toolCallId:t,answers:n}),e.addToolResult({toolCallId:t,tool:ne,output:{answers:n}})},[e,l]),H=(0,Q.useRef)(void 0),U={widgets:c,onRenderWidget:d,onReset:()=>{let t=e.getState().auth;t.status===`ready`&&M.identity===JSON.stringify([ce(t.currentUser),Qe(e.getOptions())])&&M.reset()}},se=(0,Q.useRef)(U);(0,Q.useEffect)(()=>{se.current=U,H.current?.update(U)}),(0,Q.useEffect)(()=>{let t=e.attachView(se.current);return H.current=t,()=>{H.current=void 0,t.dispose()}},[e]);let le=()=>requestAnimationFrame(()=>n.shadowRoot?.querySelector(`textarea`)?.focus()),de=t.showHeader!==!1,fe=t.onClose&&/* @__PURE__ */ (0,$.jsx)(K,{variant:`ghost`,size:`icon-sm`,tooltip:`Close chat`,onClick:e=>{e.detail<2&&t.onClose?.()},children:/* @__PURE__ */ (0,$.jsx)(L,{})}),pe=/* @__PURE__ */ (0,$.jsxs)(Gr,{id:r,"data-slot":`chat`,"data-closable":s,className:`relative h-full w-full gap-0 overflow-clip rounded-none bg-background pt-0 text-foreground ring-0 [--card-spacing:--spacing(3)]`,children:[/* @__PURE__ */ (0,$.jsx)(Fu,{sizing:o,panelId:r}),de&&/* @__PURE__ */ (0,$.jsxs)(Vr,{className:`flex h-14 shrink-0 items-center gap-1 border-b py-0 [.border-b]:pb-0`,children:[/* @__PURE__ */ (0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:f.has(`header`)?/* @__PURE__ */ (0,$.jsx)(`slot`,{name:Lp(`header`)}):/* @__PURE__ */ (0,$.jsx)(Rr,{className:`truncate`,children:t.title??`AstralBeam`})}),/* @__PURE__ */ (0,$.jsx)(tp,{chat:e,state:i},`mcp:${A}:${N}`),/* @__PURE__ */ (0,$.jsx)(Sp,{chat:e,state:i,onDelete:M.forget,onSelect:le},`${A}:${N}`),/* @__PURE__ */ (0,$.jsx)(K,{variant:`ghost`,size:`icon-sm`,tooltip:`New chat`,disabled:!i.thread&&m.length===0,onClick:t=>{t.detail>1||(e.reset(),le())},children:/* @__PURE__ */ (0,$.jsx)(wu,{})}),f.has(`headerActions`)&&/* @__PURE__ */ (0,$.jsx)(`slot`,{name:Lp(`headerActions`)}),fe]}),!de&&/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`flex justify-end px-2`,children:[/* @__PURE__ */ (0,$.jsx)(tp,{chat:e,state:i},`mcp:${A}:${N}`),fe]}),!!i.unavailableMcpConnections?.length&&/* @__PURE__ */ (0,$.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-xs text-muted-foreground`,children:`Some connected tools are unavailable. Open MCP connections to review them.`}),t.showConversationTitle===!0&&i.thread?.title&&/* @__PURE__ */ (0,$.jsx)(kf,{chat:e,state:i,thread:i.thread,onDelete:e=>{M.forget(e),le()}},`${A}:${N}:${i.thread.id}`),/* @__PURE__ */ (0,$.jsx)(Mr,{className:`min-h-0 flex-1 overflow-hidden p-0`,children:/* @__PURE__ */ (0,$.jsx)(B,{readOnly:i.thread?.role===`viewer`,messages:m,currentTenantUserId:_.status===`ready`?_.currentUser.user.id:void 0,hasOlder:i.messagesCursor!==void 0,loadingHistory:S===`loading`,loadingOlder:i.olderMessagesLoading,onLoadOlder:e.loadOlderMessages,emptySlot:f.has(`empty`)?Lp(`empty`):void 0,emptyHeadline:t.emptyHeadline,emptyDescription:t.emptyDescription,widgets:c,toolTitles:k,serverToolTitles:i.serverToolTitles,streaming:h===`streaming`,activeSlots:u,interactiveToolIds:O,isBusy:re,awaitingReply:I,onQuestionnaireAnswers:oe})}),/* @__PURE__ */ (0,$.jsxs)(Nr,{className:`flex-col gap-1 rounded-none border-t-0 bg-transparent pt-1 pb-2`,children:[S===`loading`?/* @__PURE__ */ (0,$.jsx)(`span`,{role:`status`,className:`w-full text-xs text-muted-foreground`,children:`Loading conversation…`}):i.thread?.role===`viewer`?/* @__PURE__ */ (0,$.jsx)(`span`,{className:`w-full text-xs text-muted-foreground`,children:`You can read this conversation.`}):i.thread?.writerActive&&!ee?/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`flex w-full items-center gap-2 text-sm text-muted-foreground`,children:[/* @__PURE__ */ (0,$.jsx)(`span`,{role:`status`,className:`min-w-0 flex-1`,children:`This response is unfinished. Refresh to check for updates.`}),/* @__PURE__ */ (0,$.jsx)(K,{variant:`outline`,size:`icon-sm`,tooltip:`Refresh`,onClick:()=>void e.refreshThread(),children:/* @__PURE__ */ (0,$.jsx)(g,{})})]}):null,i.thread?.role!==`viewer`&&i.pendingInteractions.filter(e=>!O.has(e.toolCallId)&&(i.thread?.role===`manager`||_.status===`ready`&&e.targetTenantUserId===_.currentUser.user.id)).map(t=>/* @__PURE__ */ (0,$.jsxs)(`div`,{className:`flex w-full flex-wrap items-center gap-2 text-sm`,children:[/* @__PURE__ */ (0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:`An earlier action may already have happened. Continuing skips its result without running it again.`}),/* @__PURE__ */ (0,$.jsx)(qt,{variant:`outline`,size:`sm`,className:`any-pointer-coarse:min-h-11 any-pointer-coarse:min-w-11`,onClick:()=>void e.abandonToolCall(t.toolCallId),children:`Continue without result`})]},t.responseTargetId)),b!==void 0&&/* @__PURE__ */ (0,$.jsx)(Fp,{status:b}),t.sandboxPanel===!0&&j&&/* @__PURE__ */ (0,$.jsx)(Np,{activity:y}),P.enabled&&M.storageError&&/* @__PURE__ */ (0,$.jsx)(`p`,{role:`status`,className:`w-full text-muted-foreground text-xs`,children:`Files cannot be recovered after reload because browser storage is unavailable.`}),/* @__PURE__ */ (0,$.jsx)(Nu,{title:t.title??`AstralBeam`,actionsSlot:f.has(`composerActions`)?Lp(`composerActions`):void 0,draft:M.text,onDraftChange:M.setText,onSend:ae,onStop:()=>{l?.(`status`,`generation stopped by user`),e.stop()},onRetry:w||C?.phase===`refused`?void 0:C?.phase===`failed`?()=>void e.retry():m.length>0?()=>void e.reload():void 0,retryLabel:C?.phase===`failed`?`Retry`:`Refresh`,showError:T!==void 0,error:T,streamBusy:ee,isBusy:re||C?.phase===`failed`,authPending:R,threadLoading:S===`loading`,authError:z,onAuthRetry:e.retryAuthentication,attachments:F,attachmentLimits:P,onAddFiles:ie,onRemoveAttachment:V})]})]});return/* @__PURE__ */ (0,$.jsx)(te.Provider,{value:p,children:pe})}function Jp(e,t){let n=e.host.parentElement??document.body,r=ke(),i=document.createElement(`style`);e.append(i);let a=()=>{i.textContent=W(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 Yp(e,t,n){let r=document.createElement(`style`);r.textContent=vr+(n.customCss??``),e.append(r);let i=n,a=Jp(e,()=>At(i.debug)),o=(0,Au.createRoot)(t),s=Yl(At(n.debug)),c=n.chat?void 0:Jl({...n,streamCallbacks:s}),l=t=>{i.customCss!==t.customCss&&(r.textContent=vr+(t.customCss??``)),i.debug!==t.debug&&(s=Yl(At(t.debug))),i=t,c?.updateOptions({...t,streamCallbacks:s}),o.render(/* @__PURE__ */ (0,$.jsx)(pr,{delay:400,children:/* @__PURE__ */ (0,$.jsx)(qp,{chat:t.chat??c,options:t,host:e.host})}))};return l(n),{update:l,dispose:()=>{o.unmount(),c?.dispose(),a(),r.remove()}}}export{Yp as renderChat};