teodor-new-chat-ui 4.3.334 → 4.3.335

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -2680,7 +2680,8 @@ function xx(e) {
2680
2680
  step: l,
2681
2681
  source: c ?? null,
2682
2682
  createdAt: d,
2683
- next: h ?? void 0
2683
+ next: h ?? void 0,
2684
+ parentConfig: o.parentConfig ?? null
2684
2685
  });
2685
2686
  }
2686
2687
  return t;
package/dist/index.umd.js CHANGED
@@ -32,7 +32,7 @@ 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=Or(i);r[a]||(qm(o,i),r[a]=!0)}return D.isArray(t)?t.forEach(s):s(t),this}};Ft.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),D.reduceDescriptors(Ft.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),D.freezeMethods(Ft);function oi(e,t){const n=this||Pr,r=t||n,o=Ft.from(r.headers);let s=r.data;return D.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){_e.call(this,e??"canceled",_e.ERR_CANCELED,t,n),this.name="CanceledError"}D.inherits(ur,_e,{__CANCEL__:!0});function gl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new _e("Request failed with status code "+n.status,[_e.ERR_BAD_REQUEST,_e.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Gm(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Ym(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 Xm(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 wo=(e,t,n=3)=>{let r=0;const o=Ym(50,250);return Xm(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)=>D.asap(()=>e(...t)),Jm=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,Zm=At.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];D.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),D.isString(r)&&i.push("path="+r),D.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 Qm(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function eg(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function vl(e,t,n){let r=!Qm(t);return e&&(r||n==!1)?eg(e,t):t}const bl=e=>e instanceof Ft?{...e}:e;function Vn(e,t){t=t||{};const n={};function r(c,d,f,p){return D.isPlainObject(c)&&D.isPlainObject(d)?D.merge.call({caseless:p},c,d):D.isPlainObject(d)?D.merge({},d):D.isArray(d)?d.slice():d}function o(c,d,f,p){if(D.isUndefined(d)){if(!D.isUndefined(c))return r(void 0,c,f,p)}else return r(c,d,f,p)}function s(c,d){if(!D.isUndefined(d))return r(void 0,d)}function i(c,d){if(D.isUndefined(d)){if(!D.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(bl(c),bl(d),f,!0)};return D.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,p=f(e[d],t[d],d);D.isUndefined(p)&&f!==a||(n[d]=p)}),n}const wl=e=>{const t=Vn({},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)):""))),D.isFormData(n)){if(At.hasStandardBrowserEnv||At.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(D.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&&D.isFunction(r)&&(r=r(t)),r||r!==!1&&Jm(t.url))){const l=o&&s&&Zm.read(s);l&&i.set(o,l)}return t},tg=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=wl(e);let s=o.data;const i=Ft.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,p,h,x;function m(){h&&h(),x&&x(),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 g(){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(I){n(I),m()},function(I){r(I),m()},C),y=null}"onloadend"in y?y.onloadend=g:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(g)},y.onabort=function(){y&&(r(new _e("Request aborted",_e.ECONNABORTED,e,y)),y=null)},y.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new _e(C,_e.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 _e(k,C.clarifyTimeoutError?_e.ETIMEDOUT:_e.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&D.forEach(i.toJSON(),function(k,C){y.setRequestHeader(C,k)}),D.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([p,x]=wo(c,!0),y.addEventListener("progress",p)),l&&y.upload&&([f,h]=wo(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 b=Gm(o.url);if(b&&At.protocols.indexOf(b)===-1){r(new _e("Unsupported protocol "+b+":",_e.ERR_BAD_REQUEST,e));return}y.send(s||null)})},ng=(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 _e?d:new ur(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new _e(`timeout ${t} of ms exceeded`,_e.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=()=>D.asap(a),l}},rg=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},og=async function*(e,t){for await(const n of sg(e))yield*rg(n,t)},sg=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=og(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:So}=D,ig=(({Request:e,Response:t})=>({Request:e,Response:t}))(D.global),{ReadableStream:Tl,TextEncoder:kl}=D.global,Il=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ag=e=>{e=D.merge.call({skipUndefined:!0},ig,e);const{fetch:t,Request:n,Response:r}=e,o=t?So(t):typeof fetch=="function",s=So(n),i=So(r);if(!o)return!1;const a=o&&So(Tl),l=o&&(typeof kl=="function"?(x=>m=>x.encode(m))(new kl):async x=>new Uint8Array(await new n(x).arrayBuffer())),c=s&&a&&Il(()=>{let x=!1;const m=new n(At.origin,{body:new Tl,method:"POST",get duplex(){return x=!0,"half"}}).headers.has("Content-Type");return x&&!m}),d=i&&a&&Il(()=>D.isReadableStream(new r("").body)),f={stream:d&&(x=>x.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(x=>{!f[x]&&(f[x]=(m,y)=>{let g=m&&m[x];if(g)return g.call(m);throw new _e(`Response type '${x}' is not supported`,_e.ERR_NOT_SUPPORT,y)})});const p=async x=>{if(x==null)return 0;if(D.isBlob(x))return x.size;if(D.isSpecCompliantForm(x))return(await new n(At.origin,{method:"POST",body:x}).arrayBuffer()).byteLength;if(D.isArrayBufferView(x)||D.isArrayBuffer(x))return x.byteLength;if(D.isURLSearchParams(x)&&(x=x+""),D.isString(x))return(await l(x)).byteLength},h=async(x,m)=>{const y=D.toFiniteNumber(x.getContentLength());return y??p(m)};return async x=>{let{url:m,method:y,data:g,signal:b,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:I,headers:A,withCredentials:R="same-origin",fetchOptions:$}=wl(x),P=t||fetch;I=I?(I+"").toLowerCase():"text";let O=ng([b,S&&S.toAbortSignal()],k),F=null;const N=O&&O.unsubscribe&&(()=>{O.unsubscribe()});let B;try{if(T&&c&&y!=="get"&&y!=="head"&&(B=await h(A,g))!==0){let Y=new n(m,{method:"POST",body:g,duplex:"half"}),oe;if(D.isFormData(g)&&(oe=Y.headers.get("content-type"))&&A.setContentType(oe),Y.body){const[ye,Me]=xl(B,wo(yl(T)));g=Sl(Y.body,Cl,ye,Me)}}D.isString(R)||(R=R?"include":"omit");const M=s&&"credentials"in n.prototype,Q={...$,signal:O,method:y.toUpperCase(),headers:A.normalize().toJSON(),body:g,duplex:"half",credentials:M?R:void 0};F=s&&new n(m,Q);let z=await(s?P(F,$):P(m,Q));const _=d&&(I==="stream"||I==="response");if(d&&(C||_&&N)){const Y={};["status","statusText","headers"].forEach(G=>{Y[G]=z[G]});const oe=D.toFiniteNumber(z.headers.get("content-length")),[ye,Me]=C&&xl(oe,wo(yl(C),!0))||[];z=new r(Sl(z.body,Cl,ye,()=>{Me&&Me(),N&&N()}),Y)}I=I||"text";let V=await f[D.findKey(f,I)||"text"](z,x);return!_&&N&&N(),await new Promise((Y,oe)=>{gl(Y,oe,{data:V,headers:Ft.from(z.headers),status:z.status,statusText:z.statusText,config:x,request:F})})}catch(M){throw N&&N(),M&&M.name==="TypeError"&&/Load failed|fetch/i.test(M.message)?Object.assign(new _e("Network Error",_e.ERR_NETWORK,x,F),{cause:M.cause||M}):_e.from(M,M&&M.code,x,F)}}},lg=new Map,El=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=lg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:ag(t)),d=c;return c};El();const si={http:_m,xhr:tg,fetch:{get:El}};D.forEach(si,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Al=e=>`- ${e}`,cg=e=>D.isFunction(e)||e===null||e===!1,Nl={getAdapter:(e,t)=>{e=D.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,!cg(r)&&(o=si[(a=String(r)).toLowerCase()],o===void 0))throw new _e(`Unknown adapter '${a}'`);if(o&&(D.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 _e("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:si};function ii(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ur(null,e)}function _l(e){return ii(e),e.headers=Ft.from(e.headers),e.data=oi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Nl.getAdapter(e.adapter||Pr.adapter,e)(e).then(function(r){return ii(e),r.data=oi.call(e,e.transformResponse,r),r.headers=Ft.from(r.headers),r},function(r){return ml(r)||(ii(e),r&&r.response&&(r.response.data=oi.call(e,e.transformResponse,r.response),r.response.headers=Ft.from(r.response.headers))),Promise.reject(r)})}const jl="1.12.2",Co={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Co[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Rl={};Co.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 _e(o(i," has been removed"+(n?" in "+n:"")),_e.ERR_DEPRECATED);return n&&!Rl[i]&&(Rl[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}},Co.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function ug(e,t,n){if(typeof e!="object")throw new _e("options must be an object",_e.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 _e("option "+s+" must be "+l,_e.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new _e("Unknown option "+s,_e.ERR_BAD_OPTION)}}const To={assertOptions:ug,validators:Co},un=To.validators;let Kn=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=Vn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&To.assertOptions(r,{silentJSONParsing:un.transitional(un.boolean),forcedJSONParsing:un.transitional(un.boolean),clarifyTimeoutError:un.transitional(un.boolean)},!1),o!=null&&(D.isFunction(o)?n.paramsSerializer={serialize:o}:To.assertOptions(o,{encode:un.function,serialize:un.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),To.assertOptions(n,{baseUrl:un.spelling("baseURL"),withXsrfToken:un.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&D.merge(s.common,s[n.method]);s&&D.forEach(["delete","get","head","post","put","patch","common"],x=>{delete s[x]}),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 x=[_l.bind(this),void 0];for(x.unshift(...a),x.push(...c),p=x.length,d=Promise.resolve(n);f<p;)d=d.then(x[f++],x[f++]);return d}p=a.length;let h=n;for(;f<p;){const x=a[f++],m=a[f++];try{h=x(h)}catch(y){m.call(this,y);break}}try{d=_l.call(this,h)}catch(x){return Promise.reject(x)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Vn(this.defaults,t);const n=vl(t.baseURL,t.url,t.allowAbsoluteUrls);return ul(n,t.params,t.paramsSerializer)}};D.forEach(["delete","get","head","options"],function(t){Kn.prototype[t]=function(n,r){return this.request(Vn(r||{},{method:t,url:n,data:(r||{}).data}))}}),D.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Vn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Kn.prototype[t]=n(),Kn.prototype[t+"Form"]=n(!0)});let dg=class zh{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 zh(function(o){t=o}),cancel:t}}};function fg(e){return function(n){return e.apply(null,n)}}function pg(e){return D.isObject(e)&&e.isAxiosError===!0}const ai={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(ai).forEach(([e,t])=>{ai[t]=e});function Ml(e){const t=new Kn(e),n=Ya(Kn.prototype.request,t);return D.extend(n,Kn.prototype,t,{allOwnKeys:!0}),D.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Ml(Vn(e,o))},n}const yt=Ml(Pr);yt.Axios=Kn,yt.CanceledError=ur,yt.CancelToken=dg,yt.isCancel=ml,yt.VERSION=jl,yt.toFormData=vo,yt.AxiosError=_e,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=fg,yt.isAxiosError=pg,yt.mergeConfig=Vn,yt.AxiosHeaders=Ft,yt.formToJSON=e=>pl(D.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Nl.getAdapter,yt.HttpStatusCode=ai,yt.default=yt;const{Axios:yT,AxiosError:vT,CanceledError:bT,isCancel:wT,CancelToken:ST,VERSION:CT,all:TT,Cancel:kT,isAxiosError:IT,spread:ET,toFormData:AT,AxiosHeaders:NT,HttpStatusCode:_T,formToJSON:jT,getAdapter:RT,mergeConfig:MT}=yt,Pl=typeof window<"u"?window.__API_BASE_URL__:void 0,Ol=Pl?wn(Pl):void 0;function wn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let ko=null;const li=new Set;function Dl(){return ko}function Io(e){ko=e,li.forEach(t=>t(e))}function Ll(e){return li.add(e),()=>li.delete(e)}const hg=3e4,mg=9e4,Kt=yt.create({...Ol?{baseURL:Ol}:{},timeout:hg,withCredentials:!0});Kt.interceptors.request.use(e=>(ko&&(e.headers.Authorization=`Bearer ${ko}`),e)),Kt.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 qt(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ci(e,t,n){return Kt.defaults.baseURL?(await Kt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function $l(e,t,n){return Kt.defaults.baseURL?(await Kt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fl(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Gt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){const t=Kt.defaults.baseURL;return t?wn(String(t)):""}updateConfig(t){t.baseUrl&&(Kt.defaults.baseURL=wn(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 qt("/threads"),n=Gt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ci("/threads",t?{title:t}:void 0);return Gt(r)}async updateThread(t,n){const r=await $l(`/threads/${t}`,{title:n});return Gt(r)}async deleteThread(t){const n=await Fl(`/threads/${t}`);return Gt(n)}async threadInfo(t){const n=await qt(`/threads/${t}/info`);return Gt(n)}async listAgents(){const t=await qt("/agents"),n=Gt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await qt(`/agents/${t}`);return Gt(n)}async getAgentSchema(t){const n=await qt(`/agents/${t}/schema`);return Gt(n)}async getState(t){const n=await qt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Gt(n)}async getStateHistory(t){const n=await qt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:mg});return Gt(n)}async cancelRun(t){const n=await ci("/runs/cancel",{threadId:t});return Gt(n)}async listCheckpointSummaries(t){const n=await qt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Gt(n);return(r==null?void 0:r.items)??[]}}const An=new Bl,zl=w.createContext(null);function gg({children:e,apiConfig:t}){const n=An;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 ui(){const e=w.useContext(zl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function xg(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 yg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await xg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const vg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function di(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 bg(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(!di(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Sg(t),i=Ul(r,0),a=Cg(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(!di(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(R=>!!R&&typeof R=="object").map(R=>({...R})):a===null?null:void 0,c=r.map((R,$)=>Rg(R,$)).filter(R=>!!R),d=Pt(e.config),f=Pt(d==null?void 0:d.configurable),p=dt(f,["checkpoint_id","checkpointId"]),h=dt(f,["checkpoint_ns","checkpointNs"]),x=Pt(e==null?void 0:e.parentConfig),m=Pt(x==null?void 0:x.configurable),y=dt(m,["checkpoint_id","checkpointId"])??null,g=dt(m,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,S=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(R=>R.role==="user")??null,C=Pt(e==null?void 0:e.metadata),T=dt(C,["branch_label","branchLabel"]),I=dt(m,["checkpoint_id","checkpointId"]),A=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:g,interrupt:wg(a,c,t),createdAt:S,parentId:I??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:x??null,next:A??null,tasks:l??null,values:i??null}}function wg(e,t,n){const r=_g(e,n);return r||Ng(t,n)}function Sg(e){const t=new Map;e.forEach((o,s)=>{if(!di(o))return;const i=Ul(o,s);if(!(i!=null&&i.checkpointId))return;const a=bg(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Ig(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 Cg(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=kg(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=Tg(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0})}return t}function Tg(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 kg(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 Ig(e,t){return{...e,metadata:Eo(e.metadata,t.metadata)??null,config:Eo(e.config,t.config)??null,parentConfig:Eo(e.parentConfig,t.parentConfig)??null,next:Eg(e.next,t.next)??null,tasks:Ag(e.tasks,t.tasks)??null,values:Eo(e.values,t.values)??null}}function Eo(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 Eg(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 Ag(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 Ng(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 _g(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=jg(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=Dr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Dr(r.state,`${o}-state`);if(s)return s}}return null}function jg(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,x=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:x,interrupts:m,state:y!==void 0?y:f}}const n=Pt(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 Dr(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=Dr(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=Dr(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=Dr(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 Rg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Pt(e)??{},o=Pt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=vg[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=Pt(o.additional_kwargs)??Pt(o.additionalKwargs),d=Pt(o.response_metadata)??Pt(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"]),x=Mg(o.content),m={id:l,role:i,content:x};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=Dg(Pt(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(m.artifact=y);const g=Bg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),b=d?{...d}:void 0;g&&Object.keys(g).length&&(m.additionalKwargs=g),b&&Object.keys(b).length&&(m.responseMetadata=b);const S=Pg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Og(o,m.content);k&&(m.content=k)}return m}function Mg(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(Pt(e.function),["name"]);if(!n||!r)return null;const o=Fg(e.args??e.arguments??((s=Pt(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Pg(e){return Array.isArray(e)?e.map((t,n)=>Kl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Og(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 Dg(e){return e?{plots:Lg(e.plots)}:void 0}function Lg(e){return Array.isArray(e)?e.map(t=>$g(t)).filter(t=>!!t):[]}function $g(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 Fg(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 Pt(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 Bg(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 fr=120;function zg(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>fr?`${n.slice(0,fr-3)}…`:n:""}function Ug(e){var r,o;const t=[(r=e.additionalKwargs)==null?void 0:r.summary,(o=e.responseMetadata)==null?void 0:o.summary];for(const s of t)if(typeof s=="string"&&s.trim()){const i=s.trim();return i.length>fr?`${i.slice(0,fr-3)}…`:i}const n=(e.name||e.id||"").toString().trim();return n?n.length>fr?`${n.slice(0,fr-3)}…`:n:""}function ql(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const o=zg(n.content)||Ug(n);o&&t.set(n.id,o)}return t}function Gl(e={}){const t=w.useMemo(()=>wn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,p]=w.useState(""),[h,x]=w.useState(null),[m,y]=w.useState(0),[g,b]=w.useState(!1),S=w.useRef(null),k=w.useRef(!0),C=w.useRef(0),T=w.useRef(null),I=w.useRef(null),A=w.useRef(null),R=w.useRef(null),$=w.useCallback(N=>{o(N)},[]),P=w.useCallback(()=>{p(""),x(null),d(null),I.current=null,A.current=null,R.current=null},[]),O=w.useCallback(()=>{var N;console.debug("[use-chat] stop() invoked - aborting stream"),(N=S.current)==null||N.abort(),S.current=null,T.current=null,l(!1),b(!1),C.current=0,y(0)},[]),F=w.useCallback((N,B,M)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),x(null),I.current=null,A.current=null,R.current=null;const Q=new AbortController;S.current=Q;let z=null,_=null,V=!1;return T.current={threadId:N.threadId??null,headers:{}},(async()=>{var oe,ye,Me,G,U,X,L,K,Z,ce,re,je,Ue,De,Ge,Ve,tt,Ye;const Y=ie=>{var xe;try{const He=JSON.parse(JSON.stringify(ie));return(xe=He==null?void 0:He.payload)!=null&&xe.files_info&&Array.isArray(He.payload.files_info)&&(He.payload.files_info=He.payload.files_info.map(We=>({...We,data:We!=null&&We.data?`<base64 ${String(We.data).length} chars>`:We==null?void 0:We.data}))),He}catch{return ie}};try{let ie={};try{if(r)ie={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ze=window.__AUTH_TOKEN__,pt=((oe=window.localStorage)==null?void 0:oe.getItem("authToken"))||null;let lt=null;try{const j=(ye=window.localStorage)==null?void 0:ye.getItem("chat-settings");j&&(lt=((Me=JSON.parse(j))==null?void 0:Me.apiKey)||null)}catch{}const q=Ze||pt||lt||null;q&&(ie={Authorization:`Bearer ${q}`})}}catch{}console.debug("[use-chat] POST",t+n,Y(N));let xe={};if(typeof window<"u")try{const Je=(G=window.localStorage)==null?void 0:G.getItem("authSessionId");Je&&(xe={"X-Session-Id":Je})}catch{}const He={...ie,...xe,...s.current},We={"Content-Type":"application/json",Accept:"text/event-stream",...He},rt=await fetch(t+n,{method:"POST",headers:We,body:JSON.stringify(N),signal:Q.signal,credentials:i});if(T.current&&(T.current.headers=He),!rt.ok||!rt.body){const Je=await rt.text().catch(()=>"");console.debug("[use-chat] non-OK response",rt.status,Je==null?void 0:Je.slice(0,500));const Ze=`stream ${rt.status}${Je?": "+Je:""}`;throw(U=M==null?void 0:M.onConnectionError)==null||U.call(M,Ze),V=!0,z="error",_=Ze,new Error(Ze)}b(!0);const at=rt.body.getReader(),Rt=new TextDecoder;let gt="",ht=[];C.current=0,y(0);let bt=0,St=null;const Lt=()=>{if(ht.length){const Je=ht.join("");ht=[],k.current&&p(Ze=>Ze+Je)}St=null},Mt=()=>{typeof window<"u"&&St==null&&(St=requestAnimationFrame(Lt))};let nt=Date.now();const It=setInterval(()=>{var Je;if(Date.now()-nt>18e5){const Ze="Stream idle timeout";d(Ze),z="error",_=Ze,Q.abort(),(Je=M==null?void 0:M.onError)==null||Je.call(M,Ze)}},5e3),bn=1024*1024;try{const Je=rt.headers.get("X-Thread-Id")||rt.headers.get("x-thread-id"),Ze=rt.headers.get("X-Thread-Created")||rt.headers.get("x-thread-created"),pt=Je??null,lt=String(Ze??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:pt}),(X=M==null?void 0:M.onOpen)==null||X.call(M,{threadId:pt,created:lt});;){const{value:q,done:j}=await at.read();if(j)break;gt+=Rt.decode(q,{stream:!0}),gt.length>bn&&(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=Vn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&To.assertOptions(r,{silentJSONParsing:un.transitional(un.boolean),forcedJSONParsing:un.transitional(un.boolean),clarifyTimeoutError:un.transitional(un.boolean)},!1),o!=null&&(D.isFunction(o)?n.paramsSerializer={serialize:o}:To.assertOptions(o,{encode:un.function,serialize:un.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),To.assertOptions(n,{baseUrl:un.spelling("baseURL"),withXsrfToken:un.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&D.merge(s.common,s[n.method]);s&&D.forEach(["delete","get","head","post","put","patch","common"],x=>{delete s[x]}),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 x=[_l.bind(this),void 0];for(x.unshift(...a),x.push(...c),p=x.length,d=Promise.resolve(n);f<p;)d=d.then(x[f++],x[f++]);return d}p=a.length;let h=n;for(;f<p;){const x=a[f++],m=a[f++];try{h=x(h)}catch(y){m.call(this,y);break}}try{d=_l.call(this,h)}catch(x){return Promise.reject(x)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Vn(this.defaults,t);const n=vl(t.baseURL,t.url,t.allowAbsoluteUrls);return ul(n,t.params,t.paramsSerializer)}};D.forEach(["delete","get","head","options"],function(t){Kn.prototype[t]=function(n,r){return this.request(Vn(r||{},{method:t,url:n,data:(r||{}).data}))}}),D.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Vn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Kn.prototype[t]=n(),Kn.prototype[t+"Form"]=n(!0)});let dg=class zh{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 zh(function(o){t=o}),cancel:t}}};function fg(e){return function(n){return e.apply(null,n)}}function pg(e){return D.isObject(e)&&e.isAxiosError===!0}const ai={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(ai).forEach(([e,t])=>{ai[t]=e});function Ml(e){const t=new Kn(e),n=Ya(Kn.prototype.request,t);return D.extend(n,Kn.prototype,t,{allOwnKeys:!0}),D.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Ml(Vn(e,o))},n}const yt=Ml(Pr);yt.Axios=Kn,yt.CanceledError=ur,yt.CancelToken=dg,yt.isCancel=ml,yt.VERSION=jl,yt.toFormData=vo,yt.AxiosError=_e,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=fg,yt.isAxiosError=pg,yt.mergeConfig=Vn,yt.AxiosHeaders=Ft,yt.formToJSON=e=>pl(D.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Nl.getAdapter,yt.HttpStatusCode=ai,yt.default=yt;const{Axios:yT,AxiosError:vT,CanceledError:bT,isCancel:wT,CancelToken:ST,VERSION:CT,all:TT,Cancel:kT,isAxiosError:IT,spread:ET,toFormData:AT,AxiosHeaders:NT,HttpStatusCode:_T,formToJSON:jT,getAdapter:RT,mergeConfig:MT}=yt,Pl=typeof window<"u"?window.__API_BASE_URL__:void 0,Ol=Pl?wn(Pl):void 0;function wn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let ko=null;const li=new Set;function Dl(){return ko}function Io(e){ko=e,li.forEach(t=>t(e))}function Ll(e){return li.add(e),()=>li.delete(e)}const hg=3e4,mg=9e4,Kt=yt.create({...Ol?{baseURL:Ol}:{},timeout:hg,withCredentials:!0});Kt.interceptors.request.use(e=>(ko&&(e.headers.Authorization=`Bearer ${ko}`),e)),Kt.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 qt(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ci(e,t,n){return Kt.defaults.baseURL?(await Kt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function $l(e,t,n){return Kt.defaults.baseURL?(await Kt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fl(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Gt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){const t=Kt.defaults.baseURL;return t?wn(String(t)):""}updateConfig(t){t.baseUrl&&(Kt.defaults.baseURL=wn(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 qt("/threads"),n=Gt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ci("/threads",t?{title:t}:void 0);return Gt(r)}async updateThread(t,n){const r=await $l(`/threads/${t}`,{title:n});return Gt(r)}async deleteThread(t){const n=await Fl(`/threads/${t}`);return Gt(n)}async threadInfo(t){const n=await qt(`/threads/${t}/info`);return Gt(n)}async listAgents(){const t=await qt("/agents"),n=Gt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await qt(`/agents/${t}`);return Gt(n)}async getAgentSchema(t){const n=await qt(`/agents/${t}/schema`);return Gt(n)}async getState(t){const n=await qt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Gt(n)}async getStateHistory(t){const n=await qt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:mg});return Gt(n)}async cancelRun(t){const n=await ci("/runs/cancel",{threadId:t});return Gt(n)}async listCheckpointSummaries(t){const n=await qt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Gt(n);return(r==null?void 0:r.items)??[]}}const An=new Bl,zl=w.createContext(null);function gg({children:e,apiConfig:t}){const n=An;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 ui(){const e=w.useContext(zl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function xg(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 yg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await xg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const vg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function di(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 bg(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(!di(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Sg(t),i=Ul(r,0),a=Cg(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(!di(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(R=>!!R&&typeof R=="object").map(R=>({...R})):a===null?null:void 0,c=r.map((R,$)=>Rg(R,$)).filter(R=>!!R),d=Pt(e.config),f=Pt(d==null?void 0:d.configurable),p=dt(f,["checkpoint_id","checkpointId"]),h=dt(f,["checkpoint_ns","checkpointNs"]),x=Pt(e==null?void 0:e.parentConfig),m=Pt(x==null?void 0:x.configurable),y=dt(m,["checkpoint_id","checkpointId"])??null,g=dt(m,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,S=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(R=>R.role==="user")??null,C=Pt(e==null?void 0:e.metadata),T=dt(C,["branch_label","branchLabel"]),I=dt(m,["checkpoint_id","checkpointId"]),A=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:g,interrupt:wg(a,c,t),createdAt:S,parentId:I??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:x??null,next:A??null,tasks:l??null,values:i??null}}function wg(e,t,n){const r=_g(e,n);return r||Ng(t,n)}function Sg(e){const t=new Map;e.forEach((o,s)=>{if(!di(o))return;const i=Ul(o,s);if(!(i!=null&&i.checkpointId))return;const a=bg(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Ig(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 Cg(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=kg(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=Tg(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 Tg(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 kg(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 Ig(e,t){return{...e,metadata:Eo(e.metadata,t.metadata)??null,config:Eo(e.config,t.config)??null,parentConfig:Eo(e.parentConfig,t.parentConfig)??null,next:Eg(e.next,t.next)??null,tasks:Ag(e.tasks,t.tasks)??null,values:Eo(e.values,t.values)??null}}function Eo(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 Eg(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 Ag(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 Ng(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 _g(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=jg(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=Dr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Dr(r.state,`${o}-state`);if(s)return s}}return null}function jg(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,x=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:x,interrupts:m,state:y!==void 0?y:f}}const n=Pt(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 Dr(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=Dr(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=Dr(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=Dr(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 Rg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Pt(e)??{},o=Pt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=vg[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=Pt(o.additional_kwargs)??Pt(o.additionalKwargs),d=Pt(o.response_metadata)??Pt(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"]),x=Mg(o.content),m={id:l,role:i,content:x};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=Dg(Pt(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(m.artifact=y);const g=Bg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),b=d?{...d}:void 0;g&&Object.keys(g).length&&(m.additionalKwargs=g),b&&Object.keys(b).length&&(m.responseMetadata=b);const S=Pg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Og(o,m.content);k&&(m.content=k)}return m}function Mg(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(Pt(e.function),["name"]);if(!n||!r)return null;const o=Fg(e.args??e.arguments??((s=Pt(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Pg(e){return Array.isArray(e)?e.map((t,n)=>Kl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Og(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 Dg(e){return e?{plots:Lg(e.plots)}:void 0}function Lg(e){return Array.isArray(e)?e.map(t=>$g(t)).filter(t=>!!t):[]}function $g(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 Fg(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 Pt(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 Bg(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 fr=120;function zg(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>fr?`${n.slice(0,fr-3)}…`:n:""}function Ug(e){var r,o;const t=[(r=e.additionalKwargs)==null?void 0:r.summary,(o=e.responseMetadata)==null?void 0:o.summary];for(const s of t)if(typeof s=="string"&&s.trim()){const i=s.trim();return i.length>fr?`${i.slice(0,fr-3)}…`:i}const n=(e.name||e.id||"").toString().trim();return n?n.length>fr?`${n.slice(0,fr-3)}…`:n:""}function ql(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const o=zg(n.content)||Ug(n);o&&t.set(n.id,o)}return t}function Gl(e={}){const t=w.useMemo(()=>wn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,p]=w.useState(""),[h,x]=w.useState(null),[m,y]=w.useState(0),[g,b]=w.useState(!1),S=w.useRef(null),k=w.useRef(!0),C=w.useRef(0),T=w.useRef(null),I=w.useRef(null),A=w.useRef(null),R=w.useRef(null),$=w.useCallback(N=>{o(N)},[]),P=w.useCallback(()=>{p(""),x(null),d(null),I.current=null,A.current=null,R.current=null},[]),O=w.useCallback(()=>{var N;console.debug("[use-chat] stop() invoked - aborting stream"),(N=S.current)==null||N.abort(),S.current=null,T.current=null,l(!1),b(!1),C.current=0,y(0)},[]),F=w.useCallback((N,B,M)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),x(null),I.current=null,A.current=null,R.current=null;const Q=new AbortController;S.current=Q;let z=null,_=null,V=!1;return T.current={threadId:N.threadId??null,headers:{}},(async()=>{var oe,ye,Me,G,U,X,L,K,Z,ce,re,je,Ue,De,Ge,Ve,tt,Ye;const Y=ie=>{var xe;try{const He=JSON.parse(JSON.stringify(ie));return(xe=He==null?void 0:He.payload)!=null&&xe.files_info&&Array.isArray(He.payload.files_info)&&(He.payload.files_info=He.payload.files_info.map(We=>({...We,data:We!=null&&We.data?`<base64 ${String(We.data).length} chars>`:We==null?void 0:We.data}))),He}catch{return ie}};try{let ie={};try{if(r)ie={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ze=window.__AUTH_TOKEN__,pt=((oe=window.localStorage)==null?void 0:oe.getItem("authToken"))||null;let lt=null;try{const j=(ye=window.localStorage)==null?void 0:ye.getItem("chat-settings");j&&(lt=((Me=JSON.parse(j))==null?void 0:Me.apiKey)||null)}catch{}const q=Ze||pt||lt||null;q&&(ie={Authorization:`Bearer ${q}`})}}catch{}console.debug("[use-chat] POST",t+n,Y(N));let xe={};if(typeof window<"u")try{const Je=(G=window.localStorage)==null?void 0:G.getItem("authSessionId");Je&&(xe={"X-Session-Id":Je})}catch{}const He={...ie,...xe,...s.current},We={"Content-Type":"application/json",Accept:"text/event-stream",...He},rt=await fetch(t+n,{method:"POST",headers:We,body:JSON.stringify(N),signal:Q.signal,credentials:i});if(T.current&&(T.current.headers=He),!rt.ok||!rt.body){const Je=await rt.text().catch(()=>"");console.debug("[use-chat] non-OK response",rt.status,Je==null?void 0:Je.slice(0,500));const Ze=`stream ${rt.status}${Je?": "+Je:""}`;throw(U=M==null?void 0:M.onConnectionError)==null||U.call(M,Ze),V=!0,z="error",_=Ze,new Error(Ze)}b(!0);const at=rt.body.getReader(),Rt=new TextDecoder;let gt="",ht=[];C.current=0,y(0);let bt=0,St=null;const Lt=()=>{if(ht.length){const Je=ht.join("");ht=[],k.current&&p(Ze=>Ze+Je)}St=null},Mt=()=>{typeof window<"u"&&St==null&&(St=requestAnimationFrame(Lt))};let nt=Date.now();const It=setInterval(()=>{var Je;if(Date.now()-nt>18e5){const Ze="Stream idle timeout";d(Ze),z="error",_=Ze,Q.abort(),(Je=M==null?void 0:M.onError)==null||Je.call(M,Ze)}},5e3),bn=1024*1024;try{const Je=rt.headers.get("X-Thread-Id")||rt.headers.get("x-thread-id"),Ze=rt.headers.get("X-Thread-Created")||rt.headers.get("x-thread-created"),pt=Je??null,lt=String(Ze??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:pt}),(X=M==null?void 0:M.onOpen)==null||X.call(M,{threadId:pt,created:lt});;){const{value:q,done:j}=await at.read();if(j)break;gt+=Rt.decode(q,{stream:!0}),gt.length>bn&&(gt="",console.warn("Stream buffer reset: exceeded 1MB"));let J;for(;(J=gt.indexOf(`
36
36
 
37
37
  `))>=0;){const ne=gt.slice(0,J);gt=gt.slice(J+2);const pe=Wg(ne);if(!pe)continue;let Ae;try{Ae=JSON.parse(pe)}catch{console.debug("[use-chat] malformed SSE:",pe.slice(0,200));continue}const be=Hg(Ae)?Ae.data:Ae;nt=Date.now();const Fe=be.seq;if(Fe!==void 0){if(Fe<=bt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Fe,lastProcessedSeq:bt,type:be.type});continue}bt>0&&Fe>bt+1&&((L=M==null?void 0:M.onGap)==null||L.call(M,{from:bt,to:Fe})),bt=Fe,C.current=Fe,y(Fe)}if(console.debug("[use-chat] received event",{seq:be.seq,type:be.type,preview:(()=>{var Pe;try{return be.type==="message_delta"?{deltaTypes:(Pe=be.delta)==null?void 0:Pe.map(Ne=>Ne.type),textLen:(be.delta||[]).filter(Ne=>Ne.type==="text").map(Ne=>String(Ne.text||"").length)}:be.content||be.delta?{hasContent:!0}:{}}catch(Ne){return{err:String(Ne)}}})()}),be.type==="checkpoint")I.current=be.checkpointId??null,A.current=be.checkpointNs??null,x(be.checkpointId??null);else if(be.type==="state_history"){R.current=be;try{const Ne=dr(be).latest;Ne&&(I.current=Ne.checkpointId??null,A.current=Ne.checkpointNs??null,x(Ne.checkpointId??null))}catch(Pe){console.warn("[use-chat] Failed to hydrate state_history payload",Pe)}}try{B==null||B(be)}catch(Pe){console.error("[use-chat] Error in onEvent callback:",Pe,"for event:",be.type)}if(be.type==="token"&&e.autoAppendAssistant!==!1)ht.push(be.content),Mt();else if(be.type==="message_delta"){const Pe=be.delta.filter(Ne=>Ne.type==="text").map(Ne=>Ne.text).join("");Pe&&e.autoAppendAssistant!==!1&&(ht.push(Pe),Mt())}else if(be.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(K=M==null?void 0:M.onHeartbeat)==null||K.call(M,be)}catch(Pe){console.warn("[use-chat] heartbeat callback failed",Pe)}}else if(St!==null&&cancelAnimationFrame(St),Lt(),be.type==="checkpoint")x(be.checkpointId);else if(be.type==="error"){const Pe=be;if(d(Pe.message),z="error",_=Pe.message,Pe.error_type==="auth_error"||Pe.code==="TOKEN_EXPIRED"||((Z=Pe.message)==null?void 0:Z.includes("token"))||((ce=Pe.message)==null?void 0:ce.includes("401"))||((re=Pe.message)==null?void 0:re.includes("unauthorized"))||((je=Pe.message)==null?void 0:je.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Pe.message);try{(Ue=M==null?void 0:M.onAuthError)==null||Ue.call(M,Pe.message)}catch(Vt){console.warn("[use-chat] onAuthError handler failed",Vt)}Q.abort()}}}}Lt(),z===null&&!Q.signal.aborted&&(z="complete")}catch(Je){if(Je.name==="AbortError")z=z??"aborted";else{const Ze=Je.message||String(Je);z="error",_=Ze,d(Ze),(De=M==null?void 0:M.onError)==null||De.call(M,Ze)}}finally{try{await at.cancel()}catch{}finally{(Ge=at.releaseLock)==null||Ge.call(at)}St!==null&&typeof window<"u"&&window.cancelAnimationFrame(St),clearInterval(It)}}catch(ie){if(ie.name==="AbortError")z=z??"aborted";else{const xe=ie.message||String(ie);z="error",_=xe,d(xe),(Ve=M==null?void 0:M.onError)==null||Ve.call(M,xe),V||((tt=M==null?void 0:M.onConnectionError)==null||tt.call(M,xe),V=!0)}}finally{const ie=C.current,xe=I.current,He=A.current,We=R.current,rt=z??(Q.signal.aborted?"aborted":_?"error":"complete");try{(Ye=M==null?void 0:M.onClosed)==null||Ye.call(M,{reason:rt,lastSeq:ie,lastCheckpointId:xe,lastCheckpointNs:He,lastStateHistory:We,error:_})}catch(at){console.warn("[use-chat] onClosed callback failed",at)}l(!1),b(!1),S.current=null,C.current=0,y(0),T.current=null}})(),{close:()=>Q.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var N;k.current=!1,(N=S.current)==null||N.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:h,lastSeq:m,connected:g,stream:F,stop:O,clear:P,setToken:$}}function Hg(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Wg(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
38
  `)}function Vg(e){return e.type!=="token"}const Kg={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function qg(e,t){var n;switch(t.type){case"reset":return{messages:fi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=fi(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=fi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return Xl(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>Xl(o,s),e):e}case"interrupt_response":return{...e,messages:Jl(e.messages),pendingInterrupt:null};default:return e}}function Yl(e=[]){const[t,n]=w.useReducer(qg,{...Kg,messages:e}),r=w.useRef([]),o=w.useRef(null),s=w.useRef(null),i=w.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=w.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=w.useCallback(d=>{r.current.push(d),a()},[a]);w.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=w.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 Xl(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=Jg(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},p={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:p}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??Zl(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(k=>k.id===a&&k.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},p=f[a]??{lastSeq:null,lastText:tc(d.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof p.lastSeq=="number"&&h<=p.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:p.lastSeq}),e;const{newParts:x,newMeta:m,changed:y}=Gg(d.content,t.delta,p,h);if(!y)return e;const g={...d,content:x},b=Ao(l,c,g),S={...f,[a]:m};return{...e,messages:b,messagesStreamMeta:S}}if(t.type==="message_end"){const a=e.assemblingId??Zl(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(p=>{var h;return(p==null?void 0:p.type)==="text"&&((h=p.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=d.content)==null?void 0:o.map(h=>(h==null?void 0:h.type)==="text"?String(h.text).slice(0,100):h==null?void 0:h.type)});const p=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:p}}}return e}if(t.type==="tool_start"){const a=Ql(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=ec(e,d,c),p=f>=0?e.messages[f]:null,h=l??d[0]??`${c}-${Date.now()}`,x=(p==null?void 0:p.id)??`tool-${h}`,m=d[0]??h,y={type:"tool_call",id:m,name:c,args:t.args};if(p){const S=hi(p,d,c,t.args),k={...p,name:p.name??c,additionalKwargs:S},C=f,T=C>=0?Ao(e.messages,C,k):e.messages,I=No(k,d),A=mi(e.toolIndex,x,I);return{...e,messages:T,toolIndex:A}}const g={id:x,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:hi(void 0,d.length?d:[m],c,t.args)},b=No(g,d.length?d:[m]);return{...e,messages:[...e.messages,g],toolIndex:mi(e.toolIndex,x,b)}}if(t.type==="tool_end"){const a=Ql(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=ec(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",p=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,h=(d==null?void 0:d.id)??`tool-${p}`,x=No(d,a);let m=t.output;if(typeof t.output=="string")try{const I=t.output.trim();(I.startsWith("{")||I.startsWith("["))&&(m=JSON.parse(I))}catch{m=t.output}const y=t.artifact??(d==null?void 0:d.artifact),g={type:"text",text:typeof m=="string"?m:JSON.stringify(m)},b=(d==null?void 0:d.createdAt)??new Date().toISOString(),S=hi(d??void 0,x.length?x:a,f),k={id:h,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[g],createdAt:b,artifact:y??void 0,additionalKwargs:S},C=c>=0?Ao(e.messages,c,k):[...e.messages,k],T=No(k,a.length?a:x);return{...e,messages:C,toolIndex:mi(e.toolIndex,h,T)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Xg(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=dr(t),l=a.interrupt,c=a.latest,d=l===null?Jl(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function fi(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 Ao(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Jl(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 Zl(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Ql(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 pi(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 hi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=pi(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};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 No(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=pi(e);for(const o of r)n.add(o);return Array.from(n)}function mi(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 ec(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(pi(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function tc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Gg(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??tc(e);let l="",c=e.slice();if(s){const f=Yg(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??"",x={...p,text:h+l};c=[...c.slice(0,c.length-1),x]}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 nc(e){return e.replace(/\s+/g," ").trim()}function Yg(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=nc(e),o=nc(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 Xg(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 Ao(e,r,s)}return e}function Jg(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const rc=200;function Zg({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=w.useRef(null),f=w.useRef(null),p=w.useRef(new Map),h=w.useRef(null),x=w.useRef(null),m=w.useCallback(P=>{try{const O=globalThis.structuredClone;if(typeof O=="function")return O(P)}catch{}try{return JSON.parse(JSON.stringify(P))}catch{return P}},[]),y=w.useCallback((P,O)=>{if(!P)return;const F=p.current.get(P)??[],N=m(O),B=F.length>=rc?[...F.slice(F.length-rc+1),N]:[...F,N];p.current.set(P,B)},[m]),g=w.useCallback(P=>{P&&p.current.set(P,[])},[]),b=w.useCallback(P=>{const O=P??f.current;if(!O)return;const F=p.current.get(O);F!=null&&F.length&&F.forEach(N=>{try{n(N)}catch(B){console.error("[useChatStreamingService] Failed to replay buffered event",B)}})},[n]),S=w.useCallback(P=>{var N,B,M,Q,z;const O=P.seq??null;if(O!==null){const _=d.current;if(_!==null){if(O<=_)return;O>_+1&&(s==null||s({from:_,to:O}))}d.current=O}if(P.type==="thread_info"){f.current=P.threadId,h.current&&(h.current.threadIdGuess=P.threadId),x.current=P,g(P.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",P);try{t(P)}catch(_){console.error("[useChatStreamingService] Error in onThreadInfo handler:",_)}return}if(P.type==="heartbeat"){try{c==null||c(P)}catch(_){console.error("[useChatStreamingService] Error in onHeartbeat handler:",_)}return}if(P.type==="error"){const _=P;if(_.error_type==="auth_error"||_.code==="TOKEN_EXPIRED"||((N=_.message)==null?void 0:N.includes("token"))||((B=_.message)==null?void 0:B.includes("401"))||((M=_.message)==null?void 0:M.includes("unauthorized"))||((Q=_.message)==null?void 0:Q.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",_.message);try{l==null||l(_.message)}catch(Y){console.warn("[useChatStreamingService] onAuthError handler failed",Y)}}}const F=P.threadId??(P.type==="state_history"?P.threadId:void 0)??f.current??((z=h.current)==null?void 0:z.threadIdGuess)??null;if(P.type==="state_history"){f.current=F??f.current;try{r==null||r(P)}catch(_){console.error("[useChatStreamingService] onStateHistory handler failed",_)}}if(Vg(P)){P.type==="checkpoint"||P.type==="state_history"?g(F??null):y(F??null,P);try{n(P)}catch(_){console.error("[useChatStreamingService] Error in onMessageEvent handler:",_)}return}try{o==null||o(P)}catch(_){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",_)}},[y,g,n,s,t,r,o]),{stream:k,stop:C,isStreaming:T,error:I,setToken:A}=Gl({baseUrl:e,token:void 0}),R=w.useCallback((P,O)=>{d.current=null,x.current=null,f.current=P.threadId??null,h.current={request:P,callbacks:O,manualStop:!1,threadIdGuess:P.threadId??null},k(P,S,{onOpen:O==null?void 0:O.onOpen,onError:F=>{var N;(N=O==null?void 0:O.onError)==null||N.call(O,F)},onGap:(O==null?void 0:O.onGap)??s,onConnectionError:F=>{var N;a==null||a(F),(N=O==null?void 0:O.onConnectionError)==null||N.call(O,F)},onAuthError:F=>{var N;l==null||l(F),(N=O==null?void 0:O.onAuthError)==null||N.call(O,F)},onHeartbeat:F=>{var N;try{c==null||c(F)}catch(B){console.warn("[useChatStreamingService] onHeartbeat handler failed",B)}try{(N=O==null?void 0:O.onHeartbeat)==null||N.call(O,F)}catch(B){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",B)}},onClosed:F=>{var Q,z,_,V;const N=((Q=h.current)==null?void 0:Q.manualStop)??!1,B=f.current??((z=h.current)==null?void 0:z.threadIdGuess)??((_=F.lastStateHistory)==null?void 0:_.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&N)&&g(B);const M={...F,threadId:B,threadInfo:x.current,manualStop:N};try{i==null||i(M)}catch(Y){console.warn("[useChatStreamingService] onStreamClosed handler failed",Y)}try{(V=O==null?void 0:O.onClosed)==null||V.call(O,M)}catch(Y){console.warn("[useChatStreamingService] downstream onClosed handler failed",Y)}h.current&&(h.current=null)}})},[g,S,l,a,c,s,i,k]),$=w.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return w.useMemo(()=>({startStream:R,stop:$,isStreaming:T,error:I,setAuthToken:A,replayBufferedEvents:b}),[R,$,T,I,A,b])}const oc=w.createContext(null),sc=w.createContext(null),ic=w.createContext(null);w.createContext(!1);function Qg({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a}){const{api:l,baseUrl:c}=ui(),d=w.useMemo(()=>wn(c),[c]),[f,p]=w.useState([]),[h,x]=w.useState(t),[m,y]=w.useState(!1),[g,b]=w.useState(null),[S,k]=w.useState(!1),[C,T]=w.useState(null),{state:I,seed:A,prepend:R,pushUser:$,onEvent:P}=Yl(),[O,F]=w.useState(!1),[N,B]=w.useState(!1),[M,Q]=w.useState(null),[z,_]=w.useState([]),[V,Y]=w.useState([]),[oe,ye]=w.useState(!1),Me=w.useMemo(()=>z.flatMap(q=>q.messages??[]),[z]),G=w.useMemo(()=>ql(Me),[Me]),U=w.useRef(h),X=w.useRef(null),L=w.useRef(null),K=w.useRef(null),Z=w.useRef(null),ce=w.useRef(!1),re=w.useRef(null),je=w.useRef(new Map),Ue=w.useRef(new Map);w.useEffect(()=>{U.current=h},[h]);const De=w.useCallback(async()=>{y(!0),b(null);try{const q=await l.listThreads();p(q??[])}catch(q){const j=String(q);b(j),s==null||s(j)}finally{y(!1)}},[l,s]),Ge=w.useCallback(q=>{if(!(q!=null&&q.threadId))return;const j={threadId:q.threadId,title:q.title||`Thread ${q.threadId.slice(0,8)}`,createdAt:q.createdAt||new Date().toISOString(),updatedAt:q.updatedAt||new Date().toISOString(),messageCount:q.messageCount??1};p(J=>J.some(pe=>pe.threadId===j.threadId)?(console.debug("[ChatSessionProvider] thread_info: thread already in list",j.threadId),J):(console.debug("[ChatSessionProvider] thread_info: adding thread to list",j.threadId),[j,...J]))},[]),Ve=w.useCallback(q=>{const j=q.threadId??U.current;if(!j||U.current&&U.current!==j)return;const{checkpoints:J,timeline:ne}=dr(q);if(!J.length)return;const pe=J.find(Ae=>Ae.messages&&Ae.messages.length>0)??J.find(Ae=>!!Ae.checkpointId)??J[0];A((pe==null?void 0:pe.messages)??[],{checkpointId:(pe==null?void 0:pe.checkpointId)??null,checkpointNs:(pe==null?void 0:pe.checkpointNs)??null}),Y(ne),_(J),F(!!(pe!=null&&pe.nextCursor)),Q((pe==null?void 0:pe.nextCursor)??null),re.current=`${j}:latest`,L.current=null,K.current=null},[A]),tt=w.useCallback(q=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",q.threadId),Ge(q),U.current!==q.threadId&&((q.created??!U.current)&&(L.current=q.threadId),K.current=q.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),x(q.threadId))},[Ge]),{startStream:Ye,stop:ie,isStreaming:xe,error:He,setAuthToken:We}=Zg({baseUrl:d,onThreadInfo:tt,onMessageEvent:P,onStateHistory:Ve,onUnhandledEvent:q=>{console.warn("[ChatSessionProvider] Unhandled event:",q.type)},onAuthError:i}),rt=w.useCallback(async q=>{try{const j=await l.createThread(q);return x(j.threadId),await De(),j.threadId}catch(j){return s==null||s(String(j)),null}},[l,De,s]),at=w.useCallback(async q=>{const j=f;p(ne=>ne.filter(pe=>pe.threadId!==q));const J=new AbortController;Ue.current.set(q,J);try{await l.deleteThread(q),U.current===q&&(x(null),A([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",q)}catch(ne){console.error("[ChatSessionProvider] Delete failed, restoring thread:",q,ne),p(j),s==null||s(`Failed to delete thread: ${String(ne)}`)}finally{Ue.current.delete(q)}},[f,l,A,s]),Rt=w.useCallback(async(q,j)=>{try{await l.updateThread(q,j),await De()}catch(J){s==null||s(String(J))}},[l,De,s]),gt=w.useCallback(async(q,j)=>{if(!q)return;const J=`${q}:${j??"latest"}`,ne=je.current.get(J);if(ne)return ne;const pe=(async()=>{const Ae=q;k(!0),T(null);try{const be=await l.getStateHistory({threadId:Ae,checkpointId:j||void 0});if(U.current!==Ae){console.log(`[ChatSessionProvider] Thread changed during load (was ${Ae}, now ${U.current}), discarding stale data`);return}const{checkpoints:Fe,timeline:Pe}=dr(be),Ne=Fe.find(Vt=>Vt.messages&&Vt.messages.length>0)??(j?Fe.find(Vt=>Vt.checkpointId===j):null)??Fe[0];A((Ne==null?void 0:Ne.messages)??[],{checkpointId:(Ne==null?void 0:Ne.checkpointId)??null,checkpointNs:(Ne==null?void 0:Ne.checkpointNs)??null}),Y(Pe),_(Fe),F(!!(Ne!=null&&Ne.nextCursor)),Q((Ne==null?void 0:Ne.nextCursor)??null)}catch(be){if(U.current===Ae){const Fe=String(be);T(Fe),s==null||s(Fe)}}finally{k(!1)}})();je.current.set(J,pe);try{await pe}finally{je.current.delete(J)}return U.current===q&&(re.current=J),pe},[l,A,s]),ht=w.useCallback(async(q,j)=>{Z.current=q;try{await gt(q,j)}finally{Z.current===q&&(Z.current=null)}},[gt]);w.useEffect(()=>{if(!o||!h||S||xe)return;if(L.current===h){L.current=null,X.current=h;return}if(K.current===h){X.current=h;return}if(Z.current===h){Z.current=null,X.current=h;return}if(X.current===h)return;X.current=h;const q=!ce.current&&!!n&&h===t;let j;q&&n?(j=n,ce.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",j,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const J=`${h}:${j??"latest"}`;re.current!==J&&ht(h,j)},[o,h,n,r,t,S,xe,ht]);const bt=w.useCallback(async(q,j)=>{const J=U.current;if(!J)return;const ne=J;ye(!0);try{const pe=await l.getStateHistory({threadId:ne,checkpointId:q,checkpointNs:j??void 0});if(U.current!==ne){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${ne}, now ${U.current}), discarding stale data`);return}const{checkpoints:Ae,timeline:be}=dr(pe),Fe=Ae.find(Pe=>Pe.checkpointId===q&&(j?Pe.checkpointNs===j:!0));if(!Fe){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:q,checkpointNs:j});return}Y(be),_(Ae),A(Fe.messages??[],{checkpointId:Fe.checkpointId??null,checkpointNs:Fe.checkpointNs??null})}catch(pe){U.current===ne&&(s==null||s(String(pe)))}finally{ye(!1)}},[l,A,s]),St=w.useCallback((q,j)=>{A(I.messages,{checkpointId:q??null,checkpointNs:j??null})},[A,I.messages]),Lt=w.useCallback(async()=>{U.current&&await ht(U.current)},[ht]),Mt=w.useCallback(async()=>{if(!U.current||!M)return;const q=U.current;B(!0);try{const j=await l.getStateHistory({threadId:q,checkpointId:M});if(U.current!==q)return;const{checkpoints:J}=dr(j);if(J.length>0){const ne=J[J.length-1];R((ne==null?void 0:ne.messages)??[]),F(!!(ne!=null&&ne.nextCursor)),Q((ne==null?void 0:ne.nextCursor)??null)}}catch(j){U.current===q&&(s==null||s(String(j)))}finally{B(!1)}},[l,M,R,s]),nt=w.useCallback(async()=>{A([],{}),x(null),ie(),_([]),Y([]),F(!1),Q(null),k(!1),ye(!1),B(!1),T(null);try{await l.getAgent("default")}catch(q){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",q)}},[A,ie,l]),It=w.useCallback(async(q,j,J)=>{const ne=U.current;if(!ne)throw new Error("No active thread to handle interrupt");const pe=j?J??!0:!1;try{const Ae={threadId:ne,checkpointId:I.lastCheckpointId??void 0,checkpointNs:I.lastCheckpointNs??void 0,command:{kind:"resume",value:pe}};Ye(Ae)}catch(Ae){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${q}:`,Ae),Ae}},[I.lastCheckpointId,I.lastCheckpointNs,Ye]);w.useEffect(()=>{De()},[De]),w.useEffect(()=>{a==null||a(h)},[h,a]);const bn=w.useCallback(async(q,j)=>{let J=U.current;const ne=(q==null?void 0:q.text)??"",pe=(q==null?void 0:q.attachments)??[],Ae=(ne==null?void 0:ne.trim())??"",be={...(q==null?void 0:q.payload)??{}},Fe=Array.isArray(be.messages)?be.messages:void 0;Fe&&delete be.messages;const Pe=!!(Fe&&Fe.length);if(!J&&!Ae&&pe.length===0&&!Pe)return;if(!J){const se=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),ve=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);J=`${se}${ve}`,L.current=J,x(J)}const{contentParts:Ne,filesInfo:Vt}=await yg(l,pe),En=[...Ne];Ae&&En.push({type:"text",text:ne});const ir=j==null?void 0:j.originalMessageId,Ar=!!(j!=null&&j.edit&&ir),fo=!Pe&&En.length>0;let zn=null;fo&&(zn={id:Ar?ir:`msg-${Date.now()}`,role:"user",content:En,createdAt:new Date().toISOString()},Ar||$(zn));const ar=Pe?Fe:zn?[zn]:[],E={...be,...Vt.length?{files_info:Vt}:{}};ar.length?E.messages=ar:"messages"in E||(E.messages=[]);const W={threadId:J,payload:E,checkpointId:(j==null?void 0:j.checkpointId)??I.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??I.lastCheckpointNs??void 0,edit:!!(j!=null&&j.edit),timelineCheckpoints:V};Ye(W)},[l,$,I,Ye,V]),Je=w.useMemo(()=>({threads:f,currentThreadId:h,setCurrentThreadId:x,isLoading:m,error:g,actions:{createThread:rt,deleteThread:at,renameThread:Rt,refreshThreads:De}}),[f,h,m,g,rt,at,Rt,De]),Ze=w.useMemo(()=>{const q=I.assemblingId??null;return q?{assemblingMessageId:q}:null},[I.assemblingId]),pt=w.useMemo(()=>({threadId:h,messages:I.messages,interrupt:null,checkpoint:{id:I.lastCheckpointId??null,namespace:I.lastCheckpointNs??null},checkpoints:z,timelineCheckpoints:V,metadata:Ze,isLoading:S,isHistoryLoading:N,isLoadingCheckpoint:oe,error:C,hasMore:O,loadOlder:Mt,clearState:nt,navigateToCheckpoint:bt,setCurrentCheckpointId:St,returnToLatest:Lt,loadThread:ht,clearThread:nt,respondToInterrupt:It,messagePreviews:G}),[h,I,z,V,S,N,oe,C,O,Mt,nt,bt,St,Lt,ht,It,G,Ze]),lt=w.useMemo(()=>({isStreaming:xe,error:He,connectionState:xe?"connected":"idle",submit:bn,send:bn,stop:ie,setAuthToken:We}),[xe,He,bn,ie,We]);return u.jsx(oc.Provider,{value:Je,children:u.jsx(sc.Provider,{value:pt,children:u.jsx(ic.Provider,{value:lt,children:e})})})}function _o(){const e=w.useContext(oc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function jo(){const e=w.useContext(sc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function ac(){const e=w.useContext(ic);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Ro({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onError:i,onAuthError:a,onThreadChange:l}){return u.jsx(gg,{apiConfig:t,children:u.jsx(Qg,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:i,onAuthError:a,onThreadChange:l,children:e})})}function te(...e){return Hh.twMerge(Uh.clsx(e))}const ex=po.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"}}),Qe=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Hn.Slot:"button";return u.jsx(i,{className:te(ex({variant:t,size:n,className:e})),ref:s,...o})});Qe.displayName="Button";const lc=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}));lc.displayName="Textarea";function cc({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 x=i!==void 0,[m,y]=w.useState(e),g=(x?i:m)??"",[b,S]=w.useTransition(),k=w.useRef(null),C=w.useRef(0),T=w.useRef(null);w.useEffect(()=>{x||(y(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,x]);const I=w.useCallback(()=>{const B=k.current;B&&(B.style.height="auto",B.style.height=`${B.scrollHeight}px`)},[]);w.useEffect(()=>{I()},[I,g]);const A=w.useCallback((B,{fromUser:M})=>{x||y(B),M&&(a==null||a(B))},[x,a]),R=w.useCallback(async B=>{B&&B.preventDefault();const M=(g??"").trim();if(!M&&!h)return;const Q=++C.current;T.current={id:Q,shouldClear:!0},S(()=>{var z,_,V;try{const Y=l(M);Y&&typeof Y.then=="function"?Y.then(()=>{var oe,ye;((oe=T.current)==null?void 0:oe.id)===Q&&T.current.shouldClear&&(x||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((ye=T.current)==null?void 0:ye.id)===Q&&(T.current=null)}).catch(()=>{var oe;((oe=T.current)==null?void 0:oe.id)===Q&&(T.current=null)}):(((z=T.current)==null?void 0:z.id)===Q&&T.current.shouldClear&&(x||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((_=T.current)==null?void 0:_.id)===Q&&(T.current=null))}catch{((V=T.current)==null?void 0:V.id)===Q&&(T.current=null)}})},[g,l,h,x,a]),$=w.useCallback(B=>{const M=B.target.value;A(M,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[A]),P=w.useCallback(B=>{B.key==="Enter"&&!B.shiftKey?(B.preventDefault(),R()):B.key==="Escape"&&t&&(B.preventDefault(),c==null||c())},[R,t,c]),N=`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:B=>void R(B),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(lc,{ref:k,value:g,onChange:$,onKeyDown:P,placeholder:t?"Edit your message...":n,className:N,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(Qe,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(ae.Square,{size:16})}):u.jsx(Qe,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!g.trim()&&!h||b,children:u.jsx(ae.Send,{size:16})})})]})})}const tx=w.memo(cc);function de(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 uc(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=uc(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():uc(e[o],null)}}}}function Be(...e){return v.useCallback(gi(...e),e)}function nx(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 Sn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var g;const{scope:p,children:h,...x}=f,m=((g=p==null?void 0:p[e])==null?void 0:g[l])||a,y=v.useMemo(()=>x,Object.values(x));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,x=v.useContext(h);if(x)return x;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,rx(o,...t)]}function rx(...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 Tt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},ox=v[" useInsertionEffect ".trim().toString()]||Tt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=sx({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=ix(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 sx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return ox(()=>{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 ix(e){return typeof e=="function"}var ax=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ee=ax.reduce((e,t)=>{const n=Hn.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 dc(e,t){e&&ho.flushSync(()=>e.dispatchEvent(t))}function xi(e){const t=e+"CollectionProvider",[n,r]=Sn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:y,children:g}=m,b=w.useRef(null),S=w.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:b,children:g})};i.displayName=t;const a=e+"CollectionSlot",l=Hn.createSlot(a),c=w.forwardRef((m,y)=>{const{scope:g,children:b}=m,S=s(a,g),k=Be(y,S.collectionRef);return u.jsx(l,{ref:k,children:b})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=Hn.createSlot(d),h=w.forwardRef((m,y)=>{const{scope:g,children:b,...S}=m,k=w.useRef(null),C=Be(y,k),T=s(d,g);return w.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:C,children:b})});h.displayName=d;function x(m){const y=s(e+"CollectionConsumer",m);return w.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const S=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((T,I)=>S.indexOf(T.ref.current)-S.indexOf(I.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},x,r]}var lx=v.createContext(void 0);function Mo(e){const t=v.useContext(lx);return e||t||"ltr"}function kt(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 cx(e,t=globalThis==null?void 0:globalThis.document){const n=kt(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 ux="DismissableLayer",yi="dismissableLayer.update",dx="dismissableLayer.pointerDownOutside",fx="dismissableLayer.focusOutside",fc,pc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Po=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(pc),[d,f]=v.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),x=Be(t,I=>f(I)),m=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=m.indexOf(y),b=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=b>=g,C=mx(I=>{const A=I.target,R=[...c.branches].some($=>$.contains(A));!k||R||(o==null||o(I),i==null||i(I),I.defaultPrevented||a==null||a())},p),T=gx(I=>{const A=I.target;[...c.branches].some($=>$.contains(A))||(s==null||s(I),i==null||i(I),I.defaultPrevented||a==null||a())},p);return cx(I=>{b===c.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&a&&(I.preventDefault(),a()))},p),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(fc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),hc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=fc)}},[d,p,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),hc())},[d,c]),v.useEffect(()=>{const I=()=>h({});return document.addEventListener(yi,I),()=>document.removeEventListener(yi,I)},[]),u.jsx(Ee.div,{...l,ref:x,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,T.onFocusCapture),onBlurCapture:de(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,C.onPointerDownCapture)})});Po.displayName=ux;var px="DismissableLayerBranch",hx=v.forwardRef((e,t)=>{const n=v.useContext(pc),r=v.useRef(null),o=Be(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ee.div,{...e,ref:o})});hx.displayName=px;function mx(e,t=globalThis==null?void 0:globalThis.document){const n=kt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){mc(dx,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 gx(e,t=globalThis==null?void 0:globalThis.document){const n=kt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&mc(fx,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 hc(){const e=new CustomEvent(yi);document.dispatchEvent(e)}function mc(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?dc(o,s):o.dispatchEvent(s)}var vi=0;function bi(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??gc()),document.body.insertAdjacentElement("beforeend",e[1]??gc()),vi++,()=>{vi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),vi--}},[])}function gc(){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 wi="focusScope.autoFocusOnMount",Si="focusScope.autoFocusOnUnmount",xc={bubbles:!1,cancelable:!0},xx="FocusScope",Oo=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=kt(o),d=kt(s),f=v.useRef(null),p=Be(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:Nn(f.current,{select:!0})},y=function(S){if(h.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||Nn(f.current,{select:!0}))},g=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&Nn(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const b=new MutationObserver(g);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),b.disconnect()}}},[r,a,h.paused]),v.useEffect(()=>{if(a){bc.add(h);const m=document.activeElement;if(!a.contains(m)){const g=new CustomEvent(wi,xc);a.addEventListener(wi,c),a.dispatchEvent(g),g.defaultPrevented||(yx(Cx(yc(a)),{select:!0}),document.activeElement===m&&Nn(a))}return()=>{a.removeEventListener(wi,c),setTimeout(()=>{const g=new CustomEvent(Si,xc);a.addEventListener(Si,d),a.dispatchEvent(g),g.defaultPrevented||Nn(m??document.body,{select:!0}),a.removeEventListener(Si,d),bc.remove(h)},0)}}},[a,c,d,h]);const x=v.useCallback(m=>{if(!n&&!r||h.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,g=document.activeElement;if(y&&g){const b=m.currentTarget,[S,k]=vx(b);S&&k?!m.shiftKey&&g===k?(m.preventDefault(),n&&Nn(S,{select:!0})):m.shiftKey&&g===S&&(m.preventDefault(),n&&Nn(k,{select:!0})):g===b&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Ee.div,{tabIndex:-1,...i,ref:p,onKeyDown:x})});Oo.displayName=xx;function yx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Nn(r,{select:t}),document.activeElement!==n)return}function vx(e){const t=yc(e),n=vc(t,e),r=vc(t.reverse(),e);return[n,r]}function yc(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 vc(e,t){for(const n of e)if(!bx(n,{upTo:t}))return n}function bx(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 wx(e){return e instanceof HTMLInputElement&&"select"in e}function Nn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&wx(e)&&t&&e.select()}}var bc=Sx();function Sx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=wc(e,t),e.unshift(t)},remove(t){var n;e=wc(e,t),(n=e[0])==null||n.resume()}}}function wc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Cx(e){return e.filter(t=>t.tagName!=="A")}var Tx=v[" useId ".trim().toString()]||(()=>{}),kx=0;function Cn(e){const[t,n]=v.useState(Tx());return Tt(()=>{n(r=>r??String(kx++))},[e]),t?`radix-${t}`:""}const Ix=["top","right","bottom","left"],_n=Math.min,zt=Math.max,Do=Math.round,Lo=Math.floor,dn=e=>({x:e,y:e}),Ex={left:"right",right:"left",bottom:"top",top:"bottom"},Ax={start:"end",end:"start"};function Ci(e,t,n){return zt(e,_n(t,n))}function Tn(e,t){return typeof e=="function"?e(t):e}function kn(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 Nx=new Set(["top","bottom"]);function fn(e){return Nx.has(kn(e))?"y":"x"}function Ii(e){return Ti(fn(e))}function _x(e,t,n){n===void 0&&(n=!1);const r=hr(e),o=Ii(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=$o(i)),[i,$o(i)]}function jx(e){const t=$o(e);return[Ei(e),t,Ei(t)]}function Ei(e){return e.replace(/start|end/g,t=>Ax[t])}const Sc=["left","right"],Cc=["right","left"],Rx=["top","bottom"],Mx=["bottom","top"];function Px(e,t,n){switch(e){case"top":case"bottom":return n?t?Cc:Sc:t?Sc:Cc;case"left":case"right":return t?Rx:Mx;default:return[]}}function Ox(e,t,n,r){const o=hr(e);let s=Px(kn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ei)))),s}function $o(e){return e.replace(/left|right|bottom|top/g,t=>Ex[t])}function Dx(e){return{top:0,right:0,bottom:0,left:0,...e}}function Tc(e){return typeof e!="number"?Dx(e):{top:e,right:e,bottom:e,left:e}}function Fo(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 kc(e,t,n){let{reference:r,floating:o}=e;const s=fn(t),i=Ii(t),a=ki(i),l=kn(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 Lx=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}=kc(c,r,l),p=r,h={},x=0;for(let m=0;m<a.length;m++){const{name:y,fn:g}=a[m],{x:b,y:S,data:k,reset:C}=await g({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=b??d,f=S??f,h={...h,[y]:{...h[y],...k}},C&&x<=50&&(x++,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}=kc(c,p,l)),m=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function Lr(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}=Tn(t,e),x=Tc(h),y=a[p?f==="floating"?"reference":"floating":f],g=Fo(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})),b=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=Fo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:S,strategy:l}):b);return{top:(g.top-C.top+x.top)/k.y,bottom:(C.bottom-g.bottom+x.bottom)/k.y,left:(g.left-C.left+x.left)/k.x,right:(C.right-g.right+x.right)/k.x}}const $x=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}=Tn(e,t)||{};if(c==null)return{};const f=Tc(d),p={x:n,y:r},h=Ii(o),x=ki(h),m=await i.getDimensions(c),y=h==="y",g=y?"top":"left",b=y?"bottom":"right",S=y?"clientHeight":"clientWidth",k=s.reference[x]+s.reference[h]-p[h]-s.floating[x],C=p[h]-s.reference[h],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let I=T?T[S]:0;(!I||!await(i.isElement==null?void 0:i.isElement(T)))&&(I=a.floating[S]||s.floating[x]);const A=k/2-C/2,R=I/2-m[x]/2-1,$=_n(f[g],R),P=_n(f[b],R),O=$,F=I-m[x]-P,N=I/2-m[x]/2+A,B=Ci(O,N,F),M=!l.arrow&&hr(o)!=null&&N!==B&&s.reference[x]/2-(N<O?$:P)-m[x]/2<0,Q=M?N<O?N-O:N-F:0;return{[h]:p[h]+Q,data:{[h]:B,centerOffset:N-B-Q,...M&&{alignmentOffset:Q}},reset:M}}}),Fx=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:x="none",flipAlignment:m=!0,...y}=Tn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const g=kn(o),b=fn(a),S=kn(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(S||!m?[$o(a)]:jx(a)),T=x!=="none";!p&&T&&C.push(...Ox(a,m,x,k));const I=[a,...C],A=await Lr(t,y),R=[];let $=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&R.push(A[g]),f){const N=_x(o,i,k);R.push(A[N[0]],A[N[1]])}if($=[...$,{placement:o,overflows:R}],!R.every(N=>N<=0)){var P,O;const N=(((P=s.flip)==null?void 0:P.index)||0)+1,B=I[N];if(B&&(!(f==="alignment"?b!==fn(B):!1)||$.every(z=>fn(z.placement)===b?z.overflows[0]>0:!0)))return{data:{index:N,overflows:$},reset:{placement:B}};let M=(O=$.filter(Q=>Q.overflows[0]<=0).sort((Q,z)=>Q.overflows[1]-z.overflows[1])[0])==null?void 0:O.placement;if(!M)switch(h){case"bestFit":{var F;const Q=(F=$.filter(z=>{if(T){const _=fn(z.placement);return _===b||_==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(_=>_>0).reduce((_,V)=>_+V,0)]).sort((z,_)=>z[1]-_[1])[0])==null?void 0:F[0];Q&&(M=Q);break}case"initialPlacement":M=a;break}if(o!==M)return{reset:{placement:M}}}return{}}}};function Ic(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Ec(e){return Ix.some(t=>e[t]>=0)}const Bx=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Tn(e,t);switch(r){case"referenceHidden":{const s=await Lr(t,{...o,elementContext:"reference"}),i=Ic(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Ec(i)}}}case"escaped":{const s=await Lr(t,{...o,altBoundary:!0}),i=Ic(s,n.floating);return{data:{escapedOffsets:i,escaped:Ec(i)}}}default:return{}}}}},Ac=new Set(["left","top"]);async function zx(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=kn(n),a=hr(n),l=fn(n)==="y",c=Ac.has(i)?-1:1,d=s&&l?-1:1,f=Tn(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:x}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof x=="number"&&(h=a==="end"?x*-1:x),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const Ux=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 zx(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}}}}},Hx=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:g,y:b}=y;return{x:g,y:b}}},...l}=Tn(e,t),c={x:n,y:r},d=await Lr(t,l),f=fn(kn(o)),p=Ti(f);let h=c[p],x=c[f];if(s){const y=p==="y"?"top":"left",g=p==="y"?"bottom":"right",b=h+d[y],S=h-d[g];h=Ci(b,h,S)}if(i){const y=f==="y"?"top":"left",g=f==="y"?"bottom":"right",b=x+d[y],S=x-d[g];x=Ci(b,x,S)}const m=a.fn({...t,[p]:h,[f]:x});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[f]:i}}}}}},Wx=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}=Tn(e,t),d={x:n,y:r},f=fn(o),p=Ti(f);let h=d[p],x=d[f];const m=Tn(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 g,b;const S=p==="y"?"width":"height",k=Ac.has(kn(o)),C=s.reference[f]-s.floating[S]+(k&&((g=i.offset)==null?void 0:g[f])||0)+(k?0:y.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((b=i.offset)==null?void 0:b[f])||0)-(k?y.crossAxis:0);x<C?x=C:x>T&&(x=T)}return{[p]:h,[f]:x}}}},Vx=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}=Tn(e,t),d=await Lr(t,c),f=kn(o),p=hr(o),h=fn(o)==="y",{width:x,height:m}=s.floating;let y,g;f==="top"||f==="bottom"?(y=f,g=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(g=f,y=p==="end"?"top":"bottom");const b=m-d.top-d.bottom,S=x-d.left-d.right,k=_n(m-d[y],b),C=_n(x-d[g],S),T=!t.middlewareData.shift;let I=k,A=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(A=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(I=b),T&&!p){const $=zt(d.left,0),P=zt(d.right,0),O=zt(d.top,0),F=zt(d.bottom,0);h?A=x-2*($!==0||P!==0?$+P:zt(d.left,d.right)):I=m-2*(O!==0||F!==0?O+F:zt(d.top,d.bottom))}await l({...t,availableWidth:A,availableHeight:I});const R=await i.getDimensions(a.floating);return x!==R.width||m!==R.height?{reset:{rects:!0}}:{}}}};function Bo(){return typeof window<"u"}function mr(e){return Nc(e)?(e.nodeName||"").toLowerCase():"#document"}function Ut(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function pn(e){var t;return(t=(Nc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Nc(e){return Bo()?e instanceof Node||e instanceof Ut(e).Node:!1}function rn(e){return Bo()?e instanceof Element||e instanceof Ut(e).Element:!1}function hn(e){return Bo()?e instanceof HTMLElement||e instanceof Ut(e).HTMLElement:!1}function _c(e){return!Bo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ut(e).ShadowRoot}const Kx=new Set(["inline","contents"]);function $r(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=on(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!Kx.has(o)}const qx=new Set(["table","td","th"]);function Gx(e){return qx.has(mr(e))}const Yx=[":popover-open",":modal"];function zo(e){return Yx.some(t=>{try{return e.matches(t)}catch{return!1}})}const Xx=["transform","translate","scale","rotate","perspective"],Jx=["transform","translate","scale","rotate","perspective","filter"],Zx=["paint","layout","strict","content"];function Ai(e){const t=Ni(),n=rn(e)?on(e):e;return Xx.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)||Jx.some(r=>(n.willChange||"").includes(r))||Zx.some(r=>(n.contain||"").includes(r))}function Qx(e){let t=jn(e);for(;hn(t)&&!gr(t);){if(Ai(t))return t;if(zo(t))return null;t=jn(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 on(e){return Ut(e).getComputedStyle(e)}function Uo(e){return rn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function jn(e){if(mr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||_c(e)&&e.host||pn(e);return _c(t)?t.host:t}function jc(e){const t=jn(e);return gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:hn(t)&&$r(t)?t:jc(t)}function Fr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=jc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Ut(o);if(s){const a=_i(i);return t.concat(i,i.visualViewport||[],$r(o)?o:[],a&&n?Fr(a):[])}return t.concat(o,Fr(o,[],n))}function _i(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Rc(e){const t=on(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=hn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Do(n)!==s||Do(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ji(e){return rn(e)?e:e.contextElement}function xr(e){const t=ji(e);if(!hn(t))return dn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Rc(t);let i=(s?Do(n.width):n.width)/r,a=(s?Do(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const ty=dn(0);function Mc(e){const t=Ut(e);return!Ni()||!t.visualViewport?ty:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function ny(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Ut(e)?!1:t}function qn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ji(e);let i=dn(1);t&&(r?rn(r)&&(i=xr(r)):i=xr(e));const a=ny(s,n,r)?Mc(s):dn(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=Ut(s),h=r&&rn(r)?Ut(r):r;let x=p,m=_i(x);for(;m&&r&&h!==x;){const y=xr(m),g=m.getBoundingClientRect(),b=on(m),S=g.left+(m.clientLeft+parseFloat(b.paddingLeft))*y.x,k=g.top+(m.clientTop+parseFloat(b.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=k,x=Ut(m),m=_i(x)}}return Fo({width:d,height:f,x:l,y:c})}function Ho(e,t){const n=Uo(e).scrollLeft;return t?t.left+n:qn(pn(e)).left+n}function Pc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Ho(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function ry(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=pn(r),a=t?zo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=dn(1);const d=dn(0),f=hn(r);if((f||!f&&!s)&&((mr(r)!=="body"||$r(i))&&(l=Uo(r)),hn(r))){const h=qn(r);c=xr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?Pc(i,l):dn(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 oy(e){return Array.from(e.getClientRects())}function sy(e){const t=pn(e),n=Uo(e),r=e.ownerDocument.body,o=zt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=zt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Ho(e);const a=-n.scrollTop;return on(r).direction==="rtl"&&(i+=zt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Oc=25;function iy(e,t){const n=Ut(e),r=pn(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=Ho(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,x=Math.abs(r.clientWidth-f.clientWidth-h);x<=Oc&&(s-=x)}else c<=Oc&&(s+=c);return{width:s,height:i,x:a,y:l}}const ay=new Set(["absolute","fixed"]);function ly(e,t){const n=qn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=hn(e)?xr(e):dn(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 Dc(e,t,n){let r;if(t==="viewport")r=iy(e,n);else if(t==="document")r=sy(pn(e));else if(rn(t))r=ly(t,n);else{const o=Mc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Fo(r)}function Lc(e,t){const n=jn(e);return n===t||!rn(n)||gr(n)?!1:on(n).position==="fixed"||Lc(n,t)}function cy(e,t){const n=t.get(e);if(n)return n;let r=Fr(e,[],!1).filter(a=>rn(a)&&mr(a)!=="body"),o=null;const s=on(e).position==="fixed";let i=s?jn(e):e;for(;rn(i)&&!gr(i);){const a=on(i),l=Ai(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&ay.has(o.position)||$r(i)&&!l&&Lc(e,i))?r=r.filter(d=>d!==i):o=a,i=jn(i)}return t.set(e,r),r}function uy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?zo(t)?[]:cy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Dc(t,d,o);return c.top=zt(f.top,c.top),c.right=_n(f.right,c.right),c.bottom=_n(f.bottom,c.bottom),c.left=zt(f.left,c.left),c},Dc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function dy(e){const{width:t,height:n}=Rc(e);return{width:t,height:n}}function fy(e,t,n){const r=hn(t),o=pn(t),s=n==="fixed",i=qn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=dn(0);function c(){l.x=Ho(o)}if(r||!r&&!s)if((mr(t)!=="body"||$r(o))&&(a=Uo(t)),r){const h=qn(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?Pc(o,a):dn(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 Ri(e){return on(e).position==="static"}function $c(e,t){if(!hn(e)||on(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return pn(e)===n&&(n=n.ownerDocument.body),n}function Fc(e,t){const n=Ut(e);if(zo(e))return n;if(!hn(e)){let o=jn(e);for(;o&&!gr(o);){if(rn(o)&&!Ri(o))return o;o=jn(o)}return n}let r=$c(e,t);for(;r&&Gx(r)&&Ri(r);)r=$c(r,t);return r&&gr(r)&&Ri(r)&&!Ai(r)?n:r||Qx(e)||n}const py=async function(e){const t=this.getOffsetParent||Fc,n=this.getDimensions,r=await n(e.floating);return{reference:fy(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function hy(e){return on(e).direction==="rtl"}const my={convertOffsetParentRelativeRectToViewportRelativeRect:ry,getDocumentElement:pn,getClippingRect:uy,getOffsetParent:Fc,getElementRects:py,getClientRects:oy,getDimensions:dy,getScale:xr,isElement:rn,isRTL:hy};function Bc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function gy(e,t){let n=null,r;const o=pn(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 x=Lo(f),m=Lo(o.clientWidth-(d+p)),y=Lo(o.clientHeight-(f+h)),g=Lo(d),S={rootMargin:-x+"px "+-m+"px "+-y+"px "+-g+"px",threshold:zt(0,_n(1,l))||1};let k=!0;function C(T){const I=T[0].intersectionRatio;if(I!==l){if(!k)return i();I?i(!1,I):r=setTimeout(()=>{i(!1,1e-7)},1e3)}I===1&&!Bc(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 xy(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?Fr(c):[],...Fr(t)]:[];d.forEach(g=>{o&&g.addEventListener("scroll",n,{passive:!0}),s&&g.addEventListener("resize",n)});const f=c&&a?gy(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(g=>{let[b]=g;b&&b.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 x,m=l?qn(e):null;l&&y();function y(){const g=qn(e);m&&!Bc(m,g)&&n(),m=g,x=requestAnimationFrame(y)}return n(),()=>{var g;d.forEach(b=>{o&&b.removeEventListener("scroll",n),s&&b.removeEventListener("resize",n)}),f==null||f(),(g=h)==null||g.disconnect(),h=null,l&&cancelAnimationFrame(x)}}const yy=Ux,vy=Hx,by=Fx,wy=Vx,Sy=Bx,zc=$x,Cy=Wx,Ty=(e,t,n)=>{const r=new Map,o={platform:my,...n},s={...o.platform,_c:r};return Lx(e,t,{...o,platform:s})};var ky=typeof document<"u",Iy=function(){},Wo=ky?w.useLayoutEffect:Iy;function Vo(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(!Vo(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)&&!Vo(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Uc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Hc(e,t){const n=Uc(e);return Math.round(t*n)/n}function Mi(e){const t=v.useRef(e);return Wo(()=>{t.current=e}),t}function Ey(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);Vo(p,r)||h(r);const[x,m]=v.useState(null),[y,g]=v.useState(null),b=v.useCallback(z=>{z!==T.current&&(T.current=z,m(z))},[]),S=v.useCallback(z=>{z!==I.current&&(I.current=z,g(z))},[]),k=s||x,C=i||y,T=v.useRef(null),I=v.useRef(null),A=v.useRef(d),R=l!=null,$=Mi(l),P=Mi(o),O=Mi(c),F=v.useCallback(()=>{if(!T.current||!I.current)return;const z={placement:t,strategy:n,middleware:p};P.current&&(z.platform=P.current),Ty(T.current,I.current,z).then(_=>{const V={..._,isPositioned:O.current!==!1};N.current&&!Vo(A.current,V)&&(A.current=V,ho.flushSync(()=>{f(V)}))})},[p,t,n,P,O]);Wo(()=>{c===!1&&A.current.isPositioned&&(A.current.isPositioned=!1,f(z=>({...z,isPositioned:!1})))},[c]);const N=v.useRef(!1);Wo(()=>(N.current=!0,()=>{N.current=!1}),[]),Wo(()=>{if(k&&(T.current=k),C&&(I.current=C),k&&C){if($.current)return $.current(k,C,F);F()}},[k,C,F,$,R]);const B=v.useMemo(()=>({reference:T,floating:I,setReference:b,setFloating:S}),[b,S]),M=v.useMemo(()=>({reference:k,floating:C}),[k,C]),Q=v.useMemo(()=>{const z={position:n,left:0,top:0};if(!M.floating)return z;const _=Hc(M.floating,d.x),V=Hc(M.floating,d.y);return a?{...z,transform:"translate("+_+"px, "+V+"px)",...Uc(M.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:_,top:V}},[n,a,M.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:F,refs:B,elements:M,floatingStyles:Q}),[d,F,B,M,Q])}const Ay=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?zc({element:r.current,padding:o}).fn(n):{}:r?zc({element:r,padding:o}).fn(n):{}}}},Ny=(e,t)=>({...yy(e),options:[e,t]}),_y=(e,t)=>({...vy(e),options:[e,t]}),jy=(e,t)=>({...Cy(e),options:[e,t]}),Ry=(e,t)=>({...by(e),options:[e,t]}),My=(e,t)=>({...wy(e),options:[e,t]}),Py=(e,t)=>({...Sy(e),options:[e,t]}),Oy=(e,t)=>({...Ay(e),options:[e,t]});var Dy="Arrow",Wc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Ee.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"})})});Wc.displayName=Dy;var Ly=Wc;function Vc(e){const[t,n]=v.useState(void 0);return Tt(()=>{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 Pi="Popper",[Kc,Ko]=Sn(Pi),[$y,qc]=Kc(Pi),Gc=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx($y,{scope:t,anchor:r,onAnchorChange:o,children:n})};Gc.displayName=Pi;var Yc="PopperAnchor",Xc=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=qc(Yc,n),i=v.useRef(null),a=Be(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(Ee.div,{...o,ref:a})});Xc.displayName=Yc;var Oi="PopperContent",[Fy,By]=Kc(Oi),Jc=v.forwardRef((e,t)=>{var X,L,K,Z,ce,re;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:x,...m}=e,y=qc(Oi,n),[g,b]=v.useState(null),S=Be(t,je=>b(je)),[k,C]=v.useState(null),T=Vc(k),I=(T==null?void 0:T.width)??0,A=(T==null?void 0:T.height)??0,R=r+(s!=="center"?"-"+s:""),$=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},P=Array.isArray(c)?c:[c],O=P.length>0,F={padding:$,boundary:P.filter(Uy),altBoundary:O},{refs:N,floatingStyles:B,placement:M,isPositioned:Q,middlewareData:z}=Ey({strategy:"fixed",placement:R,whileElementsMounted:(...je)=>xy(...je,{animationFrame:h==="always"}),elements:{reference:y.anchor},middleware:[Ny({mainAxis:o+A,alignmentAxis:i}),l&&_y({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?jy():void 0,...F}),l&&Ry({...F}),My({...F,apply:({elements:je,rects:Ue,availableWidth:De,availableHeight:Ge})=>{const{width:Ve,height:tt}=Ue.reference,Ye=je.floating.style;Ye.setProperty("--radix-popper-available-width",`${De}px`),Ye.setProperty("--radix-popper-available-height",`${Ge}px`),Ye.setProperty("--radix-popper-anchor-width",`${Ve}px`),Ye.setProperty("--radix-popper-anchor-height",`${tt}px`)}}),k&&Oy({element:k,padding:a}),Hy({arrowWidth:I,arrowHeight:A}),p&&Py({strategy:"referenceHidden",...F})]}),[_,V]=eu(M),Y=kt(x);Tt(()=>{Q&&(Y==null||Y())},[Q,Y]);const oe=(X=z.arrow)==null?void 0:X.x,ye=(L=z.arrow)==null?void 0:L.y,Me=((K=z.arrow)==null?void 0:K.centerOffset)!==0,[G,U]=v.useState();return Tt(()=>{g&&U(window.getComputedStyle(g).zIndex)},[g]),u.jsx("div",{ref:N.setFloating,"data-radix-popper-content-wrapper":"",style:{...B,transform:Q?B.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:G,"--radix-popper-transform-origin":[(Z=z.transformOrigin)==null?void 0:Z.x,(ce=z.transformOrigin)==null?void 0:ce.y].join(" "),...((re=z.hide)==null?void 0:re.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(Fy,{scope:n,placedSide:_,onArrowChange:C,arrowX:oe,arrowY:ye,shouldHideArrow:Me,children:u.jsx(Ee.div,{"data-side":_,"data-align":V,...m,ref:S,style:{...m.style,animation:Q?void 0:"none"}})})})});Jc.displayName=Oi;var Zc="PopperArrow",zy={top:"bottom",right:"left",bottom:"top",left:"right"},Qc=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=By(Zc,r),i=zy[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(Ly,{...o,ref:n,style:{...o.style,display:"block"}})})});Qc.displayName=Zc;function Uy(e){return e!==null}var Hy=e=>({name:"transformOrigin",options:e,fn(t){var y,g,b;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]=eu(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((g=o.arrow)==null?void 0:g.x)??0)+a/2,h=(((b=o.arrow)==null?void 0:b.y)??0)+l/2;let x="",m="";return c==="bottom"?(x=i?f:`${p}px`,m=`${-l}px`):c==="top"?(x=i?f:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(x=`${-l}px`,m=i?f:`${h}px`):c==="left"&&(x=`${r.floating.width+l}px`,m=i?f:`${h}px`),{data:{x,y:m}}}});function eu(e){const[t,n="center"]=e.split("-");return[t,n]}var tu=Gc,nu=Xc,ru=Jc,ou=Qc,Wy="Portal",qo=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Tt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Gs.createPortal(u.jsx(Ee.div,{...r,ref:t}),i):null});qo.displayName=Wy;function Vy(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Yt=e=>{const{present:t,children:n}=e,r=Ky(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Be(r.ref,qy(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Yt.displayName="Presence";function Ky(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Vy(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Go(r.current);s.current=a==="mounted"?c:"none"},[a]),Tt(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=Go(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]),Tt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const m=Go(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=Go(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 Go(e){return(e==null?void 0:e.animationName)||"none"}function qy(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",Gy={bubbles:!1,cancelable:!0},Br="RovingFocusGroup",[Li,su,Yy]=xi(Br),[Xy,iu]=Sn(Br,[Yy]),[Jy,Zy]=Xy(Br),au=v.forwardRef((e,t)=>u.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Qy,{...e,ref:t})})}));au.displayName=Br;var Qy=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=Be(t,p),x=Mo(s),[m,y]=pr({prop:i,defaultProp:a??null,onChange:l,caller:Br}),[g,b]=v.useState(!1),S=kt(c),k=su(n),C=v.useRef(!1),[T,I]=v.useState(0);return v.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(Di,S),()=>A.removeEventListener(Di,S)},[S]),u.jsx(Jy,{scope:n,orientation:r,dir:x,loop:o,currentTabStopId:m,onItemFocus:v.useCallback(A=>y(A),[y]),onItemShiftTab:v.useCallback(()=>b(!0),[]),onFocusableItemAdd:v.useCallback(()=>I(A=>A+1),[]),onFocusableItemRemove:v.useCallback(()=>I(A=>A-1),[]),children:u.jsx(Ee.div,{tabIndex:g||T===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{C.current=!0}),onFocus:de(e.onFocus,A=>{const R=!C.current;if(A.target===A.currentTarget&&R&&!g){const $=new CustomEvent(Di,Gy);if(A.currentTarget.dispatchEvent($),!$.defaultPrevented){const P=k().filter(M=>M.focusable),O=P.find(M=>M.active),F=P.find(M=>M.id===m),B=[O,F,...P].filter(Boolean).map(M=>M.ref.current);uu(B,d)}}C.current=!1}),onBlur:de(e.onBlur,()=>b(!1))})})}),lu="RovingFocusGroupItem",cu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=Cn(),c=s||l,d=Zy(lu,n),f=d.currentTabStopId===c,p=su(n),{onFocusableItemAdd:h,onFocusableItemRemove:x,currentTabStopId:m}=d;return v.useEffect(()=>{if(r)return h(),()=>x()},[r,h,x]),u.jsx(Li.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Ee.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:de(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:de(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:de(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const g=nv(y,d.orientation,d.dir);if(g!==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(g==="last")S.reverse();else if(g==="prev"||g==="next"){g==="prev"&&S.reverse();const k=S.indexOf(y.currentTarget);S=d.loop?rv(S,k+1):S.slice(k+1)}setTimeout(()=>uu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});cu.displayName=lu;var ev={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function tv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function nv(e,t,n){const r=tv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return ev[r]}function uu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function rv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var ov=au,sv=cu,iv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},yr=new WeakMap,Yo=new WeakMap,Xo={},$i=0,du=function(e){return e&&(e.host||du(e.parentNode))},av=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=du(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})},lv=function(e,t,n,r){var o=av(t,Array.isArray(e)?e:[e]);Xo[n]||(Xo[n]=new WeakMap);var s=Xo[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),x=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&&x&&Yo.set(p,!0),y===1&&p.setAttribute(n,"true"),x||p.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",p,g)}})};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||(Yo.has(f)||f.removeAttribute(r),Yo.delete(f)),h||f.removeAttribute(n)}),$i--,$i||(yr=new WeakMap,yr=new WeakMap,Yo=new WeakMap,Xo={})}},Fi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=iv(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),lv(r,o,n,"aria-hidden")):function(){return null}},mn=function(){return mn=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},mn.apply(this,arguments)};function fu(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 cv(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 Jo="right-scroll-bar-position",Zo="width-before-scroll-bar",uv="with-scroll-bars-hidden",dv="--removed-body-scroll-bar-size";function Bi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function fv(e,t){var n=w.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 pv=typeof window<"u"?v.useLayoutEffect:v.useEffect,pu=new WeakMap;function hv(e,t){var n=fv(null,function(r){return e.forEach(function(o){return Bi(o,r)})});return pv(function(){var r=pu.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)})}pu.set(n,e)},[e]),n}function mv(e){return e}function gv(e,t){t===void 0&&(t=mv);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 xv(e){e===void 0&&(e={});var t=gv(null);return t.options=mn({async:!0,ssr:!1},e),t}var hu=function(e){var t=e.sideCar,n=fu(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,mn({},n))};hu.isSideCarExport=!0;function yv(e,t){return e.useMedium(t),hu}var mu=xv(),zi=function(){},Qo=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,x=e.noIsolation,m=e.inert,y=e.allowPinchZoom,g=e.as,b=g===void 0?"div":g,S=e.gapMode,k=fu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,T=hv([n,t]),I=mn(mn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(C,{sideCar:mu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:x,inert:m,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),mn(mn({},I),{ref:T})):v.createElement(b,mn({},I,{className:l,ref:T}),a))});Qo.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Qo.classNames={fullWidth:Zo,zeroRight:Jo};var vv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function bv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=vv();return t&&e.setAttribute("nonce",t),e}function wv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Sv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Cv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=bv())&&(wv(t,n),Sv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Tv=function(){var e=Cv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},gu=function(){var e=Tv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},kv={left:0,top:0,right:0,gap:0},Ui=function(e){return parseInt(e||"",10)||0},Iv=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)]},Ev=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return kv;var t=Iv(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])}},Av=gu(),vr="data-scroll-locked",Nv=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
@@ -10,6 +10,7 @@ export type TimelineCheckpoint = {
10
10
  source: string | null;
11
11
  createdAt: string | null;
12
12
  next?: string | null;
13
+ parentConfig?: Record<string, unknown> | null;
13
14
  };
14
15
  export type CheckpointMeta = {
15
16
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teodor-new-chat-ui",
3
- "version": "4.3.334",
3
+ "version": "4.3.335",
4
4
  "description": "React chat UI components with streaming support, tool calls, and modern design",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.esm.js",