teodor-new-chat-ui 4.3.356 → 4.3.357
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,6 +1,6 @@
|
|
|
1
1
|
import * as ResizablePrimitive from "react-resizable-panels";
|
|
2
2
|
declare const ResizablePanelGroup: ({ className, ...props }: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => import("react/jsx-runtime").JSX.Element;
|
|
3
|
-
declare const ResizablePanel: import("react").ForwardRefExoticComponent<Omit<import("react").HTMLAttributes<HTMLButtonElement | HTMLElement | HTMLTextAreaElement | HTMLFormElement | HTMLDivElement | HTMLObjectElement |
|
|
3
|
+
declare const ResizablePanel: import("react").ForwardRefExoticComponent<Omit<import("react").HTMLAttributes<HTMLButtonElement | HTMLElement | HTMLTextAreaElement | HTMLFormElement | HTMLDivElement | HTMLObjectElement | HTMLDataElement | HTMLHeadElement | HTMLLinkElement | HTMLBodyElement | HTMLMapElement | HTMLMetaElement | HTMLLabelElement | HTMLSourceElement | HTMLOutputElement | HTMLSlotElement | HTMLStyleElement | HTMLTitleElement | HTMLDialogElement | HTMLImageElement | HTMLOptionElement | HTMLTableElement | HTMLAnchorElement | HTMLHeadingElement | HTMLInputElement | HTMLLIElement | HTMLOListElement | HTMLParagraphElement | HTMLSelectElement | HTMLSpanElement | HTMLUListElement | HTMLAreaElement | HTMLAudioElement | HTMLBaseElement | HTMLQuoteElement | HTMLBRElement | HTMLCanvasElement | HTMLTableColElement | HTMLDataListElement | HTMLModElement | HTMLDetailsElement | HTMLDListElement | HTMLEmbedElement | HTMLFieldSetElement | HTMLHRElement | HTMLHtmlElement | HTMLIFrameElement | HTMLLegendElement | HTMLMeterElement | HTMLOptGroupElement | HTMLPreElement | HTMLProgressElement | HTMLScriptElement | HTMLTemplateElement | HTMLTableSectionElement | HTMLTableCellElement | HTMLTimeElement | HTMLTableRowElement | HTMLTrackElement | HTMLVideoElement | HTMLMenuElement | HTMLTableCaptionElement | HTMLPictureElement>, "id" | "onResize"> & {
|
|
4
4
|
className?: string | undefined;
|
|
5
5
|
collapsedSize?: number | undefined;
|
|
6
6
|
collapsible?: boolean | undefined;
|
package/dist/index.esm.js
CHANGED
|
@@ -3554,12 +3554,12 @@ function Dl(e, t) {
|
|
|
3554
3554
|
toolStreamingStack: w
|
|
3555
3555
|
};
|
|
3556
3556
|
}
|
|
3557
|
-
if (t.type === "progress") {
|
|
3557
|
+
if (t.type === "tool.progress") {
|
|
3558
3558
|
const i = e.toolStreamingMessageId;
|
|
3559
3559
|
if (!i)
|
|
3560
3560
|
return e;
|
|
3561
3561
|
const a = {
|
|
3562
|
-
type: "progress",
|
|
3562
|
+
type: "tool.progress",
|
|
3563
3563
|
content: t.content ?? null
|
|
3564
3564
|
}, l = bo(e.messages, i, a), c = l.findIndex((y) => y.id === i);
|
|
3565
3565
|
if (c === -1)
|
|
@@ -3852,7 +3852,7 @@ function fy(e) {
|
|
|
3852
3852
|
return n.length === 0 ? null : n.join(`
|
|
3853
3853
|
`);
|
|
3854
3854
|
}
|
|
3855
|
-
const py = ["message.start", "message.delta", "message.end"
|
|
3855
|
+
const py = ["message.start", "message.delta", "message.end"], hy = ["tool.start", "tool.end", "tool.progress"], my = ["thread_info", "checkpoint"], gy = ["error", "interrupt", "heartbeat", "state_history", "cancelled"], xy = [
|
|
3856
3856
|
...py,
|
|
3857
3857
|
...hy,
|
|
3858
3858
|
...my,
|
package/dist/index.umd.js
CHANGED
|
@@ -32,10 +32,10 @@ React keys must be passed directly to JSX without using spread:
|
|
|
32
32
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[hl]=this[hl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Dr(i);r[a]||(eg(o,i),r[a]=!0)}return O.isArray(t)?t.forEach(s):s(t),this}};Ft.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),O.reduceDescriptors(Ft.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),O.freezeMethods(Ft);function si(e,t){const n=this||Or,r=t||n,o=Ft.from(r.headers);let s=r.data;return O.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function ml(e){return!!(e&&e.__CANCEL__)}function ur(e,t,n){je.call(this,e??"canceled",je.ERR_CANCELED,t,n),this.name="CanceledError"}O.inherits(ur,je,{__CANCEL__:!0});function gl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new je("Request failed with status code "+n.status,[je.ERR_BAD_REQUEST,je.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function tg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function ng(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,p=0;for(;f!==o;)p+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const h=d&&c-d;return h?Math.round(p*1e3/h):void 0}}function rg(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const So=(e,t,n=3)=>{let r=0;const o=ng(50,250);return rg(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},xl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},yl=e=>(...t)=>O.asap(()=>e(...t)),og=At.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,At.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(At.origin),At.navigator&&/(msie|trident)/i.test(At.navigator.userAgent)):()=>!0,sg=At.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];O.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),O.isString(r)&&i.push("path="+r),O.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function ig(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ag(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function vl(e,t,n){let r=!ig(t);return e&&(r||n==!1)?ag(e,t):t}const wl=e=>e instanceof Ft?{...e}:e;function qn(e,t){t=t||{};const n={};function r(c,d,f,p){return O.isPlainObject(c)&&O.isPlainObject(d)?O.merge.call({caseless:p},c,d):O.isPlainObject(d)?O.merge({},d):O.isArray(d)?d.slice():d}function o(c,d,f,p){if(O.isUndefined(d)){if(!O.isUndefined(c))return r(void 0,c,f,p)}else return r(c,d,f,p)}function s(c,d){if(!O.isUndefined(d))return r(void 0,d)}function i(c,d){if(O.isUndefined(d)){if(!O.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(wl(c),wl(d),f,!0)};return O.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,p=f(e[d],t[d],d);O.isUndefined(p)&&f!==a||(n[d]=p)}),n}const bl=e=>{const t=qn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Ft.from(i),t.url=ul(vl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),O.isFormData(n)){if(At.hasStandardBrowserEnv||At.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(O.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(At.hasStandardBrowserEnv&&(r&&O.isFunction(r)&&(r=r(t)),r||r!==!1&&og(t.url))){const l=o&&s&&sg.read(s);l&&i.set(o,l)}return t},lg=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=bl(e);let s=o.data;const i=Ft.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,p,h,g;function m(){h&&h(),g&&g(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function x(){if(!y)return;const S=Ft.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:S,config:e,request:y};gl(function(E){n(E),m()},function(E){r(E),m()},C),y=null}"onloadend"in y?y.onloadend=x:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(x)},y.onabort=function(){y&&(r(new je("Request aborted",je.ECONNABORTED,e,y)),y=null)},y.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new je(C,je.ERR_NETWORK,e,y);T.event=k||null,r(T),y=null},y.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||fl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new je(k,C.clarifyTimeoutError?je.ETIMEDOUT:je.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&O.forEach(i.toJSON(),function(k,C){y.setRequestHeader(C,k)}),O.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([p,g]=So(c,!0),y.addEventListener("progress",p)),l&&y.upload&&([f,h]=So(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",h)),(o.cancelToken||o.signal)&&(d=S=>{y&&(r(!S||S.type?new ur(null,e,y):S),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const w=tg(o.url);if(w&&At.protocols.indexOf(w)===-1){r(new je("Unsupported protocol "+w+":",je.ERR_BAD_REQUEST,e));return}y.send(s||null)})},cg=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof je?d:new ur(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new je(`timeout ${t} of ms exceeded`,je.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>O.asap(a),l}},ug=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},dg=async function*(e,t){for await(const n of fg(e))yield*ug(n,t)},fg=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Sl=(e,t,n,r)=>{const o=dg(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let p=s+=f;n(p)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},Cl=64*1024,{isFunction:Co}=O,pg=(({Request:e,Response:t})=>({Request:e,Response:t}))(O.global),{ReadableStream:Tl,TextEncoder:kl}=O.global,El=(e,...t)=>{try{return!!e(...t)}catch{return!1}},hg=e=>{e=O.merge.call({skipUndefined:!0},pg,e);const{fetch:t,Request:n,Response:r}=e,o=t?Co(t):typeof fetch=="function",s=Co(n),i=Co(r);if(!o)return!1;const a=o&&Co(Tl),l=o&&(typeof kl=="function"?(g=>m=>g.encode(m))(new kl):async g=>new Uint8Array(await new n(g).arrayBuffer())),c=s&&a&&El(()=>{let g=!1;const m=new n(At.origin,{body:new Tl,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return g&&!m}),d=i&&a&&El(()=>O.isReadableStream(new r("").body)),f={stream:d&&(g=>g.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!f[g]&&(f[g]=(m,y)=>{let x=m&&m[g];if(x)return x.call(m);throw new je(`Response type '${g}' is not supported`,je.ERR_NOT_SUPPORT,y)})});const p=async g=>{if(g==null)return 0;if(O.isBlob(g))return g.size;if(O.isSpecCompliantForm(g))return(await new n(At.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(O.isArrayBufferView(g)||O.isArrayBuffer(g))return g.byteLength;if(O.isURLSearchParams(g)&&(g=g+""),O.isString(g))return(await l(g)).byteLength},h=async(g,m)=>{const y=O.toFiniteNumber(g.getContentLength());return y??p(m)};return async g=>{let{url:m,method:y,data:x,signal:w,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:E,headers:N,withCredentials:_="same-origin",fetchOptions:D}=bl(g),B=t||fetch;E=E?(E+"").toLowerCase():"text";let G=cg([w,S&&S.toAbortSignal()],k),V=null;const P=G&&G.unsubscribe&&(()=>{G.unsubscribe()});let M;try{if(T&&c&&y!=="get"&&y!=="head"&&(M=await h(N,x))!==0){let X=new n(m,{method:"POST",body:x,duplex:"half"}),ne;if(O.isFormData(x)&&(ne=X.headers.get("content-type"))&&N.setContentType(ne),X.body){const[ye,Te]=xl(M,So(yl(T)));x=Sl(X.body,Cl,ye,Te)}}O.isString(_)||(_=_?"include":"omit");const A=s&&"credentials"in n.prototype,F={...D,signal:G,method:y.toUpperCase(),headers:N.normalize().toJSON(),body:x,duplex:"half",credentials:A?_:void 0};V=s&&new n(m,F);let L=await(s?B(V,D):B(m,F));const R=d&&(E==="stream"||E==="response");if(d&&(C||R&&P)){const X={};["status","statusText","headers"].forEach(q=>{X[q]=L[q]});const ne=O.toFiniteNumber(L.headers.get("content-length")),[ye,Te]=C&&xl(ne,So(yl(C),!0))||[];L=new r(Sl(L.body,Cl,ye,()=>{Te&&Te(),P&&P()}),X)}E=E||"text";let z=await f[O.findKey(f,E)||"text"](L,g);return!R&&P&&P(),await new Promise((X,ne)=>{gl(X,ne,{data:z,headers:Ft.from(L.headers),status:L.status,statusText:L.statusText,config:g,request:V})})}catch(A){throw P&&P(),A&&A.name==="TypeError"&&/Load failed|fetch/i.test(A.message)?Object.assign(new je("Network Error",je.ERR_NETWORK,g,V),{cause:A.cause||A}):je.from(A,A&&A.code,g,V)}}},mg=new Map,Il=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=mg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:hg(t)),d=c;return c};Il();const ii={http:Lm,xhr:lg,fetch:{get:Il}};O.forEach(ii,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Al=e=>`- ${e}`,gg=e=>O.isFunction(e)||e===null||e===!1,Nl={getAdapter:(e,t)=>{e=O.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!gg(r)&&(o=ii[(a=String(r)).toLowerCase()],o===void 0))throw new je(`Unknown adapter '${a}'`);if(o&&(O.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
|
|
33
33
|
`+i.map(Al).join(`
|
|
34
34
|
`):" "+Al(i[0]):"as no adapter specified";throw new je("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:ii};function ai(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ur(null,e)}function _l(e){return ai(e),e.headers=Ft.from(e.headers),e.data=si.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Nl.getAdapter(e.adapter||Or.adapter,e)(e).then(function(r){return ai(e),r.data=si.call(e,e.transformResponse,r),r.headers=Ft.from(r.headers),r},function(r){return ml(r)||(ai(e),r&&r.response&&(r.response.data=si.call(e,e.transformResponse,r.response),r.response.headers=Ft.from(r.response.headers))),Promise.reject(r)})}const jl="1.12.2",To={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{To[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ml={};To.transitional=function(t,n,r){function o(s,i){return"[Axios v"+jl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new je(o(i," has been removed"+(n?" in "+n:"")),je.ERR_DEPRECATED);return n&&!Ml[i]&&(Ml[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},To.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function xg(e,t,n){if(typeof e!="object")throw new je("options must be an object",je.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new je("option "+s+" must be "+l,je.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new je("Unknown option "+s,je.ERR_BAD_OPTION)}}const ko={assertOptions:xg,validators:To},fn=ko.validators;let Gn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new dl,response:new dl}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
35
|
-
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=qn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ko.assertOptions(r,{silentJSONParsing:fn.transitional(fn.boolean),forcedJSONParsing:fn.transitional(fn.boolean),clarifyTimeoutError:fn.transitional(fn.boolean)},!1),o!=null&&(O.isFunction(o)?n.paramsSerializer={serialize:o}:ko.assertOptions(o,{encode:fn.function,serialize:fn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ko.assertOptions(n,{baseUrl:fn.spelling("baseURL"),withXsrfToken:fn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&O.merge(s.common,s[n.method]);s&&O.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=Ft.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(l=l&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let d,f=0,p;if(!l){const g=[_l.bind(this),void 0];for(g.unshift(...a),g.push(...c),p=g.length,d=Promise.resolve(n);f<p;)d=d.then(g[f++],g[f++]);return d}p=a.length;let h=n;for(;f<p;){const g=a[f++],m=a[f++];try{h=g(h)}catch(y){m.call(this,y);break}}try{d=_l.call(this,h)}catch(g){return Promise.reject(g)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=qn(this.defaults,t);const n=vl(t.baseURL,t.url,t.allowAbsoluteUrls);return ul(n,t.params,t.paramsSerializer)}};O.forEach(["delete","get","head","options"],function(t){Gn.prototype[t]=function(n,r){return this.request(qn(r||{},{method:t,url:n,data:(r||{}).data}))}}),O.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(qn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Gn.prototype[t]=n(),Gn.prototype[t+"Form"]=n(!0)});let yg=class Gh{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Gh(function(o){t=o}),cancel:t}}};function vg(e){return function(n){return e.apply(null,n)}}function wg(e){return O.isObject(e)&&e.isAxiosError===!0}const li={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(li).forEach(([e,t])=>{li[t]=e});function Pl(e){const t=new Gn(e),n=Ya(Gn.prototype.request,t);return O.extend(n,Gn.prototype,t,{allOwnKeys:!0}),O.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pl(qn(e,o))},n}const yt=Pl(Or);yt.Axios=Gn,yt.CanceledError=ur,yt.CancelToken=yg,yt.isCancel=ml,yt.VERSION=jl,yt.toFormData=wo,yt.AxiosError=je,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=vg,yt.isAxiosError=wg,yt.mergeConfig=qn,yt.AxiosHeaders=Ft,yt.formToJSON=e=>pl(O.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Nl.getAdapter,yt.HttpStatusCode=li,yt.default=yt;const{Axios:VT,AxiosError:KT,CanceledError:qT,isCancel:GT,CancelToken:YT,VERSION:XT,all:JT,Cancel:ZT,isAxiosError:QT,spread:ek,toFormData:tk,AxiosHeaders:nk,HttpStatusCode:rk,formToJSON:ok,getAdapter:sk,mergeConfig:ik}=yt,Rl=typeof window<"u"?window.__API_BASE_URL__:void 0,Ol=Rl?Cn(Rl):void 0;function Cn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Eo=null;const ci=new Set;function Dl(){return Eo}function Io(e){Eo=e,ci.forEach(t=>t(e))}function Ll(e){return ci.add(e),()=>ci.delete(e)}const bg=3e4,Sg=9e4,qt=yt.create({...Ol?{baseURL:Ol}:{},timeout:bg,withCredentials:!0});qt.interceptors.request.use(e=>(Eo&&(e.headers.Authorization=`Bearer ${Eo}`),e)),qt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),Io(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Gt(e,t){return qt.defaults.baseURL?(await qt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ui(e,t,n){return qt.defaults.baseURL?(await qt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function $l(e,t,n){return qt.defaults.baseURL?(await qt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fl(e,t){return qt.defaults.baseURL?(await qt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Yt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){const t=qt.defaults.baseURL;return t?Cn(String(t)):""}updateConfig(t){t.baseUrl&&(qt.defaults.baseURL=Cn(String(t.baseUrl))),t.authToken!==void 0&&Io(t.authToken)}getAuthToken(){return Dl()}setAuthToken(t){Io(t)}onTokenChange(t){return Ll(t)}async listThreads(){const t=await Gt("/threads"),n=Yt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ui("/threads",t?{title:t}:void 0);return Yt(r)}async updateThread(t,n){const r=await $l(`/threads/${t}`,{title:n});return Yt(r)}async deleteThread(t){const n=await Fl(`/threads/${t}`);return Yt(n)}async threadInfo(t){const n=await Gt(`/threads/${t}/info`);return Yt(n)}async listAgents(){const t=await Gt("/agents"),n=Yt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Gt(`/agents/${t}`);return Yt(n)}async getAgentSchema(t){const n=await Gt(`/agents/${t}/schema`);return Yt(n)}async getState(t){const n=await Gt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Yt(n)}async getStateHistory(t){const n=await Gt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sg});return Yt(n)}async cancelRun(t){const n=await ui("/runs/cancel",{threadId:t});return Yt(n)}async listCheckpointSummaries(t){const n=await Gt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Yt(n);return(r==null?void 0:r.items)??[]}}const _n=new Bl,zl=b.createContext(null);function Cg({children:e,apiConfig:t}){const n=_n;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(zl.Provider,{value:r,children:e})}function di(){const e=b.useContext(zl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Tg(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function kg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Tg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Eg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function fi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Ig(e,t){return`${e??""}::${t??""}`}function dr(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!fi(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ng(t),i=Ul(r,0),a=_g(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Ul(e,t){if(!fi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,D)=>Fg(_,D)).filter(_=>!!_),d=Ot(e.config),f=Ot(d==null?void 0:d.configurable),p=dt(f,["checkpoint_id","checkpointId"]),h=dt(f,["checkpoint_ns","checkpointNs"]),g=Ot(e==null?void 0:e.parentConfig),m=Ot(g==null?void 0:g.configurable),y=dt(m,["checkpoint_id","checkpointId"])??null,x=dt(m,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,S=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(_=>_.role==="user")??null,C=Ot(e==null?void 0:e.metadata),T=dt(C,["branch_label","branchLabel"]),E=dt(m,["checkpoint_id","checkpointId"]),N=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:p??null,checkpointNs:h??null,nextCursor:y,nextCursorNs:x,interrupt:Ag(a,c,t),createdAt:S,parentId:E??null,branchLabel:T??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:C??null,config:d??null,parentConfig:g??null,next:N??null,tasks:l??null,values:i??null}}function Ag(e,t,n){const r=Lg(e,n);return r||Dg(t,n)}function Ng(e){const t=new Map;e.forEach((o,s)=>{if(!fi(o))return;const i=Ul(o,s);if(!(i!=null&&i.checkpointId))return;const a=Ig(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Pg(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Wl(s.createdAt??"")-Wl(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function _g(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=dt(i,["label"])??dt(i,["branch_label","branchLabel"])??dt(i,["description"])??"User input",l=Mg(i,["step"]),c=dt(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,p=o.lastUserMessageId??f,h=jg(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0,parentConfig:o.parentConfig??null})}return t}function jg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Mg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Pg(e,t){return{...e,metadata:Ao(e.metadata,t.metadata)??null,config:Ao(e.config,t.config)??null,parentConfig:Ao(e.parentConfig,t.parentConfig)??null,next:Rg(e.next,t.next)??null,tasks:Og(e.tasks,t.tasks)??null,values:Ao(e.values,t.values)??null}}function Ao(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Rg(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Og(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Dg(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Lg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=$g(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=Lr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Lr(r.state,`${o}-state`);if(s)return s}}return null}function $g(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...p]=e,h=typeof a=="string"&&a.trim()?a:t,g=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",m=Array.isArray(d)?d:void 0,y=p.length?p[p.length-1]:void 0;return{id:h,name:g,interrupts:m,state:y!==void 0?y:f}}const n=Ot(e);if(!n)return null;const r=dt(n,["id","thread_id","taskId"])??t,o=dt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function Lr(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Hl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Lr(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=Lr(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=Lr(l,t,n+1,r);if(c)return c}}return null}function Hl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=dt(n,["type","event","kind"]),o=dt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Hl(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Wl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Ot(e)??{},o=Ot(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Eg[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=Ot(o.additional_kwargs)??Ot(o.additionalKwargs),d=Ot(o.response_metadata)??Ot(o.responseMetadata),f=dt(c,["createdAt","created_at"])??dt(o,["created_at","createdAt"]),p=dt(c,["checkpointId","checkpoint_id"]),h=dt(c,["checkpointNs","checkpoint_ns"]),g=Bg(o.content),m={id:l,role:i,content:g};f&&(m.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(m.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(m.model=String(d.model_name)),!m.model&&typeof o.model=="string"&&(m.model=o.model),p&&(m.checkpointId=p),h&&(m.checkpointNs=h);const y=Hg(Ot(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(m.artifact=y);const x=qg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),w=d?{...d}:void 0;x&&Object.keys(x).length&&(m.additionalKwargs=x),w&&Object.keys(w).length&&(m.responseMetadata=w);const S=zg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Ug(o,m.content);k&&(m.content=k)}return m}function Bg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Vl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Vl(e);return t?[t]:[]}return[]}function Vl(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=dt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=dt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Kl(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=dt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Kl(e,t){var s;const n=dt(e,["id","call_id"])??t,r=dt(e,["name"])??dt(Ot(e.function),["name"]);if(!n||!r)return null;const o=Kg(e.args??e.arguments??((s=Ot(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function zg(e){return Array.isArray(e)?e.map((t,n)=>Kl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ug(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Hg(e){return e?{plots:Wg(e.plots)}:void 0}function Wg(e){return Array.isArray(e)?e.map(t=>Vg(t)).filter(t=>!!t):[]}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Kg(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function Ot(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function dt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function qg(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}const ql=120;function Gg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>ql?`${n.slice(0,ql-3)}…`:n:""}function Gl(e){return Gg(e.content)||""}function Yg(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=Gl(n);r&&t.set(n.id,r)}return t}function Xg(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=Gl(o);s&&t.set(r.checkpointId,s)}}return t}const Yl="aiNav:tool-progress";function pi(){return typeof window<"u"&&typeof window.localStorage<"u"}function Xl(e){return`${Yl}:${e}`}function Jg(e,t,n){if(!pi()||!e)return;const r=Xl(e);if(!t.length){window.localStorage.removeItem(r);return}const o={messageId:e,entries:t,updatedAt:Date.now(),...n??{}};try{window.localStorage.setItem(r,JSON.stringify(o))}catch{}}function Zg(e){if(!pi()||!e)return;const t=Xl(e),n=window.localStorage.getItem(t);if(n)try{const r=JSON.parse(n);return!(r!=null&&r.entries)||!Array.isArray(r.entries)?void 0:r.entries}catch{window.localStorage.removeItem(t);return}}function Jl(){if(!pi())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(Yl)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const Tt=[];for(let e=0;e<256;++e)Tt.push((e+256).toString(16).slice(1));function Qg(e,t=0){return(Tt[e[t+0]]+Tt[e[t+1]]+Tt[e[t+2]]+Tt[e[t+3]]+"-"+Tt[e[t+4]]+Tt[e[t+5]]+"-"+Tt[e[t+6]]+Tt[e[t+7]]+"-"+Tt[e[t+8]]+Tt[e[t+9]]+"-"+Tt[e[t+10]]+Tt[e[t+11]]+Tt[e[t+12]]+Tt[e[t+13]]+Tt[e[t+14]]+Tt[e[t+15]]).toLowerCase()}let hi;const ex=new Uint8Array(16);function tx(){if(!hi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");hi=crypto.getRandomValues.bind(crypto)}return hi(ex)}const Zl={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function nx(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??tx();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Qg(r)}function rx(e,t,n){return Zl.randomUUID&&!e?Zl.randomUUID():nx(e)}function mi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function No(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ql(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function ec(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function tc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function ox(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=dx(e);for(const o of r)n.add(o);return Array.from(n)}function nc(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function sx(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};for(const l of t)s(l);const i=Array.from(o),a={};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function _o(e,t,n){const r=e.findIndex(c=>c.id===t);if(r===-1)return e;const o=e[r],s=[...e],i={...o.additionalKwargs??{}},a=Array.isArray(i.toolProgress)?[...i.toolProgress]:[],l={id:rx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),Jg(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function rc(e,t){return e.includes(t)?e:[...e,t]}function ix(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function fr(e,t){let n=!1;const r={},o=e.map(s=>{const i=fx(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??Zg(s.id);if(a!=null&&a.length){const l=[...a];r[s.id]=l,n=!0;const c={...s.additionalKwargs??{},toolProgress:l};return{...s,additionalKwargs:c}}return s});return{messages:n?o:e,toolTimelines:r}}function oc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function ax(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??oc(e);let l="",c=e.slice();if(s){const f=lx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const p=c[c.length-1];if((p==null?void 0:p.type)==="text"){const h=p.text??"",g={...p,text:h+l};c=[...c.slice(0,c.length-1),g]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function sc(e){return e.replace(/\s+/g," ").trim()}function lx(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=sc(e),o=sc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function cx(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return No(e,r,s)}return e}function ux(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function dx(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function fx(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}const px={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function hx(e,t){var n;switch(t.type){case"reset":return{messages:mi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],pendingInterrupt:null,toolTimelines:{}};case"seed":{const r=mi(t.payload.messages),{messages:o,toolTimelines:s}=fr(r,e.toolTimelines),i={...e,messages:o,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,toolStreamingMessageId:null,toolStreamingStack:[],toolTimelines:s};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(i.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(i.lastCheckpointNs=t.payload.checkpointNs??null),i}case"prepend":{const r=mi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(c=>c.id)),s=r.filter(c=>!o.has(c.id));if(!s.length)return e;const i=[...s,...e.messages],{messages:a,toolTimelines:l}=fr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"event":return ac(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>ac(o,s),e):e}case"interrupt_response":return{...e,messages:Ql(e.messages),pendingInterrupt:null};default:return e}}function ic(e=[]){const[t,n]=b.useReducer(hx,{...px,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function ac(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=ux(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const c={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,c]}}if(t.type==="message.delta"){const i=e.assemblingId??ec(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:oc(c.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof f.lastSeq=="number"&&p<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:f.lastSeq}),e;const{newParts:h,newMeta:g,changed:m}=ax(c.content,t.delta,f,p);if(!m)return e;const y={...c,content:h},x=No(a,l,y),w={...d,[i]:g};return{...e,messages:x,messagesStreamMeta:w}}if(t.type==="message.end"){const i=e.assemblingId??ec(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(c=>c.id===i&&c.role==="assistant");if(l>=0){const c=a[l];if(!((n=c.content)==null?void 0:n.some(f=>{var p;return(f==null?void 0:f.type)==="text"&&((p=f.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=c.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool.start"){const i=tc(t),a=i[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),l=t.name??t.tool??"tool";!a&&i.length===0&&i.push(`${l}-${Date.now()}`);const c=i.length?i:a?[a]:[],d=c[0]??`${l}-${Date.now()}`,f={type:"tool_call",id:d,name:l,args:t.args},p={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},h=e.toolStreamingMessageId;if(!h){const w={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...sx(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},S=ox(w,c.length?c:[d]),k=[...e.messages,w],C=_o(k,w.id,p),{messages:T,toolTimelines:E}=fr(C,e.toolTimelines);return{...e,messages:T,toolIndex:nc(e.toolIndex,w.id,S),toolStreamingMessageId:w.id,toolStreamingStack:rc(e.toolStreamingStack??[],a??d),toolTimelines:E}}const g=_o(e.messages,h,p),{messages:m,toolTimelines:y}=fr(g,e.toolTimelines);return{...e,messages:m,toolIndex:nc(e.toolIndex,h,c),toolStreamingStack:rc(e.toolStreamingStack??[],a??d),toolTimelines:y}}if(t.type==="tool.end"){const i=tc(t);if(!i.length&&!(typeof t.id=="string"&&t.id))return e;const a=i[0]??(typeof t.id=="string"?t.id:null);if(!a)return e;const l=e.toolStreamingStack??[],c=l[0]??null,d=ix(l,a),f=d[0]?e.toolIndex[d[0]]:null,p=e.toolStreamingMessageId,h=c===a,g=t.name??((s=e.messages.find(C=>C.id===p))==null?void 0:s.name)??"tool",m=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),y={type:"tool.end",toolId:a,toolName:g,content:m==null?void 0:m.slice(0,200)};let x=e.messages;if(p&&(x=_o(x,p,y)),h&&p){const C=x.findIndex(T=>T.id===p);if(C>=0){const T=x[C],N={type:"text",text:(()=>{if(typeof t.output=="string"){const D=t.output.trim();try{return D}catch{return D}}return JSON.stringify(t.output??"")})()},_={...T,content:[N],artifact:t.artifact??T.artifact,additionalKwargs:{...T.additionalKwargs??{}}};x=No(x,C,_)}}const w=d,{messages:S,toolTimelines:k}=fr(x,e.toolTimelines);return{...e,messages:S,toolTimelines:k,toolStreamingMessageId:h?f:p,toolStreamingStack:w}}if(t.type==="progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"progress",content:t.content??null},l=_o(e.messages,i,a),c=l.findIndex(y=>y.id===i);if(c===-1)return e;const d=l[c],f={...d.additionalKwargs??{},toolStreaming:!0},p={...d,additionalKwargs:f},h=No(l,c,p),{messages:g,toolTimelines:m}=fr(h,e.toolTimelines);return{...e,messages:g,toolTimelines:m}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=cx(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="state_history"){const i=dr(t),a=i.interrupt,l=i.latest,c=a===null?Ql(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:a,lastCheckpointId:(l==null?void 0:l.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(l==null?void 0:l.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function lc(e={}){const t=b.useMemo(()=>Cn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,p]=b.useState(""),[h,g]=b.useState(null),[m,y]=b.useState(0),[x,w]=b.useState(!1),S=b.useRef(null),k=b.useRef(!0),C=b.useRef(0),T=b.useRef(null),E=b.useRef(null),N=b.useRef(null),_=b.useRef(null),D=b.useCallback(P=>{o(P)},[]),B=b.useCallback(()=>{p(""),g(null),d(null),E.current=null,N.current=null,_.current=null},[]),G=b.useCallback(()=>{var P;console.debug("[use-chat] stop() invoked - aborting stream"),(P=S.current)==null||P.abort(),S.current=null,T.current=null,l(!1),w(!1),C.current=0,y(0)},[]),V=b.useCallback((P,M,A)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),g(null),E.current=null,N.current=null,_.current=null;const F=new AbortController;S.current=F;let L=null,R=null,z=!1;return T.current={threadId:P.threadId??null,headers:{}},(async()=>{var ne,ye,Te,q,U,Z,$,Y,Q,de,oe,_e,ze,se,me,Pe,Ve,ut;const X=Ke=>{var qe;try{const Qe=JSON.parse(JSON.stringify(Ke));return(qe=Qe==null?void 0:Qe.payload)!=null&&qe.files_info&&Array.isArray(Qe.payload.files_info)&&(Qe.payload.files_info=Qe.payload.files_info.map(Ge=>({...Ge,data:Ge!=null&&Ge.data?`<base64 ${String(Ge.data).length} chars>`:Ge==null?void 0:Ge.data}))),Qe}catch{return Ke}};try{let Ke={};try{if(r)Ke={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const We=window.__AUTH_TOKEN__,pt=((ne=window.localStorage)==null?void 0:ne.getItem("authToken"))||null;let Rt=null;try{const H=(ye=window.localStorage)==null?void 0:ye.getItem("chat-settings");H&&(Rt=((Te=JSON.parse(H))==null?void 0:Te.apiKey)||null)}catch{}const Ye=We||pt||Rt||null;Ye&&(Ke={Authorization:`Bearer ${Ye}`})}}catch{}console.debug("[use-chat] POST",t+n,X(P));let qe={};if(typeof window<"u")try{const tt=(q=window.localStorage)==null?void 0:q.getItem("authSessionId");tt&&(qe={"X-Session-Id":tt})}catch{}const Qe={...Ke,...qe,...s.current},Ge={"Content-Type":"application/json",Accept:"text/event-stream",...Qe},et=await fetch(t+n,{method:"POST",headers:Ge,body:JSON.stringify(P),signal:F.signal,credentials:i});if(T.current&&(T.current.headers=Qe),!et.ok||!et.body){const tt=await et.text().catch(()=>"");console.debug("[use-chat] non-OK response",et.status,tt==null?void 0:tt.slice(0,500));const We=`stream ${et.status}${tt?": "+tt:""}`;throw(U=A==null?void 0:A.onConnectionError)==null||U.call(A,We),z=!0,L="error",R=We,new Error(We)}w(!0);const st=et.body.getReader(),Mt=new TextDecoder;let gt="",Ct=[];C.current=0,y(0);let it=0,St=null;const Pt=()=>{if(Ct.length){const tt=Ct.join("");Ct=[],k.current&&p(We=>We+tt)}St=null},zt=()=>{typeof window<"u"&&St==null&&(St=requestAnimationFrame(Pt))};let nn=Date.now();const Le=setInterval(()=>{var tt;if(Date.now()-nn>18e5){const We="Stream idle timeout";d(We),L="error",R=We,F.abort(),(tt=A==null?void 0:A.onError)==null||tt.call(A,We)}},5e3),Sn=1024*1024;try{const tt=et.headers.get("X-Thread-Id")||et.headers.get("x-thread-id"),We=et.headers.get("X-Thread-Created")||et.headers.get("x-thread-created"),pt=tt??null,Rt=String(We??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:pt}),(Z=A==null?void 0:A.onOpen)==null||Z.call(A,{threadId:pt,created:Rt});;){const{value:Ye,done:H}=await st.read();if(H)break;gt+=Mt.decode(Ye,{stream:!0}),gt.length>Sn&&(gt="",console.warn("Stream buffer reset: exceeded 1MB"));let j;for(;(j=gt.indexOf(`
|
|
35
|
+
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=qn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ko.assertOptions(r,{silentJSONParsing:fn.transitional(fn.boolean),forcedJSONParsing:fn.transitional(fn.boolean),clarifyTimeoutError:fn.transitional(fn.boolean)},!1),o!=null&&(O.isFunction(o)?n.paramsSerializer={serialize:o}:ko.assertOptions(o,{encode:fn.function,serialize:fn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ko.assertOptions(n,{baseUrl:fn.spelling("baseURL"),withXsrfToken:fn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&O.merge(s.common,s[n.method]);s&&O.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=Ft.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(l=l&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let d,f=0,p;if(!l){const g=[_l.bind(this),void 0];for(g.unshift(...a),g.push(...c),p=g.length,d=Promise.resolve(n);f<p;)d=d.then(g[f++],g[f++]);return d}p=a.length;let h=n;for(;f<p;){const g=a[f++],m=a[f++];try{h=g(h)}catch(y){m.call(this,y);break}}try{d=_l.call(this,h)}catch(g){return Promise.reject(g)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=qn(this.defaults,t);const n=vl(t.baseURL,t.url,t.allowAbsoluteUrls);return ul(n,t.params,t.paramsSerializer)}};O.forEach(["delete","get","head","options"],function(t){Gn.prototype[t]=function(n,r){return this.request(qn(r||{},{method:t,url:n,data:(r||{}).data}))}}),O.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(qn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Gn.prototype[t]=n(),Gn.prototype[t+"Form"]=n(!0)});let yg=class Gh{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Gh(function(o){t=o}),cancel:t}}};function vg(e){return function(n){return e.apply(null,n)}}function wg(e){return O.isObject(e)&&e.isAxiosError===!0}const li={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(li).forEach(([e,t])=>{li[t]=e});function Pl(e){const t=new Gn(e),n=Ya(Gn.prototype.request,t);return O.extend(n,Gn.prototype,t,{allOwnKeys:!0}),O.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pl(qn(e,o))},n}const yt=Pl(Or);yt.Axios=Gn,yt.CanceledError=ur,yt.CancelToken=yg,yt.isCancel=ml,yt.VERSION=jl,yt.toFormData=wo,yt.AxiosError=je,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=vg,yt.isAxiosError=wg,yt.mergeConfig=qn,yt.AxiosHeaders=Ft,yt.formToJSON=e=>pl(O.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Nl.getAdapter,yt.HttpStatusCode=li,yt.default=yt;const{Axios:VT,AxiosError:KT,CanceledError:qT,isCancel:GT,CancelToken:YT,VERSION:XT,all:JT,Cancel:ZT,isAxiosError:QT,spread:ek,toFormData:tk,AxiosHeaders:nk,HttpStatusCode:rk,formToJSON:ok,getAdapter:sk,mergeConfig:ik}=yt,Rl=typeof window<"u"?window.__API_BASE_URL__:void 0,Ol=Rl?Cn(Rl):void 0;function Cn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Eo=null;const ci=new Set;function Dl(){return Eo}function Io(e){Eo=e,ci.forEach(t=>t(e))}function Ll(e){return ci.add(e),()=>ci.delete(e)}const bg=3e4,Sg=9e4,qt=yt.create({...Ol?{baseURL:Ol}:{},timeout:bg,withCredentials:!0});qt.interceptors.request.use(e=>(Eo&&(e.headers.Authorization=`Bearer ${Eo}`),e)),qt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),Io(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Gt(e,t){return qt.defaults.baseURL?(await qt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ui(e,t,n){return qt.defaults.baseURL?(await qt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function $l(e,t,n){return qt.defaults.baseURL?(await qt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fl(e,t){return qt.defaults.baseURL?(await qt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Yt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){const t=qt.defaults.baseURL;return t?Cn(String(t)):""}updateConfig(t){t.baseUrl&&(qt.defaults.baseURL=Cn(String(t.baseUrl))),t.authToken!==void 0&&Io(t.authToken)}getAuthToken(){return Dl()}setAuthToken(t){Io(t)}onTokenChange(t){return Ll(t)}async listThreads(){const t=await Gt("/threads"),n=Yt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ui("/threads",t?{title:t}:void 0);return Yt(r)}async updateThread(t,n){const r=await $l(`/threads/${t}`,{title:n});return Yt(r)}async deleteThread(t){const n=await Fl(`/threads/${t}`);return Yt(n)}async threadInfo(t){const n=await Gt(`/threads/${t}/info`);return Yt(n)}async listAgents(){const t=await Gt("/agents"),n=Yt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Gt(`/agents/${t}`);return Yt(n)}async getAgentSchema(t){const n=await Gt(`/agents/${t}/schema`);return Yt(n)}async getState(t){const n=await Gt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Yt(n)}async getStateHistory(t){const n=await Gt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sg});return Yt(n)}async cancelRun(t){const n=await ui("/runs/cancel",{threadId:t});return Yt(n)}async listCheckpointSummaries(t){const n=await Gt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Yt(n);return(r==null?void 0:r.items)??[]}}const _n=new Bl,zl=b.createContext(null);function Cg({children:e,apiConfig:t}){const n=_n;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(zl.Provider,{value:r,children:e})}function di(){const e=b.useContext(zl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Tg(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function kg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Tg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Eg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function fi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Ig(e,t){return`${e??""}::${t??""}`}function dr(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!fi(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ng(t),i=Ul(r,0),a=_g(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Ul(e,t){if(!fi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,D)=>Fg(_,D)).filter(_=>!!_),d=Ot(e.config),f=Ot(d==null?void 0:d.configurable),p=dt(f,["checkpoint_id","checkpointId"]),h=dt(f,["checkpoint_ns","checkpointNs"]),g=Ot(e==null?void 0:e.parentConfig),m=Ot(g==null?void 0:g.configurable),y=dt(m,["checkpoint_id","checkpointId"])??null,x=dt(m,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,S=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(_=>_.role==="user")??null,C=Ot(e==null?void 0:e.metadata),T=dt(C,["branch_label","branchLabel"]),E=dt(m,["checkpoint_id","checkpointId"]),N=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:p??null,checkpointNs:h??null,nextCursor:y,nextCursorNs:x,interrupt:Ag(a,c,t),createdAt:S,parentId:E??null,branchLabel:T??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:C??null,config:d??null,parentConfig:g??null,next:N??null,tasks:l??null,values:i??null}}function Ag(e,t,n){const r=Lg(e,n);return r||Dg(t,n)}function Ng(e){const t=new Map;e.forEach((o,s)=>{if(!fi(o))return;const i=Ul(o,s);if(!(i!=null&&i.checkpointId))return;const a=Ig(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Pg(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Wl(s.createdAt??"")-Wl(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function _g(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=dt(i,["label"])??dt(i,["branch_label","branchLabel"])??dt(i,["description"])??"User input",l=Mg(i,["step"]),c=dt(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,p=o.lastUserMessageId??f,h=jg(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0,parentConfig:o.parentConfig??null})}return t}function jg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Mg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Pg(e,t){return{...e,metadata:Ao(e.metadata,t.metadata)??null,config:Ao(e.config,t.config)??null,parentConfig:Ao(e.parentConfig,t.parentConfig)??null,next:Rg(e.next,t.next)??null,tasks:Og(e.tasks,t.tasks)??null,values:Ao(e.values,t.values)??null}}function Ao(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Rg(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Og(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Dg(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Lg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=$g(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=Lr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Lr(r.state,`${o}-state`);if(s)return s}}return null}function $g(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...p]=e,h=typeof a=="string"&&a.trim()?a:t,g=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",m=Array.isArray(d)?d:void 0,y=p.length?p[p.length-1]:void 0;return{id:h,name:g,interrupts:m,state:y!==void 0?y:f}}const n=Ot(e);if(!n)return null;const r=dt(n,["id","thread_id","taskId"])??t,o=dt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function Lr(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Hl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Lr(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=Lr(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=Lr(l,t,n+1,r);if(c)return c}}return null}function Hl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=dt(n,["type","event","kind"]),o=dt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Hl(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Wl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Ot(e)??{},o=Ot(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Eg[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=Ot(o.additional_kwargs)??Ot(o.additionalKwargs),d=Ot(o.response_metadata)??Ot(o.responseMetadata),f=dt(c,["createdAt","created_at"])??dt(o,["created_at","createdAt"]),p=dt(c,["checkpointId","checkpoint_id"]),h=dt(c,["checkpointNs","checkpoint_ns"]),g=Bg(o.content),m={id:l,role:i,content:g};f&&(m.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(m.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(m.model=String(d.model_name)),!m.model&&typeof o.model=="string"&&(m.model=o.model),p&&(m.checkpointId=p),h&&(m.checkpointNs=h);const y=Hg(Ot(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(m.artifact=y);const x=qg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),w=d?{...d}:void 0;x&&Object.keys(x).length&&(m.additionalKwargs=x),w&&Object.keys(w).length&&(m.responseMetadata=w);const S=zg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Ug(o,m.content);k&&(m.content=k)}return m}function Bg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Vl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Vl(e);return t?[t]:[]}return[]}function Vl(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=dt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=dt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Kl(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=dt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Kl(e,t){var s;const n=dt(e,["id","call_id"])??t,r=dt(e,["name"])??dt(Ot(e.function),["name"]);if(!n||!r)return null;const o=Kg(e.args??e.arguments??((s=Ot(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function zg(e){return Array.isArray(e)?e.map((t,n)=>Kl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ug(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Hg(e){return e?{plots:Wg(e.plots)}:void 0}function Wg(e){return Array.isArray(e)?e.map(t=>Vg(t)).filter(t=>!!t):[]}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Kg(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function Ot(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function dt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function qg(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}const ql=120;function Gg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>ql?`${n.slice(0,ql-3)}…`:n:""}function Gl(e){return Gg(e.content)||""}function Yg(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=Gl(n);r&&t.set(n.id,r)}return t}function Xg(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=Gl(o);s&&t.set(r.checkpointId,s)}}return t}const Yl="aiNav:tool-progress";function pi(){return typeof window<"u"&&typeof window.localStorage<"u"}function Xl(e){return`${Yl}:${e}`}function Jg(e,t,n){if(!pi()||!e)return;const r=Xl(e);if(!t.length){window.localStorage.removeItem(r);return}const o={messageId:e,entries:t,updatedAt:Date.now(),...n??{}};try{window.localStorage.setItem(r,JSON.stringify(o))}catch{}}function Zg(e){if(!pi()||!e)return;const t=Xl(e),n=window.localStorage.getItem(t);if(n)try{const r=JSON.parse(n);return!(r!=null&&r.entries)||!Array.isArray(r.entries)?void 0:r.entries}catch{window.localStorage.removeItem(t);return}}function Jl(){if(!pi())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(Yl)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const Tt=[];for(let e=0;e<256;++e)Tt.push((e+256).toString(16).slice(1));function Qg(e,t=0){return(Tt[e[t+0]]+Tt[e[t+1]]+Tt[e[t+2]]+Tt[e[t+3]]+"-"+Tt[e[t+4]]+Tt[e[t+5]]+"-"+Tt[e[t+6]]+Tt[e[t+7]]+"-"+Tt[e[t+8]]+Tt[e[t+9]]+"-"+Tt[e[t+10]]+Tt[e[t+11]]+Tt[e[t+12]]+Tt[e[t+13]]+Tt[e[t+14]]+Tt[e[t+15]]).toLowerCase()}let hi;const ex=new Uint8Array(16);function tx(){if(!hi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");hi=crypto.getRandomValues.bind(crypto)}return hi(ex)}const Zl={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function nx(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??tx();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Qg(r)}function rx(e,t,n){return Zl.randomUUID&&!e?Zl.randomUUID():nx(e)}function mi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function No(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ql(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function ec(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function tc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function ox(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=dx(e);for(const o of r)n.add(o);return Array.from(n)}function nc(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function sx(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};for(const l of t)s(l);const i=Array.from(o),a={};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function _o(e,t,n){const r=e.findIndex(c=>c.id===t);if(r===-1)return e;const o=e[r],s=[...e],i={...o.additionalKwargs??{}},a=Array.isArray(i.toolProgress)?[...i.toolProgress]:[],l={id:rx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),Jg(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function rc(e,t){return e.includes(t)?e:[...e,t]}function ix(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function fr(e,t){let n=!1;const r={},o=e.map(s=>{const i=fx(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??Zg(s.id);if(a!=null&&a.length){const l=[...a];r[s.id]=l,n=!0;const c={...s.additionalKwargs??{},toolProgress:l};return{...s,additionalKwargs:c}}return s});return{messages:n?o:e,toolTimelines:r}}function oc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function ax(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??oc(e);let l="",c=e.slice();if(s){const f=lx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const p=c[c.length-1];if((p==null?void 0:p.type)==="text"){const h=p.text??"",g={...p,text:h+l};c=[...c.slice(0,c.length-1),g]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function sc(e){return e.replace(/\s+/g," ").trim()}function lx(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=sc(e),o=sc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function cx(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return No(e,r,s)}return e}function ux(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function dx(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function fx(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}const px={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function hx(e,t){var n;switch(t.type){case"reset":return{messages:mi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],pendingInterrupt:null,toolTimelines:{}};case"seed":{const r=mi(t.payload.messages),{messages:o,toolTimelines:s}=fr(r,e.toolTimelines),i={...e,messages:o,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,toolStreamingMessageId:null,toolStreamingStack:[],toolTimelines:s};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(i.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(i.lastCheckpointNs=t.payload.checkpointNs??null),i}case"prepend":{const r=mi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(c=>c.id)),s=r.filter(c=>!o.has(c.id));if(!s.length)return e;const i=[...s,...e.messages],{messages:a,toolTimelines:l}=fr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"event":return ac(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>ac(o,s),e):e}case"interrupt_response":return{...e,messages:Ql(e.messages),pendingInterrupt:null};default:return e}}function ic(e=[]){const[t,n]=b.useReducer(hx,{...px,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function ac(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=ux(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const c={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,c]}}if(t.type==="message.delta"){const i=e.assemblingId??ec(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:oc(c.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof f.lastSeq=="number"&&p<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:f.lastSeq}),e;const{newParts:h,newMeta:g,changed:m}=ax(c.content,t.delta,f,p);if(!m)return e;const y={...c,content:h},x=No(a,l,y),w={...d,[i]:g};return{...e,messages:x,messagesStreamMeta:w}}if(t.type==="message.end"){const i=e.assemblingId??ec(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(c=>c.id===i&&c.role==="assistant");if(l>=0){const c=a[l];if(!((n=c.content)==null?void 0:n.some(f=>{var p;return(f==null?void 0:f.type)==="text"&&((p=f.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=c.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool.start"){const i=tc(t),a=i[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),l=t.name??t.tool??"tool";!a&&i.length===0&&i.push(`${l}-${Date.now()}`);const c=i.length?i:a?[a]:[],d=c[0]??`${l}-${Date.now()}`,f={type:"tool_call",id:d,name:l,args:t.args},p={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},h=e.toolStreamingMessageId;if(!h){const w={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...sx(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},S=ox(w,c.length?c:[d]),k=[...e.messages,w],C=_o(k,w.id,p),{messages:T,toolTimelines:E}=fr(C,e.toolTimelines);return{...e,messages:T,toolIndex:nc(e.toolIndex,w.id,S),toolStreamingMessageId:w.id,toolStreamingStack:rc(e.toolStreamingStack??[],a??d),toolTimelines:E}}const g=_o(e.messages,h,p),{messages:m,toolTimelines:y}=fr(g,e.toolTimelines);return{...e,messages:m,toolIndex:nc(e.toolIndex,h,c),toolStreamingStack:rc(e.toolStreamingStack??[],a??d),toolTimelines:y}}if(t.type==="tool.end"){const i=tc(t);if(!i.length&&!(typeof t.id=="string"&&t.id))return e;const a=i[0]??(typeof t.id=="string"?t.id:null);if(!a)return e;const l=e.toolStreamingStack??[],c=l[0]??null,d=ix(l,a),f=d[0]?e.toolIndex[d[0]]:null,p=e.toolStreamingMessageId,h=c===a,g=t.name??((s=e.messages.find(C=>C.id===p))==null?void 0:s.name)??"tool",m=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),y={type:"tool.end",toolId:a,toolName:g,content:m==null?void 0:m.slice(0,200)};let x=e.messages;if(p&&(x=_o(x,p,y)),h&&p){const C=x.findIndex(T=>T.id===p);if(C>=0){const T=x[C],N={type:"text",text:(()=>{if(typeof t.output=="string"){const D=t.output.trim();try{return D}catch{return D}}return JSON.stringify(t.output??"")})()},_={...T,content:[N],artifact:t.artifact??T.artifact,additionalKwargs:{...T.additionalKwargs??{}}};x=No(x,C,_)}}const w=d,{messages:S,toolTimelines:k}=fr(x,e.toolTimelines);return{...e,messages:S,toolTimelines:k,toolStreamingMessageId:h?f:p,toolStreamingStack:w}}if(t.type==="tool.progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"tool.progress",content:t.content??null},l=_o(e.messages,i,a),c=l.findIndex(y=>y.id===i);if(c===-1)return e;const d=l[c],f={...d.additionalKwargs??{},toolStreaming:!0},p={...d,additionalKwargs:f},h=No(l,c,p),{messages:g,toolTimelines:m}=fr(h,e.toolTimelines);return{...e,messages:g,toolTimelines:m}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=cx(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="state_history"){const i=dr(t),a=i.interrupt,l=i.latest,c=a===null?Ql(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:a,lastCheckpointId:(l==null?void 0:l.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(l==null?void 0:l.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function lc(e={}){const t=b.useMemo(()=>Cn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,p]=b.useState(""),[h,g]=b.useState(null),[m,y]=b.useState(0),[x,w]=b.useState(!1),S=b.useRef(null),k=b.useRef(!0),C=b.useRef(0),T=b.useRef(null),E=b.useRef(null),N=b.useRef(null),_=b.useRef(null),D=b.useCallback(P=>{o(P)},[]),B=b.useCallback(()=>{p(""),g(null),d(null),E.current=null,N.current=null,_.current=null},[]),G=b.useCallback(()=>{var P;console.debug("[use-chat] stop() invoked - aborting stream"),(P=S.current)==null||P.abort(),S.current=null,T.current=null,l(!1),w(!1),C.current=0,y(0)},[]),V=b.useCallback((P,M,A)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),g(null),E.current=null,N.current=null,_.current=null;const F=new AbortController;S.current=F;let L=null,R=null,z=!1;return T.current={threadId:P.threadId??null,headers:{}},(async()=>{var ne,ye,Te,q,U,Z,$,Y,Q,de,oe,_e,ze,se,me,Pe,Ve,ut;const X=Ke=>{var qe;try{const Qe=JSON.parse(JSON.stringify(Ke));return(qe=Qe==null?void 0:Qe.payload)!=null&&qe.files_info&&Array.isArray(Qe.payload.files_info)&&(Qe.payload.files_info=Qe.payload.files_info.map(Ge=>({...Ge,data:Ge!=null&&Ge.data?`<base64 ${String(Ge.data).length} chars>`:Ge==null?void 0:Ge.data}))),Qe}catch{return Ke}};try{let Ke={};try{if(r)Ke={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const We=window.__AUTH_TOKEN__,pt=((ne=window.localStorage)==null?void 0:ne.getItem("authToken"))||null;let Rt=null;try{const H=(ye=window.localStorage)==null?void 0:ye.getItem("chat-settings");H&&(Rt=((Te=JSON.parse(H))==null?void 0:Te.apiKey)||null)}catch{}const Ye=We||pt||Rt||null;Ye&&(Ke={Authorization:`Bearer ${Ye}`})}}catch{}console.debug("[use-chat] POST",t+n,X(P));let qe={};if(typeof window<"u")try{const tt=(q=window.localStorage)==null?void 0:q.getItem("authSessionId");tt&&(qe={"X-Session-Id":tt})}catch{}const Qe={...Ke,...qe,...s.current},Ge={"Content-Type":"application/json",Accept:"text/event-stream",...Qe},et=await fetch(t+n,{method:"POST",headers:Ge,body:JSON.stringify(P),signal:F.signal,credentials:i});if(T.current&&(T.current.headers=Qe),!et.ok||!et.body){const tt=await et.text().catch(()=>"");console.debug("[use-chat] non-OK response",et.status,tt==null?void 0:tt.slice(0,500));const We=`stream ${et.status}${tt?": "+tt:""}`;throw(U=A==null?void 0:A.onConnectionError)==null||U.call(A,We),z=!0,L="error",R=We,new Error(We)}w(!0);const st=et.body.getReader(),Mt=new TextDecoder;let gt="",Ct=[];C.current=0,y(0);let it=0,St=null;const Pt=()=>{if(Ct.length){const tt=Ct.join("");Ct=[],k.current&&p(We=>We+tt)}St=null},zt=()=>{typeof window<"u"&&St==null&&(St=requestAnimationFrame(Pt))};let nn=Date.now();const Le=setInterval(()=>{var tt;if(Date.now()-nn>18e5){const We="Stream idle timeout";d(We),L="error",R=We,F.abort(),(tt=A==null?void 0:A.onError)==null||tt.call(A,We)}},5e3),Sn=1024*1024;try{const tt=et.headers.get("X-Thread-Id")||et.headers.get("x-thread-id"),We=et.headers.get("X-Thread-Created")||et.headers.get("x-thread-created"),pt=tt??null,Rt=String(We??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:pt}),(Z=A==null?void 0:A.onOpen)==null||Z.call(A,{threadId:pt,created:Rt});;){const{value:Ye,done:H}=await st.read();if(H)break;gt+=Mt.decode(Ye,{stream:!0}),gt.length>Sn&&(gt="",console.warn("Stream buffer reset: exceeded 1MB"));let j;for(;(j=gt.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const J=gt.slice(0,j);gt=gt.slice(j+2);const re=gx(J);if(!re)continue;let ie;try{ie=JSON.parse(re)}catch{console.debug("[use-chat] malformed SSE:",re.slice(0,200));continue}const ce=mx(ie)?ie.data:ie;nn=Date.now();const Xe=ce.seq;if(Xe!==void 0){if(Xe<=it){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Xe,lastProcessedSeq:it,type:ce.type});continue}it>0&&Xe>it+1&&(($=A==null?void 0:A.onGap)==null||$.call(A,{from:it,to:Xe})),it=Xe,C.current=Xe,y(Xe)}if(ce.type==="checkpoint")E.current=ce.checkpointId??null,N.current=ce.checkpointNs??null,g(ce.checkpointId??null);else if(ce.type==="state_history"){_.current=ce;try{const at=dr(ce).latest;at&&(E.current=at.checkpointId??null,N.current=at.checkpointNs??null,g(at.checkpointId??null))}catch(Ie){console.warn("[use-chat] Failed to hydrate state_history payload",Ie)}}try{M==null||M(ce)}catch(Ie){console.error("[use-chat] Error in onEvent callback:",Ie,"for event:",ce.type)}if(ce.type==="message.delta"){const Ie=ce.delta.filter(at=>at.type==="text").map(at=>at.text).join("");Ie&&e.autoAppendAssistant!==!1&&(Ct.push(Ie),zt())}else if(ce.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(Y=A==null?void 0:A.onHeartbeat)==null||Y.call(A,ce)}catch(Ie){console.warn("[use-chat] heartbeat callback failed",Ie)}}else if(St!==null&&cancelAnimationFrame(St),Pt(),ce.type==="checkpoint")g(ce.checkpointId);else if(ce.type==="error"){const Ie=ce;if(d(Ie.message),L="error",R=Ie.message,Ie.error_type==="auth_error"||Ie.code==="TOKEN_EXPIRED"||((Q=Ie.message)==null?void 0:Q.includes("token"))||((de=Ie.message)==null?void 0:de.includes("401"))||((oe=Ie.message)==null?void 0:oe.includes("unauthorized"))||((_e=Ie.message)==null?void 0:_e.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Ie.message);try{(ze=A==null?void 0:A.onAuthError)==null||ze.call(A,Ie.message)}catch(ht){console.warn("[use-chat] onAuthError handler failed",ht)}F.abort()}}}}Pt(),L===null&&!F.signal.aborted&&(L="complete")}catch(tt){if(tt.name==="AbortError")L=L??"aborted";else{const We=tt.message||String(tt);L="error",R=We,d(We),(se=A==null?void 0:A.onError)==null||se.call(A,We)}}finally{try{await st.cancel()}catch{}finally{(me=st.releaseLock)==null||me.call(st)}St!==null&&typeof window<"u"&&window.cancelAnimationFrame(St),clearInterval(Le)}}catch(Ke){if(Ke.name==="AbortError")L=L??"aborted";else{const qe=Ke.message||String(Ke);L="error",R=qe,d(qe),(Pe=A==null?void 0:A.onError)==null||Pe.call(A,qe),z||((Ve=A==null?void 0:A.onConnectionError)==null||Ve.call(A,qe),z=!0)}}finally{const Ke=C.current,qe=E.current,Qe=N.current,Ge=_.current,et=L??(F.signal.aborted?"aborted":R?"error":"complete");try{(ut=A==null?void 0:A.onClosed)==null||ut.call(A,{reason:et,lastSeq:Ke,lastCheckpointId:qe,lastCheckpointNs:Qe,lastStateHistory:Ge,error:R})}catch(st){console.warn("[use-chat] onClosed callback failed",st)}l(!1),w(!1),S.current=null,C.current=0,y(0),T.current=null}})(),{close:()=>F.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var P;k.current=!1,(P=S.current)==null||P.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:h,lastSeq:m,connected:x,stream:V,stop:G,clear:B,setToken:D}}function mx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function gx(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
|
|
38
|
-
`)}const xx=["message.start","message.delta","message.end","progress"],yx=["tool.start","tool.end"],vx=["thread_info","checkpoint"],wx=["error","interrupt","heartbeat","state_history","cancelled"],bx=[...xx,...yx,...vx,...wx],Sx=new Set(bx);function Cx(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return Sx.has(t)}const cc=200;function Tx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=b.useRef(null),f=b.useRef(null),p=b.useRef(new Map),h=b.useRef(null),g=b.useRef(null),m=b.useCallback(M=>{try{const A=globalThis.structuredClone;if(typeof A=="function")return A(M)}catch{}try{return JSON.parse(JSON.stringify(M))}catch{return M}},[]),y=b.useCallback((M,A)=>{if(!M)return;const F=p.current.get(M)??[],L=m(A),R=F.length>=cc?[...F.slice(F.length-cc+1),L]:[...F,L];p.current.set(M,R)},[m]),x=b.useCallback(M=>{M&&p.current.set(M,[])},[]),w=b.useCallback(M=>{const A=M??f.current;if(!A)return;const F=p.current.get(A);F!=null&&F.length&&F.forEach(L=>{try{n(L)}catch(R){console.error("[useChatStreamingService] Failed to replay buffered event",R)}})},[n]),S=b.useCallback(M=>{f.current=M.threadId,h.current&&(h.current.threadIdGuess=M.threadId),g.current=M,x(M.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",M);try{t(M)}catch(A){console.error("[useChatStreamingService] Error in onThreadInfo handler:",A)}},[x,t]),k=b.useCallback(M=>{try{c==null||c(M)}catch(A){console.error("[useChatStreamingService] Error in onHeartbeat handler:",A)}},[c]),C=b.useCallback(M=>{var L,R,z,X;const A=M;if(A.error_type==="auth_error"||A.code==="TOKEN_EXPIRED"||((L=A.message)==null?void 0:L.includes("token"))||((R=A.message)==null?void 0:R.includes("401"))||((z=A.message)==null?void 0:z.includes("unauthorized"))||((X=A.message)==null?void 0:X.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",A.message);try{l==null||l(A.message)}catch(ne){console.warn("[useChatStreamingService] onAuthError handler failed",ne)}}},[l]),T=b.useMemo(()=>({thread_info:M=>(S(M),!0),heartbeat:M=>(k(M),!0),error:M=>(C(M),!1)}),[S,k,C]),E=b.useCallback(M=>{var R;const A=M.seq??null;if(A!==null){const z=d.current;if(z!==null){if(A<=z)return;A>z+1&&(s==null||s({from:z,to:A}))}d.current=A}const F=T[M.type];if(F&&F(M))return;const L=M.threadId??(M.type==="state_history"?M.threadId:void 0)??f.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(M.type==="state_history"){f.current=L??f.current;try{r==null||r(M)}catch(z){console.error("[useChatStreamingService] onStateHistory handler failed",z)}}if(Cx(M)){M.type==="checkpoint"||M.type==="state_history"?x(L??null):y(L??null,M);try{n(M)}catch(z){console.error("[useChatStreamingService] Error in onMessageEvent handler:",z)}return}try{o==null||o(M)}catch(z){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",z)}},[y,x,n,s,r,o,T]),{stream:N,stop:_,isStreaming:D,error:B,setToken:G}=lc({baseUrl:e,token:void 0}),V=b.useCallback((M,A)=>{d.current=null,g.current=null,f.current=M.threadId??null,h.current={request:M,callbacks:A,manualStop:!1,threadIdGuess:M.threadId??null},N(M,E,{onOpen:A==null?void 0:A.onOpen,onError:F=>{var L;(L=A==null?void 0:A.onError)==null||L.call(A,F)},onGap:(A==null?void 0:A.onGap)??s,onConnectionError:F=>{var L;a==null||a(F),(L=A==null?void 0:A.onConnectionError)==null||L.call(A,F)},onAuthError:F=>{var L;l==null||l(F),(L=A==null?void 0:A.onAuthError)==null||L.call(A,F)},onHeartbeat:F=>{var L;try{c==null||c(F)}catch(R){console.warn("[useChatStreamingService] onHeartbeat handler failed",R)}try{(L=A==null?void 0:A.onHeartbeat)==null||L.call(A,F)}catch(R){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",R)}},onClosed:F=>{var X,ne,ye,Te;const L=((X=h.current)==null?void 0:X.manualStop)??!1,R=f.current??((ne=h.current)==null?void 0:ne.threadIdGuess)??((ye=F.lastStateHistory)==null?void 0:ye.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&L)&&x(R);const z={...F,threadId:R,threadInfo:g.current,manualStop:L};try{i==null||i(z)}catch(q){console.warn("[useChatStreamingService] onStreamClosed handler failed",q)}try{(Te=A==null?void 0:A.onClosed)==null||Te.call(A,z)}catch(q){console.warn("[useChatStreamingService] downstream onClosed handler failed",q)}h.current&&(h.current=null)}})},[x,E,l,a,c,s,i,N]),P=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),_()},[_]);return b.useMemo(()=>({startStream:V,stop:P,isStreaming:D,error:B,setAuthToken:G,replayBufferedEvents:w}),[V,P,D,B,G,w])}const uc=b.createContext(null),dc=b.createContext(null),fc=b.createContext(null);b.createContext(!1);function kx({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l}){const{api:c,baseUrl:d}=di(),f=b.useMemo(()=>Cn(d),[d]),[p,h]=b.useState([]),[g,m]=b.useState(t),[y,x]=b.useState(!1),[w,S]=b.useState(null),[k,C]=b.useState(!1),[T,E]=b.useState(null),{state:N,seed:_,prepend:D,pushUser:B,onEvent:G}=ic(),[V,P]=b.useState(!1),[M,A]=b.useState(!1),[F,L]=b.useState(null),[R,z]=b.useState([]),[X,ne]=b.useState([]),[ye,Te]=b.useState(!1),q=b.useMemo(()=>Xg(R),[R]),U=b.useRef(g),Z=b.useRef(null),$=b.useRef(null),Y=b.useRef(null),Q=b.useRef(null),de=b.useRef(!1),oe=b.useRef(null),_e=b.useRef(new Map),ze=b.useRef(new Map);b.useEffect(()=>{U.current=g},[g]);const se=b.useCallback(async H=>{var J,re;if(!H.threadId)return;const j=H.threadId;(J=H.onStart)==null||J.call(H),H.setLoading(!0);try{await H.action(j)}catch(ie){if(U.current===j){const ce=String(ie);(re=H.handleError)==null||re.call(H,ce),s==null||s(ce)}throw ie}finally{H.setLoading(!1)}},[s]),me=b.useCallback(async()=>{x(!0),S(null);try{const H=await c.listThreads();h(H??[])}catch(H){const j=String(H);S(j),s==null||s(j)}finally{x(!1)}},[c,s]),Pe=b.useCallback(H=>{if(!(H!=null&&H.threadId))return;const j={threadId:H.threadId,title:H.title||`Thread ${H.threadId.slice(0,8)}`,createdAt:H.createdAt||new Date().toISOString(),updatedAt:H.updatedAt||new Date().toISOString(),messageCount:H.messageCount??1};h(J=>{let re=!1;const ie=J.map(ce=>ce.threadId===j.threadId?(re=!0,console.debug("[ChatSessionProvider] thread_info: updating existing thread",j.threadId),{...ce,title:j.title??ce.title,updatedAt:j.updatedAt??ce.updatedAt,messageCount:j.messageCount??ce.messageCount}):ce);return re?ie:(console.debug("[ChatSessionProvider] thread_info: adding thread to list",j.threadId),[j,...J])})},[]),Ve=b.useCallback(H=>{const j=H.threadId??U.current;if(!j||U.current&&U.current!==j)return;const{checkpoints:J,timeline:re}=dr(H);if(!J.length)return;const ie=J.find(ce=>ce.messages&&ce.messages.length>0)??J.find(ce=>!!ce.checkpointId)??J[0];_((ie==null?void 0:ie.messages)??[],{checkpointId:(ie==null?void 0:ie.checkpointId)??null,checkpointNs:(ie==null?void 0:ie.checkpointNs)??null}),ne(re),z(J),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null),oe.current=`${j}:latest`,$.current=null,Y.current=null},[_]),ut=b.useCallback(H=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",H.threadId),Pe(H),U.current!==H.threadId&&((H.created??!U.current)&&($.current=H.threadId),Y.current=H.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),m(H.threadId))},[Pe]),{startStream:Ke,stop:qe,isStreaming:Qe,error:Ge,setAuthToken:et}=Tx({baseUrl:f,onThreadInfo:ut,onMessageEvent:G,onStateHistory:Ve,onUnhandledEvent:H=>{console.warn("[ChatSessionProvider] Unhandled event:",H.type)},onAuthError:i,onConnectionError:l}),st=b.useCallback(async H=>{try{const j=await c.createThread(H);return m(j.threadId),await me(),j.threadId}catch(j){return s==null||s(String(j)),null}},[c,me,s]),Mt=b.useCallback(async H=>{const j=p;h(re=>re.filter(ie=>ie.threadId!==H));const J=new AbortController;ze.current.set(H,J);try{await c.deleteThread(H),U.current===H&&(m(null),_([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",H)}catch(re){console.error("[ChatSessionProvider] Delete failed, restoring thread:",H,re),h(j),s==null||s(`Failed to delete thread: ${String(re)}`)}finally{ze.current.delete(H)}},[p,c,_,s]),gt=b.useCallback(async(H,j)=>{try{await c.updateThread(H,j),await me()}catch(J){s==null||s(String(J))}},[c,me,s]),Ct=b.useCallback(async(H,j)=>{if(!H)return;const J=`${H}:${j??"latest"}`,re=_e.current.get(J);if(re)return re;const ie=se({threadId:H,setLoading:C,onStart:()=>E(null),handleError:ce=>E(ce),action:async ce=>{const Xe=await c.getStateHistory({threadId:ce,checkpointId:j||void 0});if(U.current!==ce){console.log(`[ChatSessionProvider] Thread changed during load (was ${ce}, now ${U.current}), discarding stale data`);return}const{checkpoints:Ie,timeline:at}=dr(Xe),ht=Ie.find(Kt=>Kt.messages&&Kt.messages.length>0)??(j?Ie.find(Kt=>Kt.checkpointId===j):null)??Ie[0];_((ht==null?void 0:ht.messages)??[],{checkpointId:(ht==null?void 0:ht.checkpointId)??null,checkpointNs:(ht==null?void 0:ht.checkpointNs)??null}),ne(at),z(Ie),P(!!(ht!=null&&ht.nextCursor)),L((ht==null?void 0:ht.nextCursor)??null)}});_e.current.set(J,ie);try{await ie}finally{_e.current.delete(J)}return U.current===H&&(oe.current=J),ie},[c,_,s,se]),it=b.useCallback(async(H,j,J)=>{J!=null&&J.clearProgress&&Jl(),Q.current=H;try{await Ct(H,j)}finally{Q.current===H&&(Q.current=null)}},[Ct]);b.useEffect(()=>{if(!o||!g||k||Qe)return;if($.current===g){$.current=null,Z.current=g;return}if(Y.current===g){Z.current=g;return}if(Q.current===g){Q.current=null,Z.current=g;return}if(Z.current===g)return;Z.current=g;const H=!de.current&&!!n&&g===t;let j;H&&n?(j=n,de.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",j,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const J=`${g}:${j??"latest"}`;oe.current!==J&&it(g,j)},[o,g,n,r,t,k,Qe,it]);const St=b.useCallback(async(H,j)=>{Jl();const J=U.current;await se({threadId:J,setLoading:Te,action:async re=>{const ie=await c.getStateHistory({threadId:re,checkpointId:H,checkpointNs:j??void 0});if(U.current!==re){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${re}, now ${U.current}), discarding stale data`);return}const{checkpoints:ce,timeline:Xe}=dr(ie),Ie=ce.find(at=>at.checkpointId===H&&(j?at.checkpointNs===j:!0));if(!Ie){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:H,checkpointNs:j});return}ne(Xe),z(ce),_(Ie.messages??[],{checkpointId:Ie.checkpointId??null,checkpointNs:Ie.checkpointNs??null})}}).catch(()=>{})},[c,_,s,se]),Pt=b.useCallback((H,j)=>{_(N.messages,{checkpointId:H??null,checkpointNs:j??null})},[_,N.messages]),zt=b.useCallback(async()=>{U.current&&await it(U.current)},[it]),nn=b.useCallback(async()=>{const H=U.current;!H||!F||await se({threadId:H,setLoading:A,action:async j=>{const J=await c.getStateHistory({threadId:j,checkpointId:F});if(U.current!==j)return;const{checkpoints:re}=dr(J);if(re.length>0){const ie=re[re.length-1];D((ie==null?void 0:ie.messages)??[]),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null)}}}).catch(()=>{})},[c,F,D,s,se]),Le=b.useCallback(async()=>{_([],{}),m(null),qe(),z([]),ne([]),P(!1),L(null),C(!1),Te(!1),A(!1),E(null);try{await c.getAgent("default")}catch(H){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",H)}},[_,qe,c]),Sn=b.useCallback(async(H,j,J)=>{const re=U.current;if(!re)throw new Error("No active thread to handle interrupt");const ie=j?J??!0:!1;try{const ce={threadId:re,checkpointId:N.lastCheckpointId??void 0,checkpointNs:N.lastCheckpointNs??void 0,command:{kind:"resume",value:ie}};Ke(ce)}catch(ce){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${H}:`,ce),ce}},[N.lastCheckpointId,N.lastCheckpointNs,Ke]);b.useEffect(()=>{me()},[me]),b.useEffect(()=>{a==null||a(g)},[g,a]);const tt=b.useCallback(async(H,j)=>{let J=U.current;const re=(H==null?void 0:H.text)??"",ie=(H==null?void 0:H.attachments)??[],ce=(re==null?void 0:re.trim())??"",Xe={...(H==null?void 0:H.payload)??{}},Ie=Array.isArray(Xe.messages)?Xe.messages:void 0;Ie&&delete Xe.messages;const at=!!(Ie&&Ie.length);if(!J&&!ce&&ie.length===0&&!at)return;if(!J){const we=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Be=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);J=`${we}${Be}`,$.current=J,m(J)}const{contentParts:ht,filesInfo:Kt}=await kg(c,ie),Hn=[...ht];ce&&Hn.push({type:"text",text:re});const Ar=j==null?void 0:j.originalMessageId,Nr=!!(j!=null&&j.edit&&Ar),po=!at&&Hn.length>0;let Nn=null;po&&(Nn={id:Nr?Ar:`msg-${Date.now()}`,role:"user",content:Hn,createdAt:new Date().toISOString()},Nr||B(Nn));const I=at?Ie:Nn?[Nn]:[],W={...Xe,...Kt.length?{files_info:Kt}:{}};I.length?W.messages=I:"messages"in W||(W.messages=[]);const ae={threadId:J,payload:W,checkpointId:(j==null?void 0:j.checkpointId)??N.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??N.lastCheckpointNs??void 0,edit:!!(j!=null&&j.edit),timelineCheckpoints:X};Ke(ae)},[c,B,N,Ke,X]),We=b.useMemo(()=>({threads:p,currentThreadId:g,setCurrentThreadId:m,isLoading:y,error:w,actions:{createThread:st,deleteThread:Mt,renameThread:gt,refreshThreads:me}}),[p,g,y,w,st,Mt,gt,me]),pt=b.useMemo(()=>{const H=N.assemblingId??null;return H?{assemblingMessageId:H}:null},[N.assemblingId]),Rt=b.useMemo(()=>({threadId:g,messages:N.messages,interrupt:null,checkpoint:{id:N.lastCheckpointId??null,namespace:N.lastCheckpointNs??null},checkpoints:R,timelineCheckpoints:X,metadata:pt,isLoading:k,isHistoryLoading:M,isLoadingCheckpoint:ye,error:T,hasMore:V,loadOlder:nn,clearState:Le,navigateToCheckpoint:St,setCurrentCheckpointId:Pt,returnToLatest:zt,loadThread:it,clearThread:Le,respondToInterrupt:Sn,messagePreviews:q}),[g,N,R,X,k,M,ye,T,V,nn,Le,St,Pt,zt,it,Sn,q,pt]),Ye=b.useMemo(()=>({isStreaming:Qe,error:Ge,connectionState:Qe?"connected":"idle",submit:tt,send:tt,stop:qe,setAuthToken:et}),[Qe,Ge,tt,qe,et]);return u.jsx(uc.Provider,{value:We,children:u.jsx(dc.Provider,{value:Rt,children:u.jsx(fc.Provider,{value:Ye,children:e})})})}function jo(){const e=b.useContext(uc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Mo(){const e=b.useContext(dc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function pc(){const e=b.useContext(fc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Po({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Cg,{apiConfig:t,children:u.jsx(kx,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,children:e})})}function te(...e){return Xh.twMerge(Yh.clsx(e))}const Ex=ho.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Je=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Vn.Slot:"button";return u.jsx(i,{className:te(Ex({variant:t,size:n,className:e})),ref:s,...o})});Je.displayName="Button";const hc=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));hc.displayName="Textarea";function mc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:p="",allowEmptySend:h=!1}){const g=i!==void 0,[m,y]=b.useState(e),x=(g?i:m)??"",[w,S]=b.useTransition(),k=b.useRef(null),C=b.useRef(0),T=b.useRef(null);b.useEffect(()=>{g||(y(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,g]);const E=b.useCallback(()=>{const M=k.current;M&&(M.style.height="auto",M.style.height=`${M.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const N=b.useCallback((M,{fromUser:A})=>{g||y(M),A&&(a==null||a(M))},[g,a]),_=b.useCallback(async M=>{M&&M.preventDefault();const A=(x??"").trim();if(!A&&!h)return;const F=++C.current;T.current={id:F,shouldClear:!0},S(()=>{var L,R,z;try{const X=l(A);X&&typeof X.then=="function"?X.then(()=>{var ne,ye;((ne=T.current)==null?void 0:ne.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((ye=T.current)==null?void 0:ye.id)===F&&(T.current=null)}).catch(()=>{var ne;((ne=T.current)==null?void 0:ne.id)===F&&(T.current=null)}):(((L=T.current)==null?void 0:L.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((R=T.current)==null?void 0:R.id)===F&&(T.current=null))}catch{((z=T.current)==null?void 0:z.id)===F&&(T.current=null)}})},[x,l,h,g,a]),D=b.useCallback(M=>{const A=M.target.value;N(A,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),B=b.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),_()):M.key==="Escape"&&t&&(M.preventDefault(),c==null||c())},[_,t,c]),P=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${p}`;return u.jsx("form",{onSubmit:M=>void _(M),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(hc,{ref:k,value:x,onChange:D,onKeyDown:B,placeholder:t?"Edit your message...":n,className:P,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(Je,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(le.Square,{size:16})}):u.jsx(Je,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!h||w,children:u.jsx(le.Send,{size:16})})})]})})}const Ix=b.memo(mc);function pe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function gc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function gi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=gc(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():gc(e[o],null)}}}}function $e(...e){return v.useCallback(gi(...e),e)}function Ax(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Tn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:p,children:h,...g}=f,m=((x=p==null?void 0:p[e])==null?void 0:x[l])||a,y=v.useMemo(()=>g,Object.values(g));return u.jsx(m.Provider,{value:y,children:h})};c.displayName=s+"Provider";function d(f,p){var m;const h=((m=p==null?void 0:p[e])==null?void 0:m[l])||a,g=v.useContext(h);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Nx(o,...t)]}function Nx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},_x=v[" useInsertionEffect ".trim().toString()]||kt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=jx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const p=Mx(d)?d(e):d;p!==e&&((f=i.current)==null||f.call(i,p))}else s(d)},[a,e,s,i]);return[l,c]}function jx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return _x(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Mx(e){return typeof e=="function"}var Px=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ne=Px.reduce((e,t)=>{const n=Vn.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function xc(e,t){e&&mo.flushSync(()=>e.dispatchEvent(t))}function xi(e){const t=e+"CollectionProvider",[n,r]=Tn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:y,children:x}=m,w=b.useRef(null),S=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=Vn.createSlot(a),c=b.forwardRef((m,y)=>{const{scope:x,children:w}=m,S=s(a,x),k=$e(y,S.collectionRef);return u.jsx(l,{ref:k,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=Vn.createSlot(d),h=b.forwardRef((m,y)=>{const{scope:x,children:w,...S}=m,k=b.useRef(null),C=$e(y,k),T=s(d,x);return b.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:C,children:w})});h.displayName=d;function g(m){const y=s(e+"CollectionConsumer",m);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},g,r]}var Rx=v.createContext(void 0);function Ro(e){const t=v.useContext(Rx);return e||t||"ltr"}function Et(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ox(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Dx="DismissableLayer",yi="dismissableLayer.update",Lx="dismissableLayer.pointerDownOutside",$x="dismissableLayer.focusOutside",yc,vc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Oo=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(vc),[d,f]=v.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),g=$e(t,E=>f(E)),m=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=m.indexOf(y),w=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=x,C=zx(E=>{const N=E.target,_=[...c.branches].some(D=>D.contains(N));!k||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),T=Ux(E=>{const N=E.target;[...c.branches].some(D=>D.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return Ox(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(yc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),wc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=yc)}},[d,p,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),wc())},[d,c]),v.useEffect(()=>{const E=()=>h({});return document.addEventListener(yi,E),()=>document.removeEventListener(yi,E)},[]),u.jsx(Ne.div,{...l,ref:g,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:pe(e.onFocusCapture,T.onFocusCapture),onBlurCapture:pe(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:pe(e.onPointerDownCapture,C.onPointerDownCapture)})});Oo.displayName=Dx;var Fx="DismissableLayerBranch",Bx=v.forwardRef((e,t)=>{const n=v.useContext(vc),r=v.useRef(null),o=$e(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ne.div,{...e,ref:o})});Bx.displayName=Fx;function zx(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){bc(Lx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Ux(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&bc($x,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function wc(){const e=new CustomEvent(yi);document.dispatchEvent(e)}function bc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?xc(o,s):o.dispatchEvent(s)}var vi=0;function wi(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Sc()),document.body.insertAdjacentElement("beforeend",e[1]??Sc()),vi++,()=>{vi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),vi--}},[])}function Sc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var bi="focusScope.autoFocusOnMount",Si="focusScope.autoFocusOnUnmount",Cc={bubbles:!1,cancelable:!0},Hx="FocusScope",Do=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=Et(o),d=Et(s),f=v.useRef(null),p=$e(t,m=>l(m)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(S){if(h.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:jn(f.current,{select:!0})},y=function(S){if(h.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||jn(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&jn(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,h.paused]),v.useEffect(()=>{if(a){Ec.add(h);const m=document.activeElement;if(!a.contains(m)){const x=new CustomEvent(bi,Cc);a.addEventListener(bi,c),a.dispatchEvent(x),x.defaultPrevented||(Wx(Yx(Tc(a)),{select:!0}),document.activeElement===m&&jn(a))}return()=>{a.removeEventListener(bi,c),setTimeout(()=>{const x=new CustomEvent(Si,Cc);a.addEventListener(Si,d),a.dispatchEvent(x),x.defaultPrevented||jn(m??document.body,{select:!0}),a.removeEventListener(Si,d),Ec.remove(h)},0)}}},[a,c,d,h]);const g=v.useCallback(m=>{if(!n&&!r||h.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,x=document.activeElement;if(y&&x){const w=m.currentTarget,[S,k]=Vx(w);S&&k?!m.shiftKey&&x===k?(m.preventDefault(),n&&jn(S,{select:!0})):m.shiftKey&&x===S&&(m.preventDefault(),n&&jn(k,{select:!0})):x===w&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Ne.div,{tabIndex:-1,...i,ref:p,onKeyDown:g})});Do.displayName=Hx;function Wx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(jn(r,{select:t}),document.activeElement!==n)return}function Vx(e){const t=Tc(e),n=kc(t,e),r=kc(t.reverse(),e);return[n,r]}function Tc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function kc(e,t){for(const n of e)if(!Kx(n,{upTo:t}))return n}function Kx(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function qx(e){return e instanceof HTMLInputElement&&"select"in e}function jn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&qx(e)&&t&&e.select()}}var Ec=Gx();function Gx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ic(e,t),e.unshift(t)},remove(t){var n;e=Ic(e,t),(n=e[0])==null||n.resume()}}}function Ic(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Yx(e){return e.filter(t=>t.tagName!=="A")}var Xx=v[" useId ".trim().toString()]||(()=>{}),Jx=0;function kn(e){const[t,n]=v.useState(Xx());return kt(()=>{n(r=>r??String(Jx++))},[e]),t?`radix-${t}`:""}const Zx=["top","right","bottom","left"],Mn=Math.min,Ut=Math.max,Lo=Math.round,$o=Math.floor,pn=e=>({x:e,y:e}),Qx={left:"right",right:"left",bottom:"top",top:"bottom"},ey={start:"end",end:"start"};function Ci(e,t,n){return Ut(e,Mn(t,n))}function En(e,t){return typeof e=="function"?e(t):e}function In(e){return e.split("-")[0]}function hr(e){return e.split("-")[1]}function Ti(e){return e==="x"?"y":"x"}function ki(e){return e==="y"?"height":"width"}const ty=new Set(["top","bottom"]);function hn(e){return ty.has(In(e))?"y":"x"}function Ei(e){return Ti(hn(e))}function ny(e,t,n){n===void 0&&(n=!1);const r=hr(e),o=Ei(e),s=ki(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Fo(i)),[i,Fo(i)]}function ry(e){const t=Fo(e);return[Ii(e),t,Ii(t)]}function Ii(e){return e.replace(/start|end/g,t=>ey[t])}const Ac=["left","right"],Nc=["right","left"],oy=["top","bottom"],sy=["bottom","top"];function iy(e,t,n){switch(e){case"top":case"bottom":return n?t?Nc:Ac:t?Ac:Nc;case"left":case"right":return t?oy:sy;default:return[]}}function ay(e,t,n,r){const o=hr(e);let s=iy(In(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ii)))),s}function Fo(e){return e.replace(/left|right|bottom|top/g,t=>Qx[t])}function ly(e){return{top:0,right:0,bottom:0,left:0,...e}}function _c(e){return typeof e!="number"?ly(e):{top:e,right:e,bottom:e,left:e}}function Bo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function jc(e,t,n){let{reference:r,floating:o}=e;const s=hn(t),i=Ei(t),a=ki(i),l=In(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:d,y:r.y-o.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:f};break;case"left":h={x:r.x-o.width,y:f};break;default:h={x:r.x,y:r.y}}switch(hr(t)){case"start":h[i]-=p*(n&&c?-1:1);break;case"end":h[i]+=p*(n&&c?-1:1);break}return h}const cy=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=jc(c,r,l),p=r,h={},g=0;for(let m=0;m<a.length;m++){const{name:y,fn:x}=a[m],{x:w,y:S,data:k,reset:C}=await x({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,h={...h,[y]:{...h[y],...k}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:f}=jc(c,p,l)),m=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function $r(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:h=0}=En(t,e),g=_c(h),y=a[p?f==="floating"?"reference":"floating":f],x=Bo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},C=Bo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(x.top-C.top+g.top)/k.y,bottom:(C.bottom-x.bottom+g.bottom)/k.y,left:(x.left-C.left+g.left)/k.x,right:(C.right-x.right+g.right)/k.x}}const uy=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=En(e,t)||{};if(c==null)return{};const f=_c(d),p={x:n,y:r},h=Ei(o),g=ki(h),m=await i.getDimensions(c),y=h==="y",x=y?"top":"left",w=y?"bottom":"right",S=y?"clientHeight":"clientWidth",k=s.reference[g]+s.reference[h]-p[h]-s.floating[g],C=p[h]-s.reference[h],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[g]);const N=k/2-C/2,_=E/2-m[g]/2-1,D=Mn(f[x],_),B=Mn(f[w],_),G=D,V=E-m[g]-B,P=E/2-m[g]/2+N,M=Ci(G,P,V),A=!l.arrow&&hr(o)!=null&&P!==M&&s.reference[g]/2-(P<G?D:B)-m[g]/2<0,F=A?P<G?P-G:P-V:0;return{[h]:p[h]+F,data:{[h]:M,centerOffset:P-M-F,...A&&{alignmentOffset:F}},reset:A}}}),dy=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...y}=En(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=In(o),w=hn(a),S=In(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(S||!m?[Fo(a)]:ry(a)),T=g!=="none";!p&&T&&C.push(...ay(a,m,g,k));const E=[a,...C],N=await $r(t,y),_=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(N[x]),f){const P=ny(o,i,k);_.push(N[P[0]],N[P[1]])}if(D=[...D,{placement:o,overflows:_}],!_.every(P=>P<=0)){var B,G;const P=(((B=s.flip)==null?void 0:B.index)||0)+1,M=E[P];if(M&&(!(f==="alignment"?w!==hn(M):!1)||D.every(L=>hn(L.placement)===w?L.overflows[0]>0:!0)))return{data:{index:P,overflows:D},reset:{placement:M}};let A=(G=D.filter(F=>F.overflows[0]<=0).sort((F,L)=>F.overflows[1]-L.overflows[1])[0])==null?void 0:G.placement;if(!A)switch(h){case"bestFit":{var V;const F=(V=D.filter(L=>{if(T){const R=hn(L.placement);return R===w||R==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(R=>R>0).reduce((R,z)=>R+z,0)]).sort((L,R)=>L[1]-R[1])[0])==null?void 0:V[0];F&&(A=F);break}case"initialPlacement":A=a;break}if(o!==A)return{reset:{placement:A}}}return{}}}};function Mc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Pc(e){return Zx.some(t=>e[t]>=0)}const fy=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=En(e,t);switch(r){case"referenceHidden":{const s=await $r(t,{...o,elementContext:"reference"}),i=Mc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Pc(i)}}}case"escaped":{const s=await $r(t,{...o,altBoundary:!0}),i=Mc(s,n.floating);return{data:{escapedOffsets:i,escaped:Pc(i)}}}default:return{}}}}},Rc=new Set(["left","top"]);async function py(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=In(n),a=hr(n),l=hn(n)==="y",c=Rc.has(i)?-1:1,d=s&&l?-1:1,f=En(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:g}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof g=="number"&&(h=a==="end"?g*-1:g),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const hy=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await py(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},my=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:w}=y;return{x,y:w}}},...l}=En(e,t),c={x:n,y:r},d=await $r(t,l),f=hn(In(o)),p=Ti(f);let h=c[p],g=c[f];if(s){const y=p==="y"?"top":"left",x=p==="y"?"bottom":"right",w=h+d[y],S=h-d[x];h=Ci(w,h,S)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=g+d[y],S=g-d[x];g=Ci(w,g,S)}const m=a.fn({...t,[p]:h,[f]:g});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[f]:i}}}}}},gy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=En(e,t),d={x:n,y:r},f=hn(o),p=Ti(f);let h=d[p],g=d[f];const m=En(a,t),y=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=p==="y"?"height":"width",k=s.reference[p]-s.floating[S]+y.mainAxis,C=s.reference[p]+s.reference[S]-y.mainAxis;h<k?h=k:h>C&&(h=C)}if(c){var x,w;const S=p==="y"?"width":"height",k=Rc.has(In(o)),C=s.reference[f]-s.floating[S]+(k&&((x=i.offset)==null?void 0:x[f])||0)+(k?0:y.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((w=i.offset)==null?void 0:w[f])||0)-(k?y.crossAxis:0);g<C?g=C:g>T&&(g=T)}return{[p]:h,[f]:g}}}},xy=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=En(e,t),d=await $r(t,c),f=In(o),p=hr(o),h=hn(o)==="y",{width:g,height:m}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=p==="end"?"top":"bottom");const w=m-d.top-d.bottom,S=g-d.left-d.right,k=Mn(m-d[y],w),C=Mn(g-d[x],S),T=!t.middlewareData.shift;let E=k,N=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),T&&!p){const D=Ut(d.left,0),B=Ut(d.right,0),G=Ut(d.top,0),V=Ut(d.bottom,0);h?N=g-2*(D!==0||B!==0?D+B:Ut(d.left,d.right)):E=m-2*(G!==0||V!==0?G+V:Ut(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const _=await i.getDimensions(a.floating);return g!==_.width||m!==_.height?{reset:{rects:!0}}:{}}}};function zo(){return typeof window<"u"}function mr(e){return Oc(e)?(e.nodeName||"").toLowerCase():"#document"}function Ht(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function mn(e){var t;return(t=(Oc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Oc(e){return zo()?e instanceof Node||e instanceof Ht(e).Node:!1}function sn(e){return zo()?e instanceof Element||e instanceof Ht(e).Element:!1}function gn(e){return zo()?e instanceof HTMLElement||e instanceof Ht(e).HTMLElement:!1}function Dc(e){return!zo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ht(e).ShadowRoot}const yy=new Set(["inline","contents"]);function Fr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!yy.has(o)}const vy=new Set(["table","td","th"]);function wy(e){return vy.has(mr(e))}const by=[":popover-open",":modal"];function Uo(e){return by.some(t=>{try{return e.matches(t)}catch{return!1}})}const Sy=["transform","translate","scale","rotate","perspective"],Cy=["transform","translate","scale","rotate","perspective","filter"],Ty=["paint","layout","strict","content"];function Ai(e){const t=Ni(),n=sn(e)?an(e):e;return Sy.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Cy.some(r=>(n.willChange||"").includes(r))||Ty.some(r=>(n.contain||"").includes(r))}function ky(e){let t=Pn(e);for(;gn(t)&&!gr(t);){if(Ai(t))return t;if(Uo(t))return null;t=Pn(t)}return null}function Ni(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Ey=new Set(["html","body","#document"]);function gr(e){return Ey.has(mr(e))}function an(e){return Ht(e).getComputedStyle(e)}function Ho(e){return sn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Pn(e){if(mr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Dc(e)&&e.host||mn(e);return Dc(t)?t.host:t}function Lc(e){const t=Pn(e);return gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:gn(t)&&Fr(t)?t:Lc(t)}function Br(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Lc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Ht(o);if(s){const a=_i(i);return t.concat(i,i.visualViewport||[],Fr(o)?o:[],a&&n?Br(a):[])}return t.concat(o,Br(o,[],n))}function _i(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function $c(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=gn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Lo(n)!==s||Lo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ji(e){return sn(e)?e:e.contextElement}function xr(e){const t=ji(e);if(!gn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=$c(t);let i=(s?Lo(n.width):n.width)/r,a=(s?Lo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Iy=pn(0);function Fc(e){const t=Ht(e);return!Ni()||!t.visualViewport?Iy:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Ay(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Ht(e)?!1:t}function Yn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ji(e);let i=pn(1);t&&(r?sn(r)&&(i=xr(r)):i=xr(e));const a=Ay(s,n,r)?Fc(s):pn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const p=Ht(s),h=r&&sn(r)?Ht(r):r;let g=p,m=_i(g);for(;m&&r&&h!==g;){const y=xr(m),x=m.getBoundingClientRect(),w=an(m),S=x.left+(m.clientLeft+parseFloat(w.paddingLeft))*y.x,k=x.top+(m.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=k,g=Ht(m),m=_i(g)}}return Bo({width:d,height:f,x:l,y:c})}function Wo(e,t){const n=Ho(e).scrollLeft;return t?t.left+n:Yn(mn(e)).left+n}function Bc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Wo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Ny(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=mn(r),a=t?Uo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=gn(r);if((f||!f&&!s)&&((mr(r)!=="body"||Fr(i))&&(l=Ho(r)),gn(r))){const h=Yn(r);c=xr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?Bc(i,l):pn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+p.x,y:n.y*c.y-l.scrollTop*c.y+d.y+p.y}}function _y(e){return Array.from(e.getClientRects())}function jy(e){const t=mn(e),n=Ho(e),r=e.ownerDocument.body,o=Ut(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ut(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Wo(e);const a=-n.scrollTop;return an(r).direction==="rtl"&&(i+=Ut(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const zc=25;function My(e,t){const n=Ht(e),r=mn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ni();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Wo(r);if(c<=0){const d=r.ownerDocument,f=d.body,p=getComputedStyle(f),h=d.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,g=Math.abs(r.clientWidth-f.clientWidth-h);g<=zc&&(s-=g)}else c<=zc&&(s+=c);return{width:s,height:i,x:a,y:l}}const Py=new Set(["absolute","fixed"]);function Ry(e,t){const n=Yn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=gn(e)?xr(e):pn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Uc(e,t,n){let r;if(t==="viewport")r=My(e,n);else if(t==="document")r=jy(mn(e));else if(sn(t))r=Ry(t,n);else{const o=Fc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Bo(r)}function Hc(e,t){const n=Pn(e);return n===t||!sn(n)||gr(n)?!1:an(n).position==="fixed"||Hc(n,t)}function Oy(e,t){const n=t.get(e);if(n)return n;let r=Br(e,[],!1).filter(a=>sn(a)&&mr(a)!=="body"),o=null;const s=an(e).position==="fixed";let i=s?Pn(e):e;for(;sn(i)&&!gr(i);){const a=an(i),l=Ai(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Py.has(o.position)||Fr(i)&&!l&&Hc(e,i))?r=r.filter(d=>d!==i):o=a,i=Pn(i)}return t.set(e,r),r}function Dy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Uo(t)?[]:Oy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Uc(t,d,o);return c.top=Ut(f.top,c.top),c.right=Mn(f.right,c.right),c.bottom=Mn(f.bottom,c.bottom),c.left=Ut(f.left,c.left),c},Uc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Ly(e){const{width:t,height:n}=$c(e);return{width:t,height:n}}function $y(e,t,n){const r=gn(t),o=mn(t),s=n==="fixed",i=Yn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=Wo(o)}if(r||!r&&!s)if((mr(t)!=="body"||Fr(o))&&(a=Ho(t)),r){const h=Yn(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Bc(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,p=i.top+a.scrollTop-l.y-d.y;return{x:f,y:p,width:i.width,height:i.height}}function Mi(e){return an(e).position==="static"}function Wc(e,t){if(!gn(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return mn(e)===n&&(n=n.ownerDocument.body),n}function Vc(e,t){const n=Ht(e);if(Uo(e))return n;if(!gn(e)){let o=Pn(e);for(;o&&!gr(o);){if(sn(o)&&!Mi(o))return o;o=Pn(o)}return n}let r=Wc(e,t);for(;r&&wy(r)&&Mi(r);)r=Wc(r,t);return r&&gr(r)&&Mi(r)&&!Ai(r)?n:r||ky(e)||n}const Fy=async function(e){const t=this.getOffsetParent||Vc,n=this.getDimensions,r=await n(e.floating);return{reference:$y(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function By(e){return an(e).direction==="rtl"}const zy={convertOffsetParentRelativeRectToViewportRelativeRect:Ny,getDocumentElement:mn,getClippingRect:Dy,getOffsetParent:Vc,getElementRects:Fy,getClientRects:_y,getDimensions:Ly,getScale:xr,isElement:sn,isRTL:By};function Kc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Uy(e,t){let n=null,r;const o=mn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:p,height:h}=c;if(a||t(),!p||!h)return;const g=$o(f),m=$o(o.clientWidth-(d+p)),y=$o(o.clientHeight-(f+h)),x=$o(d),S={rootMargin:-g+"px "+-m+"px "+-y+"px "+-x+"px",threshold:Ut(0,Mn(1,l))||1};let k=!0;function C(T){const E=T[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Kc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(C,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return i(!0),s}function Hy(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=ji(e),d=o||s?[...c?Br(c):[],...Br(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Uy(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(x=>{let[w]=x;w&&w.target===c&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=h)==null||S.observe(t)})),n()}),c&&!l&&h.observe(c),h.observe(t));let g,m=l?Yn(e):null;l&&y();function y(){const x=Yn(e);m&&!Kc(m,x)&&n(),m=x,g=requestAnimationFrame(y)}return n(),()=>{var x;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(x=h)==null||x.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const Wy=hy,Vy=my,Ky=dy,qy=xy,Gy=fy,qc=uy,Yy=gy,Xy=(e,t,n)=>{const r=new Map,o={platform:zy,...n},s={...o.platform,_c:r};return cy(e,t,{...o,platform:s})};var Jy=typeof document<"u",Zy=function(){},Vo=Jy?b.useLayoutEffect:Zy;function Ko(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ko(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Ko(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Gc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Yc(e,t){const n=Gc(e);return Math.round(t*n)/n}function Pi(e){const t=v.useRef(e);return Vo(()=>{t.current=e}),t}function Qy(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=v.useState(r);Ko(p,r)||h(r);const[g,m]=v.useState(null),[y,x]=v.useState(null),w=v.useCallback(L=>{L!==T.current&&(T.current=L,m(L))},[]),S=v.useCallback(L=>{L!==E.current&&(E.current=L,x(L))},[]),k=s||g,C=i||y,T=v.useRef(null),E=v.useRef(null),N=v.useRef(d),_=l!=null,D=Pi(l),B=Pi(o),G=Pi(c),V=v.useCallback(()=>{if(!T.current||!E.current)return;const L={placement:t,strategy:n,middleware:p};B.current&&(L.platform=B.current),Xy(T.current,E.current,L).then(R=>{const z={...R,isPositioned:G.current!==!1};P.current&&!Ko(N.current,z)&&(N.current=z,mo.flushSync(()=>{f(z)}))})},[p,t,n,B,G]);Vo(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f(L=>({...L,isPositioned:!1})))},[c]);const P=v.useRef(!1);Vo(()=>(P.current=!0,()=>{P.current=!1}),[]),Vo(()=>{if(k&&(T.current=k),C&&(E.current=C),k&&C){if(D.current)return D.current(k,C,V);V()}},[k,C,V,D,_]);const M=v.useMemo(()=>({reference:T,floating:E,setReference:w,setFloating:S}),[w,S]),A=v.useMemo(()=>({reference:k,floating:C}),[k,C]),F=v.useMemo(()=>{const L={position:n,left:0,top:0};if(!A.floating)return L;const R=Yc(A.floating,d.x),z=Yc(A.floating,d.y);return a?{...L,transform:"translate("+R+"px, "+z+"px)",...Gc(A.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:R,top:z}},[n,a,A.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:V,refs:M,elements:A,floatingStyles:F}),[d,V,M,A,F])}const ev=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?qc({element:r.current,padding:o}).fn(n):{}:r?qc({element:r,padding:o}).fn(n):{}}}},tv=(e,t)=>({...Wy(e),options:[e,t]}),nv=(e,t)=>({...Vy(e),options:[e,t]}),rv=(e,t)=>({...Yy(e),options:[e,t]}),ov=(e,t)=>({...Ky(e),options:[e,t]}),sv=(e,t)=>({...qy(e),options:[e,t]}),iv=(e,t)=>({...Gy(e),options:[e,t]}),av=(e,t)=>({...ev(e),options:[e,t]});var lv="Arrow",Xc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Ne.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Xc.displayName=lv;var cv=Xc;function Jc(e){const[t,n]=v.useState(void 0);return kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ri="Popper",[Zc,qo]=Tn(Ri),[uv,Qc]=Zc(Ri),eu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(uv,{scope:t,anchor:r,onAnchorChange:o,children:n})};eu.displayName=Ri;var tu="PopperAnchor",nu=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Qc(tu,n),i=v.useRef(null),a=$e(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Ne.div,{...o,ref:a})});nu.displayName=tu;var Oi="PopperContent",[dv,fv]=Zc(Oi),ru=v.forwardRef((e,t)=>{var Z,$,Y,Q,de,oe;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:g,...m}=e,y=Qc(Oi,n),[x,w]=v.useState(null),S=$e(t,_e=>w(_e)),[k,C]=v.useState(null),T=Jc(k),E=(T==null?void 0:T.width)??0,N=(T==null?void 0:T.height)??0,_=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},B=Array.isArray(c)?c:[c],G=B.length>0,V={padding:D,boundary:B.filter(hv),altBoundary:G},{refs:P,floatingStyles:M,placement:A,isPositioned:F,middlewareData:L}=Qy({strategy:"fixed",placement:_,whileElementsMounted:(..._e)=>Hy(..._e,{animationFrame:h==="always"}),elements:{reference:y.anchor},middleware:[tv({mainAxis:o+N,alignmentAxis:i}),l&&nv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?rv():void 0,...V}),l&&ov({...V}),sv({...V,apply:({elements:_e,rects:ze,availableWidth:se,availableHeight:me})=>{const{width:Pe,height:Ve}=ze.reference,ut=_e.floating.style;ut.setProperty("--radix-popper-available-width",`${se}px`),ut.setProperty("--radix-popper-available-height",`${me}px`),ut.setProperty("--radix-popper-anchor-width",`${Pe}px`),ut.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),k&&av({element:k,padding:a}),mv({arrowWidth:E,arrowHeight:N}),p&&iv({strategy:"referenceHidden",...V})]}),[R,z]=iu(A),X=Et(g);kt(()=>{F&&(X==null||X())},[F,X]);const ne=(Z=L.arrow)==null?void 0:Z.x,ye=($=L.arrow)==null?void 0:$.y,Te=((Y=L.arrow)==null?void 0:Y.centerOffset)!==0,[q,U]=v.useState();return kt(()=>{x&&U(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:P.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:F?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:q,"--radix-popper-transform-origin":[(Q=L.transformOrigin)==null?void 0:Q.x,(de=L.transformOrigin)==null?void 0:de.y].join(" "),...((oe=L.hide)==null?void 0:oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(dv,{scope:n,placedSide:R,onArrowChange:C,arrowX:ne,arrowY:ye,shouldHideArrow:Te,children:u.jsx(Ne.div,{"data-side":R,"data-align":z,...m,ref:S,style:{...m.style,animation:F?void 0:"none"}})})})});ru.displayName=Oi;var ou="PopperArrow",pv={top:"bottom",right:"left",bottom:"top",left:"right"},su=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=fv(ou,r),i=pv[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(cv,{...o,ref:n,style:{...o.style,display:"block"}})})});su.displayName=ou;function hv(e){return e!==null}var mv=e=>({name:"transformOrigin",options:e,fn(t){var y,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=iu(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,h=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let g="",m="";return c==="bottom"?(g=i?f:`${p}px`,m=`${-l}px`):c==="top"?(g=i?f:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,m=i?f:`${h}px`):c==="left"&&(g=`${r.floating.width+l}px`,m=i?f:`${h}px`),{data:{x:g,y:m}}}});function iu(e){const[t,n="center"]=e.split("-");return[t,n]}var au=eu,lu=nu,cu=ru,uu=su,gv="Portal",Go=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ys.createPortal(u.jsx(Ne.div,{...r,ref:t}),i):null});Go.displayName=gv;function xv(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Xt=e=>{const{present:t,children:n}=e,r=yv(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=$e(r.ref,vv(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Xt.displayName="Presence";function yv(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=xv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Yo(r.current);s.current=a==="mounted"?c:"none"},[a]),kt(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=Yo(c);e?l("MOUNT"):h==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const m=Yo(r.current).includes(CSS.escape(h.animationName));if(h.target===t&&m&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=h=>{h.target===t&&(s.current=Yo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Yo(e){return(e==null?void 0:e.animationName)||"none"}function vv(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Di="rovingFocusGroup.onEntryFocus",wv={bubbles:!1,cancelable:!0},zr="RovingFocusGroup",[Li,du,bv]=xi(zr),[Sv,fu]=Tn(zr,[bv]),[Cv,Tv]=Sv(zr),pu=v.forwardRef((e,t)=>u.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(kv,{...e,ref:t})})}));pu.displayName=zr;var kv=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,p=v.useRef(null),h=$e(t,p),g=Ro(s),[m,y]=pr({prop:i,defaultProp:a??null,onChange:l,caller:zr}),[x,w]=v.useState(!1),S=Et(c),k=du(n),C=v.useRef(!1),[T,E]=v.useState(0);return v.useEffect(()=>{const N=p.current;if(N)return N.addEventListener(Di,S),()=>N.removeEventListener(Di,S)},[S]),u.jsx(Cv,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:m,onItemFocus:v.useCallback(N=>y(N),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:v.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Ne.div,{tabIndex:x||T===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:pe(e.onMouseDown,()=>{C.current=!0}),onFocus:pe(e.onFocus,N=>{const _=!C.current;if(N.target===N.currentTarget&&_&&!x){const D=new CustomEvent(Di,wv);if(N.currentTarget.dispatchEvent(D),!D.defaultPrevented){const B=k().filter(A=>A.focusable),G=B.find(A=>A.active),V=B.find(A=>A.id===m),M=[G,V,...B].filter(Boolean).map(A=>A.ref.current);gu(M,d)}}C.current=!1}),onBlur:pe(e.onBlur,()=>w(!1))})})}),hu="RovingFocusGroupItem",mu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=kn(),c=s||l,d=Tv(hu,n),f=d.currentTabStopId===c,p=du(n),{onFocusableItemAdd:h,onFocusableItemRemove:g,currentTabStopId:m}=d;return v.useEffect(()=>{if(r)return h(),()=>g()},[r,h,g]),u.jsx(Li.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Ne.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:pe(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:pe(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:pe(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=Av(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=p().filter(k=>k.focusable).map(k=>k.ref.current);if(x==="last")S.reverse();else if(x==="prev"||x==="next"){x==="prev"&&S.reverse();const k=S.indexOf(y.currentTarget);S=d.loop?Nv(S,k+1):S.slice(k+1)}setTimeout(()=>gu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});mu.displayName=hu;var Ev={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Iv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Av(e,t,n){const r=Iv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Ev[r]}function gu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Nv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var _v=pu,jv=mu,Mv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},yr=new WeakMap,Xo=new WeakMap,Jo={},$i=0,xu=function(e){return e&&(e.host||xu(e.parentNode))},Pv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Rv=function(e,t,n,r){var o=Pv(t,Array.isArray(e)?e:[e]);Jo[n]||(Jo[n]=new WeakMap);var s=Jo[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(p){if(a.has(p))d(p);else try{var h=p.getAttribute(r),g=h!==null&&h!=="false",m=(yr.get(p)||0)+1,y=(s.get(p)||0)+1;yr.set(p,m),s.set(p,y),i.push(p),m===1&&g&&Xo.set(p,!0),y===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",p,x)}})};return d(t),a.clear(),$i++,function(){i.forEach(function(f){var p=yr.get(f)-1,h=s.get(f)-1;yr.set(f,p),s.set(f,h),p||(Xo.has(f)||f.removeAttribute(r),Xo.delete(f)),h||f.removeAttribute(n)}),$i--,$i||(yr=new WeakMap,yr=new WeakMap,Xo=new WeakMap,Jo={})}},Fi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Mv(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Rv(r,o,n,"aria-hidden")):function(){return null}},xn=function(){return xn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},xn.apply(this,arguments)};function yu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function Ov(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Zo="right-scroll-bar-position",Qo="width-before-scroll-bar",Dv="with-scroll-bars-hidden",Lv="--removed-body-scroll-bar-size";function Bi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function $v(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Fv=typeof window<"u"?v.useLayoutEffect:v.useEffect,vu=new WeakMap;function Bv(e,t){var n=$v(null,function(r){return e.forEach(function(o){return Bi(o,r)})});return Fv(function(){var r=vu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Bi(a,null)}),s.forEach(function(a){o.has(a)||Bi(a,i)})}vu.set(n,e)},[e]),n}function zv(e){return e}function Uv(e,t){t===void 0&&(t=zv);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Hv(e){e===void 0&&(e={});var t=Uv(null);return t.options=xn({async:!0,ssr:!1},e),t}var wu=function(e){var t=e.sideCar,n=yu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,xn({},n))};wu.isSideCarExport=!0;function Wv(e,t){return e.useMedium(t),wu}var bu=Hv(),zi=function(){},es=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:zi,onWheelCapture:zi,onTouchMoveCapture:zi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,g=e.noIsolation,m=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,S=e.gapMode,k=yu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,T=Bv([n,t]),E=xn(xn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(C,{sideCar:bu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:g,inert:m,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),xn(xn({},E),{ref:T})):v.createElement(w,xn({},E,{className:l,ref:T}),a))});es.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},es.classNames={fullWidth:Qo,zeroRight:Zo};var Vv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Kv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Vv();return t&&e.setAttribute("nonce",t),e}function qv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Gv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Yv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Kv())&&(qv(t,n),Gv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Xv=function(){var e=Yv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Su=function(){var e=Xv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Jv={left:0,top:0,right:0,gap:0},Ui=function(e){return parseInt(e||"",10)||0},Zv=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Ui(n),Ui(r),Ui(o)]},Qv=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Jv;var t=Zv(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},ew=Su(),vr="data-scroll-locked",tw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
38
|
+
`)}const xx=["message.start","message.delta","message.end"],yx=["tool.start","tool.end","tool.progress"],vx=["thread_info","checkpoint"],wx=["error","interrupt","heartbeat","state_history","cancelled"],bx=[...xx,...yx,...vx,...wx],Sx=new Set(bx);function Cx(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return Sx.has(t)}const cc=200;function Tx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=b.useRef(null),f=b.useRef(null),p=b.useRef(new Map),h=b.useRef(null),g=b.useRef(null),m=b.useCallback(M=>{try{const A=globalThis.structuredClone;if(typeof A=="function")return A(M)}catch{}try{return JSON.parse(JSON.stringify(M))}catch{return M}},[]),y=b.useCallback((M,A)=>{if(!M)return;const F=p.current.get(M)??[],L=m(A),R=F.length>=cc?[...F.slice(F.length-cc+1),L]:[...F,L];p.current.set(M,R)},[m]),x=b.useCallback(M=>{M&&p.current.set(M,[])},[]),w=b.useCallback(M=>{const A=M??f.current;if(!A)return;const F=p.current.get(A);F!=null&&F.length&&F.forEach(L=>{try{n(L)}catch(R){console.error("[useChatStreamingService] Failed to replay buffered event",R)}})},[n]),S=b.useCallback(M=>{f.current=M.threadId,h.current&&(h.current.threadIdGuess=M.threadId),g.current=M,x(M.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",M);try{t(M)}catch(A){console.error("[useChatStreamingService] Error in onThreadInfo handler:",A)}},[x,t]),k=b.useCallback(M=>{try{c==null||c(M)}catch(A){console.error("[useChatStreamingService] Error in onHeartbeat handler:",A)}},[c]),C=b.useCallback(M=>{var L,R,z,X;const A=M;if(A.error_type==="auth_error"||A.code==="TOKEN_EXPIRED"||((L=A.message)==null?void 0:L.includes("token"))||((R=A.message)==null?void 0:R.includes("401"))||((z=A.message)==null?void 0:z.includes("unauthorized"))||((X=A.message)==null?void 0:X.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",A.message);try{l==null||l(A.message)}catch(ne){console.warn("[useChatStreamingService] onAuthError handler failed",ne)}}},[l]),T=b.useMemo(()=>({thread_info:M=>(S(M),!0),heartbeat:M=>(k(M),!0),error:M=>(C(M),!1)}),[S,k,C]),E=b.useCallback(M=>{var R;const A=M.seq??null;if(A!==null){const z=d.current;if(z!==null){if(A<=z)return;A>z+1&&(s==null||s({from:z,to:A}))}d.current=A}const F=T[M.type];if(F&&F(M))return;const L=M.threadId??(M.type==="state_history"?M.threadId:void 0)??f.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(M.type==="state_history"){f.current=L??f.current;try{r==null||r(M)}catch(z){console.error("[useChatStreamingService] onStateHistory handler failed",z)}}if(Cx(M)){M.type==="checkpoint"||M.type==="state_history"?x(L??null):y(L??null,M);try{n(M)}catch(z){console.error("[useChatStreamingService] Error in onMessageEvent handler:",z)}return}try{o==null||o(M)}catch(z){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",z)}},[y,x,n,s,r,o,T]),{stream:N,stop:_,isStreaming:D,error:B,setToken:G}=lc({baseUrl:e,token:void 0}),V=b.useCallback((M,A)=>{d.current=null,g.current=null,f.current=M.threadId??null,h.current={request:M,callbacks:A,manualStop:!1,threadIdGuess:M.threadId??null},N(M,E,{onOpen:A==null?void 0:A.onOpen,onError:F=>{var L;(L=A==null?void 0:A.onError)==null||L.call(A,F)},onGap:(A==null?void 0:A.onGap)??s,onConnectionError:F=>{var L;a==null||a(F),(L=A==null?void 0:A.onConnectionError)==null||L.call(A,F)},onAuthError:F=>{var L;l==null||l(F),(L=A==null?void 0:A.onAuthError)==null||L.call(A,F)},onHeartbeat:F=>{var L;try{c==null||c(F)}catch(R){console.warn("[useChatStreamingService] onHeartbeat handler failed",R)}try{(L=A==null?void 0:A.onHeartbeat)==null||L.call(A,F)}catch(R){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",R)}},onClosed:F=>{var X,ne,ye,Te;const L=((X=h.current)==null?void 0:X.manualStop)??!1,R=f.current??((ne=h.current)==null?void 0:ne.threadIdGuess)??((ye=F.lastStateHistory)==null?void 0:ye.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&L)&&x(R);const z={...F,threadId:R,threadInfo:g.current,manualStop:L};try{i==null||i(z)}catch(q){console.warn("[useChatStreamingService] onStreamClosed handler failed",q)}try{(Te=A==null?void 0:A.onClosed)==null||Te.call(A,z)}catch(q){console.warn("[useChatStreamingService] downstream onClosed handler failed",q)}h.current&&(h.current=null)}})},[x,E,l,a,c,s,i,N]),P=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),_()},[_]);return b.useMemo(()=>({startStream:V,stop:P,isStreaming:D,error:B,setAuthToken:G,replayBufferedEvents:w}),[V,P,D,B,G,w])}const uc=b.createContext(null),dc=b.createContext(null),fc=b.createContext(null);b.createContext(!1);function kx({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l}){const{api:c,baseUrl:d}=di(),f=b.useMemo(()=>Cn(d),[d]),[p,h]=b.useState([]),[g,m]=b.useState(t),[y,x]=b.useState(!1),[w,S]=b.useState(null),[k,C]=b.useState(!1),[T,E]=b.useState(null),{state:N,seed:_,prepend:D,pushUser:B,onEvent:G}=ic(),[V,P]=b.useState(!1),[M,A]=b.useState(!1),[F,L]=b.useState(null),[R,z]=b.useState([]),[X,ne]=b.useState([]),[ye,Te]=b.useState(!1),q=b.useMemo(()=>Xg(R),[R]),U=b.useRef(g),Z=b.useRef(null),$=b.useRef(null),Y=b.useRef(null),Q=b.useRef(null),de=b.useRef(!1),oe=b.useRef(null),_e=b.useRef(new Map),ze=b.useRef(new Map);b.useEffect(()=>{U.current=g},[g]);const se=b.useCallback(async H=>{var J,re;if(!H.threadId)return;const j=H.threadId;(J=H.onStart)==null||J.call(H),H.setLoading(!0);try{await H.action(j)}catch(ie){if(U.current===j){const ce=String(ie);(re=H.handleError)==null||re.call(H,ce),s==null||s(ce)}throw ie}finally{H.setLoading(!1)}},[s]),me=b.useCallback(async()=>{x(!0),S(null);try{const H=await c.listThreads();h(H??[])}catch(H){const j=String(H);S(j),s==null||s(j)}finally{x(!1)}},[c,s]),Pe=b.useCallback(H=>{if(!(H!=null&&H.threadId))return;const j={threadId:H.threadId,title:H.title||`Thread ${H.threadId.slice(0,8)}`,createdAt:H.createdAt||new Date().toISOString(),updatedAt:H.updatedAt||new Date().toISOString(),messageCount:H.messageCount??1};h(J=>{let re=!1;const ie=J.map(ce=>ce.threadId===j.threadId?(re=!0,console.debug("[ChatSessionProvider] thread_info: updating existing thread",j.threadId),{...ce,title:j.title??ce.title,updatedAt:j.updatedAt??ce.updatedAt,messageCount:j.messageCount??ce.messageCount}):ce);return re?ie:(console.debug("[ChatSessionProvider] thread_info: adding thread to list",j.threadId),[j,...J])})},[]),Ve=b.useCallback(H=>{const j=H.threadId??U.current;if(!j||U.current&&U.current!==j)return;const{checkpoints:J,timeline:re}=dr(H);if(!J.length)return;const ie=J.find(ce=>ce.messages&&ce.messages.length>0)??J.find(ce=>!!ce.checkpointId)??J[0];_((ie==null?void 0:ie.messages)??[],{checkpointId:(ie==null?void 0:ie.checkpointId)??null,checkpointNs:(ie==null?void 0:ie.checkpointNs)??null}),ne(re),z(J),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null),oe.current=`${j}:latest`,$.current=null,Y.current=null},[_]),ut=b.useCallback(H=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",H.threadId),Pe(H),U.current!==H.threadId&&((H.created??!U.current)&&($.current=H.threadId),Y.current=H.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),m(H.threadId))},[Pe]),{startStream:Ke,stop:qe,isStreaming:Qe,error:Ge,setAuthToken:et}=Tx({baseUrl:f,onThreadInfo:ut,onMessageEvent:G,onStateHistory:Ve,onUnhandledEvent:H=>{console.warn("[ChatSessionProvider] Unhandled event:",H.type)},onAuthError:i,onConnectionError:l}),st=b.useCallback(async H=>{try{const j=await c.createThread(H);return m(j.threadId),await me(),j.threadId}catch(j){return s==null||s(String(j)),null}},[c,me,s]),Mt=b.useCallback(async H=>{const j=p;h(re=>re.filter(ie=>ie.threadId!==H));const J=new AbortController;ze.current.set(H,J);try{await c.deleteThread(H),U.current===H&&(m(null),_([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",H)}catch(re){console.error("[ChatSessionProvider] Delete failed, restoring thread:",H,re),h(j),s==null||s(`Failed to delete thread: ${String(re)}`)}finally{ze.current.delete(H)}},[p,c,_,s]),gt=b.useCallback(async(H,j)=>{try{await c.updateThread(H,j),await me()}catch(J){s==null||s(String(J))}},[c,me,s]),Ct=b.useCallback(async(H,j)=>{if(!H)return;const J=`${H}:${j??"latest"}`,re=_e.current.get(J);if(re)return re;const ie=se({threadId:H,setLoading:C,onStart:()=>E(null),handleError:ce=>E(ce),action:async ce=>{const Xe=await c.getStateHistory({threadId:ce,checkpointId:j||void 0});if(U.current!==ce){console.log(`[ChatSessionProvider] Thread changed during load (was ${ce}, now ${U.current}), discarding stale data`);return}const{checkpoints:Ie,timeline:at}=dr(Xe),ht=Ie.find(Kt=>Kt.messages&&Kt.messages.length>0)??(j?Ie.find(Kt=>Kt.checkpointId===j):null)??Ie[0];_((ht==null?void 0:ht.messages)??[],{checkpointId:(ht==null?void 0:ht.checkpointId)??null,checkpointNs:(ht==null?void 0:ht.checkpointNs)??null}),ne(at),z(Ie),P(!!(ht!=null&&ht.nextCursor)),L((ht==null?void 0:ht.nextCursor)??null)}});_e.current.set(J,ie);try{await ie}finally{_e.current.delete(J)}return U.current===H&&(oe.current=J),ie},[c,_,s,se]),it=b.useCallback(async(H,j,J)=>{J!=null&&J.clearProgress&&Jl(),Q.current=H;try{await Ct(H,j)}finally{Q.current===H&&(Q.current=null)}},[Ct]);b.useEffect(()=>{if(!o||!g||k||Qe)return;if($.current===g){$.current=null,Z.current=g;return}if(Y.current===g){Z.current=g;return}if(Q.current===g){Q.current=null,Z.current=g;return}if(Z.current===g)return;Z.current=g;const H=!de.current&&!!n&&g===t;let j;H&&n?(j=n,de.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",j,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const J=`${g}:${j??"latest"}`;oe.current!==J&&it(g,j)},[o,g,n,r,t,k,Qe,it]);const St=b.useCallback(async(H,j)=>{Jl();const J=U.current;await se({threadId:J,setLoading:Te,action:async re=>{const ie=await c.getStateHistory({threadId:re,checkpointId:H,checkpointNs:j??void 0});if(U.current!==re){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${re}, now ${U.current}), discarding stale data`);return}const{checkpoints:ce,timeline:Xe}=dr(ie),Ie=ce.find(at=>at.checkpointId===H&&(j?at.checkpointNs===j:!0));if(!Ie){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:H,checkpointNs:j});return}ne(Xe),z(ce),_(Ie.messages??[],{checkpointId:Ie.checkpointId??null,checkpointNs:Ie.checkpointNs??null})}}).catch(()=>{})},[c,_,s,se]),Pt=b.useCallback((H,j)=>{_(N.messages,{checkpointId:H??null,checkpointNs:j??null})},[_,N.messages]),zt=b.useCallback(async()=>{U.current&&await it(U.current)},[it]),nn=b.useCallback(async()=>{const H=U.current;!H||!F||await se({threadId:H,setLoading:A,action:async j=>{const J=await c.getStateHistory({threadId:j,checkpointId:F});if(U.current!==j)return;const{checkpoints:re}=dr(J);if(re.length>0){const ie=re[re.length-1];D((ie==null?void 0:ie.messages)??[]),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null)}}}).catch(()=>{})},[c,F,D,s,se]),Le=b.useCallback(async()=>{_([],{}),m(null),qe(),z([]),ne([]),P(!1),L(null),C(!1),Te(!1),A(!1),E(null);try{await c.getAgent("default")}catch(H){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",H)}},[_,qe,c]),Sn=b.useCallback(async(H,j,J)=>{const re=U.current;if(!re)throw new Error("No active thread to handle interrupt");const ie=j?J??!0:!1;try{const ce={threadId:re,checkpointId:N.lastCheckpointId??void 0,checkpointNs:N.lastCheckpointNs??void 0,command:{kind:"resume",value:ie}};Ke(ce)}catch(ce){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${H}:`,ce),ce}},[N.lastCheckpointId,N.lastCheckpointNs,Ke]);b.useEffect(()=>{me()},[me]),b.useEffect(()=>{a==null||a(g)},[g,a]);const tt=b.useCallback(async(H,j)=>{let J=U.current;const re=(H==null?void 0:H.text)??"",ie=(H==null?void 0:H.attachments)??[],ce=(re==null?void 0:re.trim())??"",Xe={...(H==null?void 0:H.payload)??{}},Ie=Array.isArray(Xe.messages)?Xe.messages:void 0;Ie&&delete Xe.messages;const at=!!(Ie&&Ie.length);if(!J&&!ce&&ie.length===0&&!at)return;if(!J){const we=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Be=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);J=`${we}${Be}`,$.current=J,m(J)}const{contentParts:ht,filesInfo:Kt}=await kg(c,ie),Hn=[...ht];ce&&Hn.push({type:"text",text:re});const Ar=j==null?void 0:j.originalMessageId,Nr=!!(j!=null&&j.edit&&Ar),po=!at&&Hn.length>0;let Nn=null;po&&(Nn={id:Nr?Ar:`msg-${Date.now()}`,role:"user",content:Hn,createdAt:new Date().toISOString()},Nr||B(Nn));const I=at?Ie:Nn?[Nn]:[],W={...Xe,...Kt.length?{files_info:Kt}:{}};I.length?W.messages=I:"messages"in W||(W.messages=[]);const ae={threadId:J,payload:W,checkpointId:(j==null?void 0:j.checkpointId)??N.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??N.lastCheckpointNs??void 0,edit:!!(j!=null&&j.edit),timelineCheckpoints:X};Ke(ae)},[c,B,N,Ke,X]),We=b.useMemo(()=>({threads:p,currentThreadId:g,setCurrentThreadId:m,isLoading:y,error:w,actions:{createThread:st,deleteThread:Mt,renameThread:gt,refreshThreads:me}}),[p,g,y,w,st,Mt,gt,me]),pt=b.useMemo(()=>{const H=N.assemblingId??null;return H?{assemblingMessageId:H}:null},[N.assemblingId]),Rt=b.useMemo(()=>({threadId:g,messages:N.messages,interrupt:null,checkpoint:{id:N.lastCheckpointId??null,namespace:N.lastCheckpointNs??null},checkpoints:R,timelineCheckpoints:X,metadata:pt,isLoading:k,isHistoryLoading:M,isLoadingCheckpoint:ye,error:T,hasMore:V,loadOlder:nn,clearState:Le,navigateToCheckpoint:St,setCurrentCheckpointId:Pt,returnToLatest:zt,loadThread:it,clearThread:Le,respondToInterrupt:Sn,messagePreviews:q}),[g,N,R,X,k,M,ye,T,V,nn,Le,St,Pt,zt,it,Sn,q,pt]),Ye=b.useMemo(()=>({isStreaming:Qe,error:Ge,connectionState:Qe?"connected":"idle",submit:tt,send:tt,stop:qe,setAuthToken:et}),[Qe,Ge,tt,qe,et]);return u.jsx(uc.Provider,{value:We,children:u.jsx(dc.Provider,{value:Rt,children:u.jsx(fc.Provider,{value:Ye,children:e})})})}function jo(){const e=b.useContext(uc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Mo(){const e=b.useContext(dc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function pc(){const e=b.useContext(fc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Po({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Cg,{apiConfig:t,children:u.jsx(kx,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,children:e})})}function te(...e){return Xh.twMerge(Yh.clsx(e))}const Ex=ho.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Je=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Vn.Slot:"button";return u.jsx(i,{className:te(Ex({variant:t,size:n,className:e})),ref:s,...o})});Je.displayName="Button";const hc=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));hc.displayName="Textarea";function mc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:p="",allowEmptySend:h=!1}){const g=i!==void 0,[m,y]=b.useState(e),x=(g?i:m)??"",[w,S]=b.useTransition(),k=b.useRef(null),C=b.useRef(0),T=b.useRef(null);b.useEffect(()=>{g||(y(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,g]);const E=b.useCallback(()=>{const M=k.current;M&&(M.style.height="auto",M.style.height=`${M.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const N=b.useCallback((M,{fromUser:A})=>{g||y(M),A&&(a==null||a(M))},[g,a]),_=b.useCallback(async M=>{M&&M.preventDefault();const A=(x??"").trim();if(!A&&!h)return;const F=++C.current;T.current={id:F,shouldClear:!0},S(()=>{var L,R,z;try{const X=l(A);X&&typeof X.then=="function"?X.then(()=>{var ne,ye;((ne=T.current)==null?void 0:ne.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((ye=T.current)==null?void 0:ye.id)===F&&(T.current=null)}).catch(()=>{var ne;((ne=T.current)==null?void 0:ne.id)===F&&(T.current=null)}):(((L=T.current)==null?void 0:L.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((R=T.current)==null?void 0:R.id)===F&&(T.current=null))}catch{((z=T.current)==null?void 0:z.id)===F&&(T.current=null)}})},[x,l,h,g,a]),D=b.useCallback(M=>{const A=M.target.value;N(A,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),B=b.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),_()):M.key==="Escape"&&t&&(M.preventDefault(),c==null||c())},[_,t,c]),P=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${p}`;return u.jsx("form",{onSubmit:M=>void _(M),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(hc,{ref:k,value:x,onChange:D,onKeyDown:B,placeholder:t?"Edit your message...":n,className:P,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(Je,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(le.Square,{size:16})}):u.jsx(Je,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!h||w,children:u.jsx(le.Send,{size:16})})})]})})}const Ix=b.memo(mc);function pe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function gc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function gi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=gc(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():gc(e[o],null)}}}}function $e(...e){return v.useCallback(gi(...e),e)}function Ax(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Tn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:p,children:h,...g}=f,m=((x=p==null?void 0:p[e])==null?void 0:x[l])||a,y=v.useMemo(()=>g,Object.values(g));return u.jsx(m.Provider,{value:y,children:h})};c.displayName=s+"Provider";function d(f,p){var m;const h=((m=p==null?void 0:p[e])==null?void 0:m[l])||a,g=v.useContext(h);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Nx(o,...t)]}function Nx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},_x=v[" useInsertionEffect ".trim().toString()]||kt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=jx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const p=Mx(d)?d(e):d;p!==e&&((f=i.current)==null||f.call(i,p))}else s(d)},[a,e,s,i]);return[l,c]}function jx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return _x(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Mx(e){return typeof e=="function"}var Px=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ne=Px.reduce((e,t)=>{const n=Vn.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function xc(e,t){e&&mo.flushSync(()=>e.dispatchEvent(t))}function xi(e){const t=e+"CollectionProvider",[n,r]=Tn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:y,children:x}=m,w=b.useRef(null),S=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=Vn.createSlot(a),c=b.forwardRef((m,y)=>{const{scope:x,children:w}=m,S=s(a,x),k=$e(y,S.collectionRef);return u.jsx(l,{ref:k,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=Vn.createSlot(d),h=b.forwardRef((m,y)=>{const{scope:x,children:w,...S}=m,k=b.useRef(null),C=$e(y,k),T=s(d,x);return b.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:C,children:w})});h.displayName=d;function g(m){const y=s(e+"CollectionConsumer",m);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},g,r]}var Rx=v.createContext(void 0);function Ro(e){const t=v.useContext(Rx);return e||t||"ltr"}function Et(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ox(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Dx="DismissableLayer",yi="dismissableLayer.update",Lx="dismissableLayer.pointerDownOutside",$x="dismissableLayer.focusOutside",yc,vc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Oo=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(vc),[d,f]=v.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),g=$e(t,E=>f(E)),m=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=m.indexOf(y),w=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=x,C=zx(E=>{const N=E.target,_=[...c.branches].some(D=>D.contains(N));!k||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),T=Ux(E=>{const N=E.target;[...c.branches].some(D=>D.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return Ox(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(yc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),wc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=yc)}},[d,p,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),wc())},[d,c]),v.useEffect(()=>{const E=()=>h({});return document.addEventListener(yi,E),()=>document.removeEventListener(yi,E)},[]),u.jsx(Ne.div,{...l,ref:g,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:pe(e.onFocusCapture,T.onFocusCapture),onBlurCapture:pe(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:pe(e.onPointerDownCapture,C.onPointerDownCapture)})});Oo.displayName=Dx;var Fx="DismissableLayerBranch",Bx=v.forwardRef((e,t)=>{const n=v.useContext(vc),r=v.useRef(null),o=$e(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ne.div,{...e,ref:o})});Bx.displayName=Fx;function zx(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){bc(Lx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Ux(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&bc($x,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function wc(){const e=new CustomEvent(yi);document.dispatchEvent(e)}function bc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?xc(o,s):o.dispatchEvent(s)}var vi=0;function wi(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Sc()),document.body.insertAdjacentElement("beforeend",e[1]??Sc()),vi++,()=>{vi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),vi--}},[])}function Sc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var bi="focusScope.autoFocusOnMount",Si="focusScope.autoFocusOnUnmount",Cc={bubbles:!1,cancelable:!0},Hx="FocusScope",Do=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=Et(o),d=Et(s),f=v.useRef(null),p=$e(t,m=>l(m)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(S){if(h.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:jn(f.current,{select:!0})},y=function(S){if(h.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||jn(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&jn(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,h.paused]),v.useEffect(()=>{if(a){Ec.add(h);const m=document.activeElement;if(!a.contains(m)){const x=new CustomEvent(bi,Cc);a.addEventListener(bi,c),a.dispatchEvent(x),x.defaultPrevented||(Wx(Yx(Tc(a)),{select:!0}),document.activeElement===m&&jn(a))}return()=>{a.removeEventListener(bi,c),setTimeout(()=>{const x=new CustomEvent(Si,Cc);a.addEventListener(Si,d),a.dispatchEvent(x),x.defaultPrevented||jn(m??document.body,{select:!0}),a.removeEventListener(Si,d),Ec.remove(h)},0)}}},[a,c,d,h]);const g=v.useCallback(m=>{if(!n&&!r||h.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,x=document.activeElement;if(y&&x){const w=m.currentTarget,[S,k]=Vx(w);S&&k?!m.shiftKey&&x===k?(m.preventDefault(),n&&jn(S,{select:!0})):m.shiftKey&&x===S&&(m.preventDefault(),n&&jn(k,{select:!0})):x===w&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Ne.div,{tabIndex:-1,...i,ref:p,onKeyDown:g})});Do.displayName=Hx;function Wx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(jn(r,{select:t}),document.activeElement!==n)return}function Vx(e){const t=Tc(e),n=kc(t,e),r=kc(t.reverse(),e);return[n,r]}function Tc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function kc(e,t){for(const n of e)if(!Kx(n,{upTo:t}))return n}function Kx(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function qx(e){return e instanceof HTMLInputElement&&"select"in e}function jn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&qx(e)&&t&&e.select()}}var Ec=Gx();function Gx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ic(e,t),e.unshift(t)},remove(t){var n;e=Ic(e,t),(n=e[0])==null||n.resume()}}}function Ic(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Yx(e){return e.filter(t=>t.tagName!=="A")}var Xx=v[" useId ".trim().toString()]||(()=>{}),Jx=0;function kn(e){const[t,n]=v.useState(Xx());return kt(()=>{n(r=>r??String(Jx++))},[e]),t?`radix-${t}`:""}const Zx=["top","right","bottom","left"],Mn=Math.min,Ut=Math.max,Lo=Math.round,$o=Math.floor,pn=e=>({x:e,y:e}),Qx={left:"right",right:"left",bottom:"top",top:"bottom"},ey={start:"end",end:"start"};function Ci(e,t,n){return Ut(e,Mn(t,n))}function En(e,t){return typeof e=="function"?e(t):e}function In(e){return e.split("-")[0]}function hr(e){return e.split("-")[1]}function Ti(e){return e==="x"?"y":"x"}function ki(e){return e==="y"?"height":"width"}const ty=new Set(["top","bottom"]);function hn(e){return ty.has(In(e))?"y":"x"}function Ei(e){return Ti(hn(e))}function ny(e,t,n){n===void 0&&(n=!1);const r=hr(e),o=Ei(e),s=ki(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Fo(i)),[i,Fo(i)]}function ry(e){const t=Fo(e);return[Ii(e),t,Ii(t)]}function Ii(e){return e.replace(/start|end/g,t=>ey[t])}const Ac=["left","right"],Nc=["right","left"],oy=["top","bottom"],sy=["bottom","top"];function iy(e,t,n){switch(e){case"top":case"bottom":return n?t?Nc:Ac:t?Ac:Nc;case"left":case"right":return t?oy:sy;default:return[]}}function ay(e,t,n,r){const o=hr(e);let s=iy(In(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ii)))),s}function Fo(e){return e.replace(/left|right|bottom|top/g,t=>Qx[t])}function ly(e){return{top:0,right:0,bottom:0,left:0,...e}}function _c(e){return typeof e!="number"?ly(e):{top:e,right:e,bottom:e,left:e}}function Bo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function jc(e,t,n){let{reference:r,floating:o}=e;const s=hn(t),i=Ei(t),a=ki(i),l=In(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:d,y:r.y-o.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:f};break;case"left":h={x:r.x-o.width,y:f};break;default:h={x:r.x,y:r.y}}switch(hr(t)){case"start":h[i]-=p*(n&&c?-1:1);break;case"end":h[i]+=p*(n&&c?-1:1);break}return h}const cy=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=jc(c,r,l),p=r,h={},g=0;for(let m=0;m<a.length;m++){const{name:y,fn:x}=a[m],{x:w,y:S,data:k,reset:C}=await x({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,h={...h,[y]:{...h[y],...k}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:f}=jc(c,p,l)),m=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function $r(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:h=0}=En(t,e),g=_c(h),y=a[p?f==="floating"?"reference":"floating":f],x=Bo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},C=Bo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(x.top-C.top+g.top)/k.y,bottom:(C.bottom-x.bottom+g.bottom)/k.y,left:(x.left-C.left+g.left)/k.x,right:(C.right-x.right+g.right)/k.x}}const uy=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=En(e,t)||{};if(c==null)return{};const f=_c(d),p={x:n,y:r},h=Ei(o),g=ki(h),m=await i.getDimensions(c),y=h==="y",x=y?"top":"left",w=y?"bottom":"right",S=y?"clientHeight":"clientWidth",k=s.reference[g]+s.reference[h]-p[h]-s.floating[g],C=p[h]-s.reference[h],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[g]);const N=k/2-C/2,_=E/2-m[g]/2-1,D=Mn(f[x],_),B=Mn(f[w],_),G=D,V=E-m[g]-B,P=E/2-m[g]/2+N,M=Ci(G,P,V),A=!l.arrow&&hr(o)!=null&&P!==M&&s.reference[g]/2-(P<G?D:B)-m[g]/2<0,F=A?P<G?P-G:P-V:0;return{[h]:p[h]+F,data:{[h]:M,centerOffset:P-M-F,...A&&{alignmentOffset:F}},reset:A}}}),dy=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...y}=En(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=In(o),w=hn(a),S=In(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(S||!m?[Fo(a)]:ry(a)),T=g!=="none";!p&&T&&C.push(...ay(a,m,g,k));const E=[a,...C],N=await $r(t,y),_=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(N[x]),f){const P=ny(o,i,k);_.push(N[P[0]],N[P[1]])}if(D=[...D,{placement:o,overflows:_}],!_.every(P=>P<=0)){var B,G;const P=(((B=s.flip)==null?void 0:B.index)||0)+1,M=E[P];if(M&&(!(f==="alignment"?w!==hn(M):!1)||D.every(L=>hn(L.placement)===w?L.overflows[0]>0:!0)))return{data:{index:P,overflows:D},reset:{placement:M}};let A=(G=D.filter(F=>F.overflows[0]<=0).sort((F,L)=>F.overflows[1]-L.overflows[1])[0])==null?void 0:G.placement;if(!A)switch(h){case"bestFit":{var V;const F=(V=D.filter(L=>{if(T){const R=hn(L.placement);return R===w||R==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(R=>R>0).reduce((R,z)=>R+z,0)]).sort((L,R)=>L[1]-R[1])[0])==null?void 0:V[0];F&&(A=F);break}case"initialPlacement":A=a;break}if(o!==A)return{reset:{placement:A}}}return{}}}};function Mc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Pc(e){return Zx.some(t=>e[t]>=0)}const fy=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=En(e,t);switch(r){case"referenceHidden":{const s=await $r(t,{...o,elementContext:"reference"}),i=Mc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Pc(i)}}}case"escaped":{const s=await $r(t,{...o,altBoundary:!0}),i=Mc(s,n.floating);return{data:{escapedOffsets:i,escaped:Pc(i)}}}default:return{}}}}},Rc=new Set(["left","top"]);async function py(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=In(n),a=hr(n),l=hn(n)==="y",c=Rc.has(i)?-1:1,d=s&&l?-1:1,f=En(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:g}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof g=="number"&&(h=a==="end"?g*-1:g),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const hy=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await py(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},my=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:w}=y;return{x,y:w}}},...l}=En(e,t),c={x:n,y:r},d=await $r(t,l),f=hn(In(o)),p=Ti(f);let h=c[p],g=c[f];if(s){const y=p==="y"?"top":"left",x=p==="y"?"bottom":"right",w=h+d[y],S=h-d[x];h=Ci(w,h,S)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=g+d[y],S=g-d[x];g=Ci(w,g,S)}const m=a.fn({...t,[p]:h,[f]:g});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[f]:i}}}}}},gy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=En(e,t),d={x:n,y:r},f=hn(o),p=Ti(f);let h=d[p],g=d[f];const m=En(a,t),y=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=p==="y"?"height":"width",k=s.reference[p]-s.floating[S]+y.mainAxis,C=s.reference[p]+s.reference[S]-y.mainAxis;h<k?h=k:h>C&&(h=C)}if(c){var x,w;const S=p==="y"?"width":"height",k=Rc.has(In(o)),C=s.reference[f]-s.floating[S]+(k&&((x=i.offset)==null?void 0:x[f])||0)+(k?0:y.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((w=i.offset)==null?void 0:w[f])||0)-(k?y.crossAxis:0);g<C?g=C:g>T&&(g=T)}return{[p]:h,[f]:g}}}},xy=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=En(e,t),d=await $r(t,c),f=In(o),p=hr(o),h=hn(o)==="y",{width:g,height:m}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=p==="end"?"top":"bottom");const w=m-d.top-d.bottom,S=g-d.left-d.right,k=Mn(m-d[y],w),C=Mn(g-d[x],S),T=!t.middlewareData.shift;let E=k,N=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),T&&!p){const D=Ut(d.left,0),B=Ut(d.right,0),G=Ut(d.top,0),V=Ut(d.bottom,0);h?N=g-2*(D!==0||B!==0?D+B:Ut(d.left,d.right)):E=m-2*(G!==0||V!==0?G+V:Ut(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const _=await i.getDimensions(a.floating);return g!==_.width||m!==_.height?{reset:{rects:!0}}:{}}}};function zo(){return typeof window<"u"}function mr(e){return Oc(e)?(e.nodeName||"").toLowerCase():"#document"}function Ht(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function mn(e){var t;return(t=(Oc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Oc(e){return zo()?e instanceof Node||e instanceof Ht(e).Node:!1}function sn(e){return zo()?e instanceof Element||e instanceof Ht(e).Element:!1}function gn(e){return zo()?e instanceof HTMLElement||e instanceof Ht(e).HTMLElement:!1}function Dc(e){return!zo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ht(e).ShadowRoot}const yy=new Set(["inline","contents"]);function Fr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!yy.has(o)}const vy=new Set(["table","td","th"]);function wy(e){return vy.has(mr(e))}const by=[":popover-open",":modal"];function Uo(e){return by.some(t=>{try{return e.matches(t)}catch{return!1}})}const Sy=["transform","translate","scale","rotate","perspective"],Cy=["transform","translate","scale","rotate","perspective","filter"],Ty=["paint","layout","strict","content"];function Ai(e){const t=Ni(),n=sn(e)?an(e):e;return Sy.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Cy.some(r=>(n.willChange||"").includes(r))||Ty.some(r=>(n.contain||"").includes(r))}function ky(e){let t=Pn(e);for(;gn(t)&&!gr(t);){if(Ai(t))return t;if(Uo(t))return null;t=Pn(t)}return null}function Ni(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Ey=new Set(["html","body","#document"]);function gr(e){return Ey.has(mr(e))}function an(e){return Ht(e).getComputedStyle(e)}function Ho(e){return sn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Pn(e){if(mr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Dc(e)&&e.host||mn(e);return Dc(t)?t.host:t}function Lc(e){const t=Pn(e);return gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:gn(t)&&Fr(t)?t:Lc(t)}function Br(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Lc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Ht(o);if(s){const a=_i(i);return t.concat(i,i.visualViewport||[],Fr(o)?o:[],a&&n?Br(a):[])}return t.concat(o,Br(o,[],n))}function _i(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function $c(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=gn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Lo(n)!==s||Lo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ji(e){return sn(e)?e:e.contextElement}function xr(e){const t=ji(e);if(!gn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=$c(t);let i=(s?Lo(n.width):n.width)/r,a=(s?Lo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Iy=pn(0);function Fc(e){const t=Ht(e);return!Ni()||!t.visualViewport?Iy:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Ay(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Ht(e)?!1:t}function Yn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ji(e);let i=pn(1);t&&(r?sn(r)&&(i=xr(r)):i=xr(e));const a=Ay(s,n,r)?Fc(s):pn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const p=Ht(s),h=r&&sn(r)?Ht(r):r;let g=p,m=_i(g);for(;m&&r&&h!==g;){const y=xr(m),x=m.getBoundingClientRect(),w=an(m),S=x.left+(m.clientLeft+parseFloat(w.paddingLeft))*y.x,k=x.top+(m.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=k,g=Ht(m),m=_i(g)}}return Bo({width:d,height:f,x:l,y:c})}function Wo(e,t){const n=Ho(e).scrollLeft;return t?t.left+n:Yn(mn(e)).left+n}function Bc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Wo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Ny(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=mn(r),a=t?Uo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=gn(r);if((f||!f&&!s)&&((mr(r)!=="body"||Fr(i))&&(l=Ho(r)),gn(r))){const h=Yn(r);c=xr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?Bc(i,l):pn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+p.x,y:n.y*c.y-l.scrollTop*c.y+d.y+p.y}}function _y(e){return Array.from(e.getClientRects())}function jy(e){const t=mn(e),n=Ho(e),r=e.ownerDocument.body,o=Ut(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ut(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Wo(e);const a=-n.scrollTop;return an(r).direction==="rtl"&&(i+=Ut(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const zc=25;function My(e,t){const n=Ht(e),r=mn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ni();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Wo(r);if(c<=0){const d=r.ownerDocument,f=d.body,p=getComputedStyle(f),h=d.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,g=Math.abs(r.clientWidth-f.clientWidth-h);g<=zc&&(s-=g)}else c<=zc&&(s+=c);return{width:s,height:i,x:a,y:l}}const Py=new Set(["absolute","fixed"]);function Ry(e,t){const n=Yn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=gn(e)?xr(e):pn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Uc(e,t,n){let r;if(t==="viewport")r=My(e,n);else if(t==="document")r=jy(mn(e));else if(sn(t))r=Ry(t,n);else{const o=Fc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Bo(r)}function Hc(e,t){const n=Pn(e);return n===t||!sn(n)||gr(n)?!1:an(n).position==="fixed"||Hc(n,t)}function Oy(e,t){const n=t.get(e);if(n)return n;let r=Br(e,[],!1).filter(a=>sn(a)&&mr(a)!=="body"),o=null;const s=an(e).position==="fixed";let i=s?Pn(e):e;for(;sn(i)&&!gr(i);){const a=an(i),l=Ai(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Py.has(o.position)||Fr(i)&&!l&&Hc(e,i))?r=r.filter(d=>d!==i):o=a,i=Pn(i)}return t.set(e,r),r}function Dy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Uo(t)?[]:Oy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Uc(t,d,o);return c.top=Ut(f.top,c.top),c.right=Mn(f.right,c.right),c.bottom=Mn(f.bottom,c.bottom),c.left=Ut(f.left,c.left),c},Uc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Ly(e){const{width:t,height:n}=$c(e);return{width:t,height:n}}function $y(e,t,n){const r=gn(t),o=mn(t),s=n==="fixed",i=Yn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=Wo(o)}if(r||!r&&!s)if((mr(t)!=="body"||Fr(o))&&(a=Ho(t)),r){const h=Yn(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Bc(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,p=i.top+a.scrollTop-l.y-d.y;return{x:f,y:p,width:i.width,height:i.height}}function Mi(e){return an(e).position==="static"}function Wc(e,t){if(!gn(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return mn(e)===n&&(n=n.ownerDocument.body),n}function Vc(e,t){const n=Ht(e);if(Uo(e))return n;if(!gn(e)){let o=Pn(e);for(;o&&!gr(o);){if(sn(o)&&!Mi(o))return o;o=Pn(o)}return n}let r=Wc(e,t);for(;r&&wy(r)&&Mi(r);)r=Wc(r,t);return r&&gr(r)&&Mi(r)&&!Ai(r)?n:r||ky(e)||n}const Fy=async function(e){const t=this.getOffsetParent||Vc,n=this.getDimensions,r=await n(e.floating);return{reference:$y(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function By(e){return an(e).direction==="rtl"}const zy={convertOffsetParentRelativeRectToViewportRelativeRect:Ny,getDocumentElement:mn,getClippingRect:Dy,getOffsetParent:Vc,getElementRects:Fy,getClientRects:_y,getDimensions:Ly,getScale:xr,isElement:sn,isRTL:By};function Kc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Uy(e,t){let n=null,r;const o=mn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:p,height:h}=c;if(a||t(),!p||!h)return;const g=$o(f),m=$o(o.clientWidth-(d+p)),y=$o(o.clientHeight-(f+h)),x=$o(d),S={rootMargin:-g+"px "+-m+"px "+-y+"px "+-x+"px",threshold:Ut(0,Mn(1,l))||1};let k=!0;function C(T){const E=T[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Kc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(C,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return i(!0),s}function Hy(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=ji(e),d=o||s?[...c?Br(c):[],...Br(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Uy(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(x=>{let[w]=x;w&&w.target===c&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=h)==null||S.observe(t)})),n()}),c&&!l&&h.observe(c),h.observe(t));let g,m=l?Yn(e):null;l&&y();function y(){const x=Yn(e);m&&!Kc(m,x)&&n(),m=x,g=requestAnimationFrame(y)}return n(),()=>{var x;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(x=h)==null||x.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const Wy=hy,Vy=my,Ky=dy,qy=xy,Gy=fy,qc=uy,Yy=gy,Xy=(e,t,n)=>{const r=new Map,o={platform:zy,...n},s={...o.platform,_c:r};return cy(e,t,{...o,platform:s})};var Jy=typeof document<"u",Zy=function(){},Vo=Jy?b.useLayoutEffect:Zy;function Ko(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ko(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Ko(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Gc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Yc(e,t){const n=Gc(e);return Math.round(t*n)/n}function Pi(e){const t=v.useRef(e);return Vo(()=>{t.current=e}),t}function Qy(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=v.useState(r);Ko(p,r)||h(r);const[g,m]=v.useState(null),[y,x]=v.useState(null),w=v.useCallback(L=>{L!==T.current&&(T.current=L,m(L))},[]),S=v.useCallback(L=>{L!==E.current&&(E.current=L,x(L))},[]),k=s||g,C=i||y,T=v.useRef(null),E=v.useRef(null),N=v.useRef(d),_=l!=null,D=Pi(l),B=Pi(o),G=Pi(c),V=v.useCallback(()=>{if(!T.current||!E.current)return;const L={placement:t,strategy:n,middleware:p};B.current&&(L.platform=B.current),Xy(T.current,E.current,L).then(R=>{const z={...R,isPositioned:G.current!==!1};P.current&&!Ko(N.current,z)&&(N.current=z,mo.flushSync(()=>{f(z)}))})},[p,t,n,B,G]);Vo(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f(L=>({...L,isPositioned:!1})))},[c]);const P=v.useRef(!1);Vo(()=>(P.current=!0,()=>{P.current=!1}),[]),Vo(()=>{if(k&&(T.current=k),C&&(E.current=C),k&&C){if(D.current)return D.current(k,C,V);V()}},[k,C,V,D,_]);const M=v.useMemo(()=>({reference:T,floating:E,setReference:w,setFloating:S}),[w,S]),A=v.useMemo(()=>({reference:k,floating:C}),[k,C]),F=v.useMemo(()=>{const L={position:n,left:0,top:0};if(!A.floating)return L;const R=Yc(A.floating,d.x),z=Yc(A.floating,d.y);return a?{...L,transform:"translate("+R+"px, "+z+"px)",...Gc(A.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:R,top:z}},[n,a,A.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:V,refs:M,elements:A,floatingStyles:F}),[d,V,M,A,F])}const ev=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?qc({element:r.current,padding:o}).fn(n):{}:r?qc({element:r,padding:o}).fn(n):{}}}},tv=(e,t)=>({...Wy(e),options:[e,t]}),nv=(e,t)=>({...Vy(e),options:[e,t]}),rv=(e,t)=>({...Yy(e),options:[e,t]}),ov=(e,t)=>({...Ky(e),options:[e,t]}),sv=(e,t)=>({...qy(e),options:[e,t]}),iv=(e,t)=>({...Gy(e),options:[e,t]}),av=(e,t)=>({...ev(e),options:[e,t]});var lv="Arrow",Xc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Ne.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Xc.displayName=lv;var cv=Xc;function Jc(e){const[t,n]=v.useState(void 0);return kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ri="Popper",[Zc,qo]=Tn(Ri),[uv,Qc]=Zc(Ri),eu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(uv,{scope:t,anchor:r,onAnchorChange:o,children:n})};eu.displayName=Ri;var tu="PopperAnchor",nu=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Qc(tu,n),i=v.useRef(null),a=$e(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Ne.div,{...o,ref:a})});nu.displayName=tu;var Oi="PopperContent",[dv,fv]=Zc(Oi),ru=v.forwardRef((e,t)=>{var Z,$,Y,Q,de,oe;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:g,...m}=e,y=Qc(Oi,n),[x,w]=v.useState(null),S=$e(t,_e=>w(_e)),[k,C]=v.useState(null),T=Jc(k),E=(T==null?void 0:T.width)??0,N=(T==null?void 0:T.height)??0,_=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},B=Array.isArray(c)?c:[c],G=B.length>0,V={padding:D,boundary:B.filter(hv),altBoundary:G},{refs:P,floatingStyles:M,placement:A,isPositioned:F,middlewareData:L}=Qy({strategy:"fixed",placement:_,whileElementsMounted:(..._e)=>Hy(..._e,{animationFrame:h==="always"}),elements:{reference:y.anchor},middleware:[tv({mainAxis:o+N,alignmentAxis:i}),l&&nv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?rv():void 0,...V}),l&&ov({...V}),sv({...V,apply:({elements:_e,rects:ze,availableWidth:se,availableHeight:me})=>{const{width:Pe,height:Ve}=ze.reference,ut=_e.floating.style;ut.setProperty("--radix-popper-available-width",`${se}px`),ut.setProperty("--radix-popper-available-height",`${me}px`),ut.setProperty("--radix-popper-anchor-width",`${Pe}px`),ut.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),k&&av({element:k,padding:a}),mv({arrowWidth:E,arrowHeight:N}),p&&iv({strategy:"referenceHidden",...V})]}),[R,z]=iu(A),X=Et(g);kt(()=>{F&&(X==null||X())},[F,X]);const ne=(Z=L.arrow)==null?void 0:Z.x,ye=($=L.arrow)==null?void 0:$.y,Te=((Y=L.arrow)==null?void 0:Y.centerOffset)!==0,[q,U]=v.useState();return kt(()=>{x&&U(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:P.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:F?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:q,"--radix-popper-transform-origin":[(Q=L.transformOrigin)==null?void 0:Q.x,(de=L.transformOrigin)==null?void 0:de.y].join(" "),...((oe=L.hide)==null?void 0:oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(dv,{scope:n,placedSide:R,onArrowChange:C,arrowX:ne,arrowY:ye,shouldHideArrow:Te,children:u.jsx(Ne.div,{"data-side":R,"data-align":z,...m,ref:S,style:{...m.style,animation:F?void 0:"none"}})})})});ru.displayName=Oi;var ou="PopperArrow",pv={top:"bottom",right:"left",bottom:"top",left:"right"},su=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=fv(ou,r),i=pv[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(cv,{...o,ref:n,style:{...o.style,display:"block"}})})});su.displayName=ou;function hv(e){return e!==null}var mv=e=>({name:"transformOrigin",options:e,fn(t){var y,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=iu(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,h=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let g="",m="";return c==="bottom"?(g=i?f:`${p}px`,m=`${-l}px`):c==="top"?(g=i?f:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,m=i?f:`${h}px`):c==="left"&&(g=`${r.floating.width+l}px`,m=i?f:`${h}px`),{data:{x:g,y:m}}}});function iu(e){const[t,n="center"]=e.split("-");return[t,n]}var au=eu,lu=nu,cu=ru,uu=su,gv="Portal",Go=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ys.createPortal(u.jsx(Ne.div,{...r,ref:t}),i):null});Go.displayName=gv;function xv(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Xt=e=>{const{present:t,children:n}=e,r=yv(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=$e(r.ref,vv(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Xt.displayName="Presence";function yv(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=xv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Yo(r.current);s.current=a==="mounted"?c:"none"},[a]),kt(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=Yo(c);e?l("MOUNT"):h==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const m=Yo(r.current).includes(CSS.escape(h.animationName));if(h.target===t&&m&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=h=>{h.target===t&&(s.current=Yo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Yo(e){return(e==null?void 0:e.animationName)||"none"}function vv(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Di="rovingFocusGroup.onEntryFocus",wv={bubbles:!1,cancelable:!0},zr="RovingFocusGroup",[Li,du,bv]=xi(zr),[Sv,fu]=Tn(zr,[bv]),[Cv,Tv]=Sv(zr),pu=v.forwardRef((e,t)=>u.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(kv,{...e,ref:t})})}));pu.displayName=zr;var kv=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,p=v.useRef(null),h=$e(t,p),g=Ro(s),[m,y]=pr({prop:i,defaultProp:a??null,onChange:l,caller:zr}),[x,w]=v.useState(!1),S=Et(c),k=du(n),C=v.useRef(!1),[T,E]=v.useState(0);return v.useEffect(()=>{const N=p.current;if(N)return N.addEventListener(Di,S),()=>N.removeEventListener(Di,S)},[S]),u.jsx(Cv,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:m,onItemFocus:v.useCallback(N=>y(N),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:v.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Ne.div,{tabIndex:x||T===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:pe(e.onMouseDown,()=>{C.current=!0}),onFocus:pe(e.onFocus,N=>{const _=!C.current;if(N.target===N.currentTarget&&_&&!x){const D=new CustomEvent(Di,wv);if(N.currentTarget.dispatchEvent(D),!D.defaultPrevented){const B=k().filter(A=>A.focusable),G=B.find(A=>A.active),V=B.find(A=>A.id===m),M=[G,V,...B].filter(Boolean).map(A=>A.ref.current);gu(M,d)}}C.current=!1}),onBlur:pe(e.onBlur,()=>w(!1))})})}),hu="RovingFocusGroupItem",mu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=kn(),c=s||l,d=Tv(hu,n),f=d.currentTabStopId===c,p=du(n),{onFocusableItemAdd:h,onFocusableItemRemove:g,currentTabStopId:m}=d;return v.useEffect(()=>{if(r)return h(),()=>g()},[r,h,g]),u.jsx(Li.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Ne.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:pe(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:pe(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:pe(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=Av(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=p().filter(k=>k.focusable).map(k=>k.ref.current);if(x==="last")S.reverse();else if(x==="prev"||x==="next"){x==="prev"&&S.reverse();const k=S.indexOf(y.currentTarget);S=d.loop?Nv(S,k+1):S.slice(k+1)}setTimeout(()=>gu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});mu.displayName=hu;var Ev={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Iv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Av(e,t,n){const r=Iv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Ev[r]}function gu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Nv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var _v=pu,jv=mu,Mv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},yr=new WeakMap,Xo=new WeakMap,Jo={},$i=0,xu=function(e){return e&&(e.host||xu(e.parentNode))},Pv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Rv=function(e,t,n,r){var o=Pv(t,Array.isArray(e)?e:[e]);Jo[n]||(Jo[n]=new WeakMap);var s=Jo[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(p){if(a.has(p))d(p);else try{var h=p.getAttribute(r),g=h!==null&&h!=="false",m=(yr.get(p)||0)+1,y=(s.get(p)||0)+1;yr.set(p,m),s.set(p,y),i.push(p),m===1&&g&&Xo.set(p,!0),y===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",p,x)}})};return d(t),a.clear(),$i++,function(){i.forEach(function(f){var p=yr.get(f)-1,h=s.get(f)-1;yr.set(f,p),s.set(f,h),p||(Xo.has(f)||f.removeAttribute(r),Xo.delete(f)),h||f.removeAttribute(n)}),$i--,$i||(yr=new WeakMap,yr=new WeakMap,Xo=new WeakMap,Jo={})}},Fi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Mv(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Rv(r,o,n,"aria-hidden")):function(){return null}},xn=function(){return xn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},xn.apply(this,arguments)};function yu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function Ov(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Zo="right-scroll-bar-position",Qo="width-before-scroll-bar",Dv="with-scroll-bars-hidden",Lv="--removed-body-scroll-bar-size";function Bi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function $v(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Fv=typeof window<"u"?v.useLayoutEffect:v.useEffect,vu=new WeakMap;function Bv(e,t){var n=$v(null,function(r){return e.forEach(function(o){return Bi(o,r)})});return Fv(function(){var r=vu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Bi(a,null)}),s.forEach(function(a){o.has(a)||Bi(a,i)})}vu.set(n,e)},[e]),n}function zv(e){return e}function Uv(e,t){t===void 0&&(t=zv);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Hv(e){e===void 0&&(e={});var t=Uv(null);return t.options=xn({async:!0,ssr:!1},e),t}var wu=function(e){var t=e.sideCar,n=yu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,xn({},n))};wu.isSideCarExport=!0;function Wv(e,t){return e.useMedium(t),wu}var bu=Hv(),zi=function(){},es=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:zi,onWheelCapture:zi,onTouchMoveCapture:zi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,g=e.noIsolation,m=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,S=e.gapMode,k=yu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,T=Bv([n,t]),E=xn(xn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(C,{sideCar:bu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:g,inert:m,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),xn(xn({},E),{ref:T})):v.createElement(w,xn({},E,{className:l,ref:T}),a))});es.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},es.classNames={fullWidth:Qo,zeroRight:Zo};var Vv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Kv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Vv();return t&&e.setAttribute("nonce",t),e}function qv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Gv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Yv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Kv())&&(qv(t,n),Gv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Xv=function(){var e=Yv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Su=function(){var e=Xv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Jv={left:0,top:0,right:0,gap:0},Ui=function(e){return parseInt(e||"",10)||0},Zv=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Ui(n),Ui(r),Ui(o)]},Qv=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Jv;var t=Zv(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},ew=Su(),vr="data-scroll-locked",tw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
39
39
|
.`.concat(Dv,` {
|
|
40
40
|
overflow: hidden `).concat(r,`;
|
|
41
41
|
padding-right: `).concat(a,"px ").concat(r,`;
|
package/dist/types/events.d.ts
CHANGED
package/package.json
CHANGED
|
File without changes
|