teodor-new-chat-ui 4.3.391 → 4.3.392
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 +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.esm.js
CHANGED
|
@@ -2719,7 +2719,7 @@ function Kx(e) {
|
|
|
2719
2719
|
step: t.metadata.step,
|
|
2720
2720
|
source: t.metadata.source,
|
|
2721
2721
|
createdAt: t.createdAt ?? null,
|
|
2722
|
-
next: t.
|
|
2722
|
+
next: t.next && t.next.length > 0 ? String(t.next[0]) : null,
|
|
2723
2723
|
parentConfig: t.parentConfig ?? null
|
|
2724
2724
|
};
|
|
2725
2725
|
}), [e]);
|
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[Nl]=this[Nl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Pr(i);r[a]||(gg(o,i),r[a]=!0)}return $.isArray(t)?t.forEach(s):s(t),this}};$t.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),$.reduceDescriptors($t.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),$.freezeMethods($t);function li(e,t){const n=this||Rr,r=t||n,o=$t.from(r.headers);let s=r.data;return $.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function Al(e){return!!(e&&e.__CANCEL__)}function cr(e,t,n){Me.call(this,e??"canceled",Me.ERR_CANCELED,t,n),this.name="CanceledError"}$.inherits(cr,Me,{__CANCEL__:!0});function jl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Me("Request failed with status code "+n.status,[Me.ERR_BAD_REQUEST,Me.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function xg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function vg(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(c){const u=Date.now(),d=r[s];i||(i=u),n[o]=c,r[o]=u;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),u-i<t)return;const p=d&&u-d;return p?Math.round(h*1e3/p):void 0}}function bg(e,t){let n=0,r=1e3/t,o,s;const i=(u,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...u)};return[(...u)=>{const d=Date.now(),f=d-n;f>=r?i(u,d):(o=u,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const To=(e,t,n=3)=>{let r=0;const o=vg(50,250);return bg(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,c=i-r,u=o(c),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:u||void 0,estimated:u&&a&&d?(a-i)/u:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},_l=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ml=e=>(...t)=>$.asap(()=>e(...t)),wg=jt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,jt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(jt.origin),jt.navigator&&/(msie|trident)/i.test(jt.navigator.userAgent)):()=>!0,yg=jt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];$.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),$.isString(r)&&i.push("path="+r),$.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 Sg(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Cg(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Rl(e,t,n){let r=!Sg(t);return e&&(r||n==!1)?Cg(e,t):t}const Pl=e=>e instanceof $t?{...e}:e;function Un(e,t){t=t||{};const n={};function r(u,d,f,h){return $.isPlainObject(u)&&$.isPlainObject(d)?$.merge.call({caseless:h},u,d):$.isPlainObject(d)?$.merge({},d):$.isArray(d)?d.slice():d}function o(u,d,f,h){if($.isUndefined(d)){if(!$.isUndefined(u))return r(void 0,u,f,h)}else return r(u,d,f,h)}function s(u,d){if(!$.isUndefined(d))return r(void 0,d)}function i(u,d){if($.isUndefined(d)){if(!$.isUndefined(u))return r(void 0,u)}else return r(void 0,d)}function a(u,d,f){if(f in t)return r(u,d);if(f in e)return r(void 0,u)}const c={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:(u,d,f)=>o(Pl(u),Pl(d),f,!0)};return $.forEach(Object.keys({...e,...t}),function(d){const f=c[d]||o,h=f(e[d],t[d],d);$.isUndefined(h)&&f!==a||(n[d]=h)}),n}const Ol=e=>{const t=Un({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=$t.from(i),t.url=kl(Rl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),$.isFormData(n)){if(jt.hasStandardBrowserEnv||jt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if($.isFunction(n.getHeaders)){const c=n.getHeaders(),u=["content-type","content-length"];Object.entries(c).forEach(([d,f])=>{u.includes(d.toLowerCase())&&i.set(d,f)})}}if(jt.hasStandardBrowserEnv&&(r&&$.isFunction(r)&&(r=r(t)),r||r!==!1&&wg(t.url))){const c=o&&s&&yg.read(s);c&&i.set(o,c)}return t},kg=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=Ol(e);let s=o.data;const i=$t.from(o.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:u}=o,d,f,h,p,v;function b(){p&&p(),v&&v(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let g=new XMLHttpRequest;g.open(o.method.toUpperCase(),o.url,!0),g.timeout=o.timeout;function x(){if(!g)return;const C=$t.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),S={data:!a||a==="text"||a==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:C,config:e,request:g};jl(function(E){n(E),b()},function(E){r(E),b()},S),g=null}"onloadend"in g?g.onloadend=x:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(x)},g.onabort=function(){g&&(r(new Me("Request aborted",Me.ECONNABORTED,e,g)),g=null)},g.onerror=function(T){const S=T&&T.message?T.message:"Network Error",k=new Me(S,Me.ERR_NETWORK,e,g);k.event=T||null,r(k),g=null},g.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const S=o.transitional||El;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new Me(T,S.clarifyTimeoutError?Me.ETIMEDOUT:Me.ECONNABORTED,e,g)),g=null},s===void 0&&i.setContentType(null),"setRequestHeader"in g&&$.forEach(i.toJSON(),function(T,S){g.setRequestHeader(S,T)}),$.isUndefined(o.withCredentials)||(g.withCredentials=!!o.withCredentials),a&&a!=="json"&&(g.responseType=o.responseType),u&&([h,v]=To(u,!0),g.addEventListener("progress",h)),c&&g.upload&&([f,p]=To(c),g.upload.addEventListener("progress",f),g.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(d=C=>{g&&(r(!C||C.type?new cr(null,e,g):C),g.abort(),g=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const w=xg(o.url);if(w&&jt.protocols.indexOf(w)===-1){r(new Me("Unsupported protocol "+w+":",Me.ERR_BAD_REQUEST,e));return}g.send(s||null)})},Tg=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(u){if(!o){o=!0,a();const d=u instanceof Error?u:this.reason;r.abort(d instanceof Me?d:new cr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Me(`timeout ${t} of ms exceeded`,Me.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(s):u.removeEventListener("abort",s)}),e=null)};e.forEach(u=>u.addEventListener("abort",s));const{signal:c}=r;return c.unsubscribe=()=>$.asap(a),c}},Eg=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},Ig=async function*(e,t){for await(const n of Ng(e))yield*Eg(n,t)},Ng=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()}},Dl=(e,t,n,r)=>{const o=Ig(e,t);let s=0,i,a=c=>{i||(i=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:u,value:d}=await o.next();if(u){a(),c.close();return}let f=d.byteLength;if(n){let h=s+=f;n(h)}c.enqueue(new Uint8Array(d))}catch(u){throw a(u),u}},cancel(c){return a(c),o.return()}},{highWaterMark:2})},Ll=64*1024,{isFunction:Eo}=$,Ag=(({Request:e,Response:t})=>({Request:e,Response:t}))($.global),{ReadableStream:$l,TextEncoder:Fl}=$.global,Bl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},jg=e=>{e=$.merge.call({skipUndefined:!0},Ag,e);const{fetch:t,Request:n,Response:r}=e,o=t?Eo(t):typeof fetch=="function",s=Eo(n),i=Eo(r);if(!o)return!1;const a=o&&Eo($l),c=o&&(typeof Fl=="function"?(v=>b=>v.encode(b))(new Fl):async v=>new Uint8Array(await new n(v).arrayBuffer())),u=s&&a&&Bl(()=>{let v=!1;const b=new n(jt.origin,{body:new $l,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!b}),d=i&&a&&Bl(()=>$.isReadableStream(new r("").body)),f={stream:d&&(v=>v.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!f[v]&&(f[v]=(b,g)=>{let x=b&&b[v];if(x)return x.call(b);throw new Me(`Response type '${v}' is not supported`,Me.ERR_NOT_SUPPORT,g)})});const h=async v=>{if(v==null)return 0;if($.isBlob(v))return v.size;if($.isSpecCompliantForm(v))return(await new n(jt.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if($.isArrayBufferView(v)||$.isArrayBuffer(v))return v.byteLength;if($.isURLSearchParams(v)&&(v=v+""),$.isString(v))return(await c(v)).byteLength},p=async(v,b)=>{const g=$.toFiniteNumber(v.getContentLength());return g??h(b)};return async v=>{let{url:b,method:g,data:x,signal:w,cancelToken:C,timeout:T,onDownloadProgress:S,onUploadProgress:k,responseType:E,headers:j,withCredentials:O="same-origin",fetchOptions:F}=Ol(v),H=t||fetch;E=E?(E+"").toLowerCase():"text";let U=Tg([w,C&&C.toAbortSignal()],T),q=null;const P=U&&U.unsubscribe&&(()=>{U.unsubscribe()});let z;try{if(k&&u&&g!=="get"&&g!=="head"&&(z=await p(j,x))!==0){let W=new n(b,{method:"POST",body:x,duplex:"half"}),_;if($.isFormData(x)&&(_=W.headers.get("content-type"))&&j.setContentType(_),W.body){const[V,ie]=_l(z,To(Ml(k)));x=Dl(W.body,Ll,V,ie)}}$.isString(O)||(O=O?"include":"omit");const I=s&&"credentials"in n.prototype,D={...F,signal:U,method:g.toUpperCase(),headers:j.normalize().toJSON(),body:x,duplex:"half",credentials:I?O:void 0};q=s&&new n(b,D);let R=await(s?H(q,F):H(b,D));const A=d&&(E==="stream"||E==="response");if(d&&(S||A&&P)){const W={};["status","statusText","headers"].forEach(Q=>{W[Q]=R[Q]});const _=$.toFiniteNumber(R.headers.get("content-length")),[V,ie]=S&&_l(_,To(Ml(S),!0))||[];R=new r(Dl(R.body,Ll,V,()=>{ie&&ie(),P&&P()}),W)}E=E||"text";let B=await f[$.findKey(f,E)||"text"](R,v);return!A&&P&&P(),await new Promise((W,_)=>{jl(W,_,{data:B,headers:$t.from(R.headers),status:R.status,statusText:R.statusText,config:v,request:q})})}catch(I){throw P&&P(),I&&I.name==="TypeError"&&/Load failed|fetch/i.test(I.message)?Object.assign(new Me("Network Error",Me.ERR_NETWORK,v,q),{cause:I.cause||I}):Me.from(I,I&&I.code,v,q)}}},_g=new Map,zl=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,c,u,d=_g;for(;a--;)c=s[a],u=d.get(c),u===void 0&&d.set(c,u=a?new Map:jg(t)),d=u;return u};zl();const ci={http:Qm,xhr:kg,fetch:{get:zl}};$.forEach(ci,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Hl=e=>`- ${e}`,Mg=e=>$.isFunction(e)||e===null||e===!1,Ul={getAdapter:(e,t)=>{e=$.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,!Mg(r)&&(o=ci[(a=String(r)).toLowerCase()],o===void 0))throw new Me(`Unknown adapter '${a}'`);if(o&&($.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([c,u])=>`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
|
|
33
33
|
`+i.map(Hl).join(`
|
|
34
34
|
`):" "+Hl(i[0]):"as no adapter specified";throw new Me("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:ci};function ui(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new cr(null,e)}function Wl(e){return ui(e),e.headers=$t.from(e.headers),e.data=li.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ul.getAdapter(e.adapter||Rr.adapter,e)(e).then(function(r){return ui(e),r.data=li.call(e,e.transformResponse,r),r.headers=$t.from(r.headers),r},function(r){return Al(r)||(ui(e),r&&r.response&&(r.response.data=li.call(e,e.transformResponse,r.response),r.response.headers=$t.from(r.response.headers))),Promise.reject(r)})}const Vl="1.12.2",Io={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Io[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const ql={};Io.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Vl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Me(o(i," has been removed"+(n?" in "+n:"")),Me.ERR_DEPRECATED);return n&&!ql[i]&&(ql[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}},Io.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Rg(e,t,n){if(typeof e!="object")throw new Me("options must be an object",Me.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],c=a===void 0||i(a,s,e);if(c!==!0)throw new Me("option "+s+" must be "+c,Me.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Me("Unknown option "+s,Me.ERR_BAD_OPTION)}}const No={assertOptions:Rg,validators:Io},un=No.validators;let Wn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Tl,response:new Tl}}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=Un(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&No.assertOptions(r,{silentJSONParsing:un.transitional(un.boolean),forcedJSONParsing:un.transitional(un.boolean),clarifyTimeoutError:un.transitional(un.boolean)},!1),o!=null&&($.isFunction(o)?n.paramsSerializer={serialize:o}:No.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),No.assertOptions(n,{baseUrl:un.spelling("baseURL"),withXsrfToken:un.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&$.merge(s.common,s[n.method]);s&&$.forEach(["delete","get","head","post","put","patch","common"],v=>{delete s[v]}),n.headers=$t.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(b){typeof b.runWhen=="function"&&b.runWhen(n)===!1||(c=c&&b.synchronous,a.unshift(b.fulfilled,b.rejected))});const u=[];this.interceptors.response.forEach(function(b){u.push(b.fulfilled,b.rejected)});let d,f=0,h;if(!c){const v=[Wl.bind(this),void 0];for(v.unshift(...a),v.push(...u),h=v.length,d=Promise.resolve(n);f<h;)d=d.then(v[f++],v[f++]);return d}h=a.length;let p=n;for(;f<h;){const v=a[f++],b=a[f++];try{p=v(p)}catch(g){b.call(this,g);break}}try{d=Wl.call(this,p)}catch(v){return Promise.reject(v)}for(f=0,h=u.length;f<h;)d=d.then(u[f++],u[f++]);return d}getUri(t){t=Un(this.defaults,t);const n=Rl(t.baseURL,t.url,t.allowAbsoluteUrls);return kl(n,t.params,t.paramsSerializer)}};$.forEach(["delete","get","head","options"],function(t){Wn.prototype[t]=function(n,r){return this.request(Un(r||{},{method:t,url:n,data:(r||{}).data}))}}),$.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Un(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Wn.prototype[t]=n(),Wn.prototype[t+"Form"]=n(!0)});let Pg=class um{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 cr(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 um(function(o){t=o}),cancel:t}}};function Og(e){return function(n){return e.apply(null,n)}}function Dg(e){return $.isObject(e)&&e.isAxiosError===!0}const di={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(di).forEach(([e,t])=>{di[t]=e});function Kl(e){const t=new Wn(e),n=cl(Wn.prototype.request,t);return $.extend(n,Wn.prototype,t,{allOwnKeys:!0}),$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Kl(Un(e,o))},n}const xt=Kl(Rr);xt.Axios=Wn,xt.CanceledError=cr,xt.CancelToken=Pg,xt.isCancel=Al,xt.VERSION=Vl,xt.toFormData=Co,xt.AxiosError=Me,xt.Cancel=xt.CanceledError,xt.all=function(t){return Promise.all(t)},xt.spread=Og,xt.isAxiosError=Dg,xt.mergeConfig=Un,xt.AxiosHeaders=$t,xt.formToJSON=e=>Il($.isHTMLForm(e)?new FormData(e):e),xt.getAdapter=Ul.getAdapter,xt.HttpStatusCode=di,xt.default=xt;const{Axios:fT,AxiosError:hT,CanceledError:pT,isCancel:mT,CancelToken:gT,VERSION:xT,all:vT,Cancel:bT,isAxiosError:wT,spread:yT,toFormData:ST,AxiosHeaders:CT,HttpStatusCode:kT,formToJSON:TT,getAdapter:ET,mergeConfig:IT}=xt,Gl=typeof window<"u"?window.__API_BASE_URL__:void 0,Yl=Gl?wn(Gl):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 Ao=null;const fi=new Set;function Xl(){return Ao}function jo(e){Ao=e,fi.forEach(t=>t(e))}function Jl(e){return fi.add(e),()=>fi.delete(e)}const Lg=3e4,$g=9e4,Kt=xt.create({...Yl?{baseURL:Yl}:{},timeout:Lg,withCredentials:!0});Kt.interceptors.request.use(e=>(Ao&&(e.headers.Authorization=`Bearer ${Ao}`),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),jo(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Gt(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function _o(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 Zl(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 hi(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Ft(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Ql{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&&jo(t.authToken)}getAuthToken(){return Xl()}setAuthToken(t){jo(t)}onTokenChange(t){return Jl(t)}async listThreads(){const t=await Gt("/threads"),n=Ft(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await Gt("/threads/shared"),n=Ft(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await _o("/threads",t?{title:t}:void 0);return Ft(r)}async updateThread(t,n){const r=await Zl(`/threads/${t}`,{title:n});return Ft(r)}async deleteThread(t){const n=await hi(`/threads/${t}`);return Ft(n)}async shareThread(t,n){const r=await _o(`/threads/${t}/share`,{shared_with_user_id:n});return Ft(r)}async threadInfo(t){const n=await Gt(`/threads/${t}/info`);return Ft(n)}async listAgents(){const t=await Gt("/agents"),n=Ft(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Gt(`/agents/${t}`);return Ft(n)}async getAgentSchema(t){const n=await Gt(`/agents/${t}/schema`);return Ft(n)}async getState(t){const n=await Gt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ft(n)}async getStateHistory(t){const n=await Gt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:$g});return Ft(n)}async cancelRun(t){const n=await _o("/runs/cancel",{threadId:t});return Ft(n)}async unshareThread(t,n){const r=await hi(`/threads/${t}/share/${n}`);return Ft(r)}}const Tn=new Ql,ec=y.createContext(null);function Fg({children:e,apiConfig:t}){const n=Tn;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 l.jsx(ec.Provider,{value:r,children:e})}function pi(){const e=y.useContext(ec);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Bg(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 c=0;c<a;c++)i+=String.fromCharCode(s[c]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function zg(e=[]){const t=[],n=[];for(const r of e)try{const o=await Bg(r);n.push({filename:r.name,data:o,mime_type:r.type||"application/octet-stream"})}catch{}return{contentParts:t,filesInfo:n}}const tc=120;function Hg(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>tc?`${n.slice(0,tc-3)}…`:n:""}function nc(e){return Hg(e.content)||""}function Ug(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=nc(n);r&&t.set(n.id,r)}return t}function Wg(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=nc(o);s&&t.set(r.checkpointId,s)}}return t}function Or(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function ur(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Vg(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 rc(e){const t=Or(e);if(t)return Or(t.configurable)??t}function Vn(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((s,i)=>qg(s,i)).filter(s=>!!s)].sort((s,i)=>oc(i.createdAt)-oc(s.createdAt)),o=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:o,checkpoints:r,interrupt:(o==null?void 0:o.interrupt)??null}}function qg(e,t){var w;if(!e)return null;const r=(Array.isArray((w=e.values)==null?void 0:w.messages)?e.values.messages:[]).filter(C=>!!(C&&typeof C=="object"&&typeof C.role=="string")),o=Or(e.metadata)??{},s=rc(e.config),i=Or(e.parent_config??e.parentConfig),a=rc(i),c=ur(s,["checkpoint_id","checkpointId"]),u=ur(s,["checkpoint_ns","checkpointNs"]),d=ur(a,["checkpoint_id","checkpointId"]),f=ur(a,["checkpoint_id","checkpointId"])??null,h=ur(a,["checkpoint_ns","checkpointNs"])??null,p=Or(e.config),v=Array.isArray(e.tasks)?e.tasks.map(C=>({...C})):e.tasks??null,b=Array.isArray(e.next)?[...e.next]:e.next??null,g=typeof e.created_at=="string"&&e.created_at.trim()?e.created_at:typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),x={...o,step:Vg(o,["step"])??0,source:ur(o,["source"])??null};return{checkpointId:c??null,checkpointNs:u??null,createdAt:g,parentId:d??null,messages:r,nextCursor:f,nextCursorNs:h,interrupt:Kg(r,t),metadata:x,config:p??null,parentConfig:i??null,next:b,tasks:v}}function Kg(e,t){return Gg(e,t)}function Gg(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 oc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Yg(e){return y.useMemo(()=>e.map((t,n)=>{var r;return{id:t.checkpointId??`cp-${n}`,label:t.metadata.source==="input"?"User Input":`Step ${t.metadata.step}`,messageId:((r=t.messages[t.messages.length-1])==null?void 0:r.id)??null,step:t.metadata.step,source:t.metadata.source,createdAt:t.createdAt??null,next:t.nextCursor??void 0,parentConfig:t.parentConfig??null}}),[e])}function Xg({api:e,seed:t,prepend:n,onError:r,currentThreadId:o,initialThreadId:s=null,initialCheckpointId:i=null,initialCheckpointNs:a=null,autoLoadInitial:c=!0,isStreaming:u,getMessages:d}){const[f,h]=y.useState(null),v=y.useMemo(()=>Vn(f),[f]).checkpoints,b=Yg(v),[g,x]=y.useState(!1),[w,C]=y.useState(null),[T,S]=y.useState(!1),[k,E]=y.useState(!1),[j,O]=y.useState(!1),[F,H]=y.useState(null),U=y.useRef(o),q=y.useRef(null),P=y.useRef(null),z=y.useRef(null),I=y.useRef(null),D=y.useRef(!1),R=y.useRef(null),A=y.useRef(new Map);y.useEffect(()=>{U.current=o},[o]);const B=y.useCallback(async G=>{var he,fe;if(!G.threadId)return;const X=G.threadId;(he=G.onStart)==null||he.call(G),G.setLoading(!0);try{await G.action(X)}catch(Z){if(U.current===X){const le=String(Z);(fe=G.handleError)==null||fe.call(G,le),r==null||r(le)}throw Z}finally{G.setLoading(!1)}},[r]),W=y.useCallback(async(G,X)=>{if(!G)return;const he=`${G}:${X??"latest"}`,fe=A.current.get(he);if(fe)return fe;const Z=B({threadId:G,setLoading:S,onStart:()=>H(null),handleError:le=>H(le),action:async le=>{const be=await e.getStateHistory({threadId:le,checkpointId:X??void 0});if(U.current!==le){console.log(`[useThreadHistoryState] Thread changed during load (was ${le}, now ${U.current}), discarding stale data`);return}const{checkpoints:_e}=Vn(be),Ne=_e.find($e=>$e.messages&&$e.messages.length>0)??(X?_e.find($e=>$e.checkpointId===X):null)??_e[0];t((Ne==null?void 0:Ne.messages)??[],{checkpointId:(Ne==null?void 0:Ne.checkpointId)??null,checkpointNs:(Ne==null?void 0:Ne.checkpointNs)??null}),h(be),x(!!(Ne!=null&&Ne.nextCursor)),C((Ne==null?void 0:Ne.nextCursor)??null)}});A.current.set(he,Z);try{await Z}finally{A.current.delete(he)}return U.current===G&&(R.current=he),Z},[e,t,B]),_=y.useCallback(async(G,X)=>{I.current=G;try{await W(G,X)}finally{I.current===G&&(I.current=null)}},[W]),V=y.useCallback(G=>{P.current=G},[]),ie=y.useCallback(G=>{z.current=G},[]),Q=y.useCallback(G=>{const X=G.threadId??U.current;if(!X||U.current&&U.current!==X)return;const{checkpoints:he}=Vn(G);if(!he.length)return;const fe=he.find(Z=>Z.messages&&Z.messages.length>0)??he.find(Z=>!!Z.checkpointId)??he[0];t((fe==null?void 0:fe.messages)??[],{checkpointId:(fe==null?void 0:fe.checkpointId)??null,checkpointNs:(fe==null?void 0:fe.checkpointNs)??null}),h(G),x(!!(fe!=null&&fe.nextCursor)),C((fe==null?void 0:fe.nextCursor)??null),R.current=`${X}:latest`,P.current=null,z.current=null},[t]),oe=y.useCallback(async(G,X)=>{const he=U.current;await B({threadId:he,setLoading:O,action:async fe=>{const Z=await e.getStateHistory({threadId:fe,checkpointId:G,checkpointNs:X??void 0});if(U.current!==fe){console.log(`[useThreadHistoryState] Thread changed during checkpoint navigation (was ${fe}, now ${U.current}), discarding stale data`);return}const{checkpoints:le}=Vn(Z),be=le.find(_e=>_e.checkpointId===G&&(X?_e.checkpointNs===X:!0));if(!be){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:G,checkpointNs:X});return}h(Z),t(be.messages??[],{checkpointId:be.checkpointId??null,checkpointNs:be.checkpointNs??null})}}).catch(()=>{})},[e,t,B]),Y=y.useCallback((G,X)=>{t(d(),{checkpointId:G??null,checkpointNs:X??null})},[d,t]),L=y.useCallback(async()=>{U.current&&await _(U.current)},[_]),K=y.useCallback(async()=>{const G=U.current;!G||!w||await B({threadId:G,setLoading:E,action:async X=>{const he=await e.getStateHistory({threadId:X,checkpointId:w});if(U.current!==X)return;const{checkpoints:fe}=Vn(he);if(fe.length>0){const Z=fe[fe.length-1];n((Z==null?void 0:Z.messages)??[]),x(!!(Z!=null&&Z.nextCursor)),C((Z==null?void 0:Z.nextCursor)??null)}}}).catch(()=>{})},[e,w,r,n,B]);y.useEffect(()=>{if(!c||!o||T||u)return;if(P.current===o){P.current=null,q.current=o;return}if(z.current===o){q.current=o;return}if(I.current===o){I.current=null,q.current=o;return}if(q.current===o)return;q.current=o;const G=!D.current&&!!i&&o===s;let X;G&&i?(X=i,D.current=!0,console.log("[useThreadHistoryState] Loading thread with checkpoint:",X,a?`(ns: ${a})`:"")):console.log("[useThreadHistoryState] Loading thread with latest checkpoint");const he=`${o}:${X??"latest"}`;R.current!==he&&_(o,X)},[c,o,i,a,s,T,u,_]);const te=y.useCallback(()=>{h(null),x(!1),C(null),S(!1),E(!1),O(!1),H(null),P.current=null,z.current=null,q.current=null,R.current=null,I.current=null},[]);return{threadCheckpoints:v,threadTimeline:b,isLoadingThread:T,isHistoryLoading:k,isLoadingCheckpoint:j,threadStateError:F,hasMoreHistory:g,loadThread:_,navigateToCheckpoint:oe,loadOlderMessages:K,setCurrentCheckpointId:Y,returnToLatest:L,handleStateHistoryEvent:Q,markSkipNextLoad:V,markStreamPendingThread:ie,resetHistoryState:te}}const Jg=["detail","message","error","description","title"];function Mo(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=Mo(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of Jg){const r=Mo(t[n]);if(r)return r}if("errors"in t){const n=Mo(t.errors);if(n)return n}}return null}function Zg(e){if(!e)return"Request failed";const t=e.response,n=Mo(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function Qg({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:o}){const[s,i]=y.useState([]),[a,c]=y.useState(t),[u,d]=y.useState(!1),[f,h]=y.useState(null),[p,v]=y.useState([]),[b,g]=y.useState(!1),[,x]=y.useState(null),[w,C]=y.useState(null),[T,S]=y.useState(!1),k=y.useRef(a),E=y.useRef(new Map);y.useEffect(()=>{k.current=a},[a]);const j=y.useCallback(async()=>{d(!0),h(null);try{const R=await e.listThreads();i(R??[])}catch(R){const A=String(R);h(A),n==null||n(A)}finally{d(!1)}},[e,n]),O=y.useCallback(async()=>{g(!0),x(null);try{const R=await e.listSharedThreads();v(R??[])}catch(R){const A=String(R);x(A),n==null||n(A)}finally{g(!1)}},[e,n]);y.useEffect(()=>{j()},[j]),y.useEffect(()=>{O()},[O]),y.useEffect(()=>{r==null||r(a)},[a,r]);const F=y.useCallback(async R=>{try{const A=await e.createThread(R);return c(A.threadId),await j(),A.threadId}catch(A){const B=String(A);return n==null||n(B),null}},[e,n,j]),H=y.useCallback(async R=>{const A=s;i(W=>W.filter(_=>_.threadId!==R));const B=new AbortController;E.current.set(R,B);try{await e.deleteThread(R),k.current===R&&(c(null),o==null||o())}catch(W){i(A);const _=String(W);n==null||n(_)}finally{E.current.delete(R)}},[e,o,n,s]),U=y.useCallback(async(R,A)=>{try{await e.updateThread(R,A),await j()}catch(B){n==null||n(String(B))}},[e,n,j]),q=y.useCallback(async(R,A)=>{S(!0),C("Sharing thread…");try{await e.shareThread(R,A),await O(),C("Shared successfully")}catch(B){const W=Zg(B);throw n==null||n(W),C(`Failed to share: ${W}`),new Error(W)}finally{S(!1)}},[e,n,O]),P=y.useCallback(async(R,A)=>{try{await e.unshareThread(R,A),await O()}catch(B){const W=String(B);throw n==null||n(W),B}},[e,n,O]),z=y.useMemo(()=>({createThread:F,deleteThread:H,renameThread:U,refreshThreads:j,refreshSharedThreads:O,shareThread:q,unshareThread:P}),[F,H,U,j,O,q,P]),I=y.useCallback(R=>{if(!(R!=null&&R.threadId))return;const A={threadId:R.threadId,title:R.title||`Thread ${R.threadId.slice(0,8)}`,createdAt:R.createdAt||new Date().toISOString(),updatedAt:R.updatedAt||new Date().toISOString(),messageCount:R.messageCount??1};i(B=>{let W=!1;const _=B.map(V=>V.threadId===A.threadId?(W=!0,console.debug("[useThreadsState] thread_info: updating existing thread",A.threadId),{...V,title:A.title??V.title,updatedAt:A.updatedAt??V.updatedAt,messageCount:A.messageCount??V.messageCount}):V);return W?_:(console.debug("[useThreadsState] thread_info: adding thread to list",A.threadId),[A,...B])})},[]),D=y.useCallback(()=>C(null),[]);return{threads:s,currentThreadId:a,currentThreadIdRef:k,setCurrentThreadId:c,isLoadingThreads:u,threadsError:f,sharedThreads:p,isLoadingSharedThreads:b,actions:z,addThreadFromEvent:I,shareInFlight:T,shareStatus:w,clearShareStatus:D}}function mi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content??[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content??[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function sc(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function ex(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 ic(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function ac(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function tx(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??ac(e);let c="",u=e.slice();if(s){const f=nx(a,s);if(f===""?c="":f===s?c=s:c=f,c){const h=u[u.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",v={...h,text:p+c};u=[...u.slice(0,u.length-1),v]}else u=[...u,{type:"text",text:c}];o.lastText=a+c}else o.lastText=a}i.length&&(u=[...u,...i]);const d=!!(c||i.length);return{newParts:u,newMeta:o,changed:d}}function lc(e){return e.replace(/\s+/g," ").trim()}function nx(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=lc(e),o=lc(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 rx(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 sc(e,r,s)}return e}function ox(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const sx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null};function ix(e,t){var n;switch(t.type){case"reset":return{messages:mi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,pendingInterrupt:null,messagesStreamMeta:{}};case"user_message":{const{message:r,editingMessageId:o}=t.payload;if(o){const s=e.messages.findIndex(i=>i.id===o);if(s>=0){const i=e.messages.slice(0,s);return{...e,messages:[...i,r]}}}return{...e,messages:[...e.messages,r]}}case"seed":{const r=mi(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=mi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(a=>a.id)),s=r.filter(a=>!o.has(a.id));if(!s.length)return e;const i=[...s,...e.messages];return{...e,messages:i}}case"event":return uc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>uc(o,s),e):e}default:return e}}function cc(e=[]){const[t,n]=y.useReducer(ix,{...sx,messages:e}),r=y.useRef([]),o=y.useRef(null),s=y.useRef(null),i=y.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=y.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]),c=y.useCallback(d=>{r.current.push(d),a()},[a]);y.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const u=y.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,f)=>n({type:"user_message",payload:{message:d,editingMessageId:f}}),onEvent:c}),[c]);return{state:t,dispatch:n,...u}}function uc(e,t){var n,r,o;if(t.type==="message.start"&&t.role==="assistant"){const s=t.id,i=ox(t.model);if(e.messages.some(u=>u.id===s)){const u=e.messagesStreamMeta??{},d={...u,[s]:u[s]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:s,messagesStreamMeta:d}}const c={id:s,role:"assistant",name:i||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:s,messages:[...e.messages,c]}}if(t.type==="message.delta"){const s=e.assemblingId??ic(e.messages);if(!s)return e;const i=e.messages,a=i.findIndex(S=>S.id===s&&S.role==="assistant");if(a===-1)return e;const c=i[a],u=e.messagesStreamMeta,d=u??{},f=d[s],h=f??{lastSeq:null,lastText:ac(c.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof h.lastSeq=="number"&&p<=h.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:h.lastSeq}),e;const{newParts:v,newMeta:b,changed:g}=tx(c.content,t.delta,h,p);if(!g)return e;const x={...c,content:v},w=sc(i,a,x),C=!f||f.lastSeq!==b.lastSeq||f.lastText!==b.lastText,T=C?{...d,[s]:b}:u;return C?{...e,messages:w,messagesStreamMeta:T}:{...e,messages:w}}if(t.type==="message.end"){const s=e.assemblingId??ic(e.messages);if(!s)return{...e,assemblingId:null};const i=e.messages,a=i.findIndex(c=>c.id===s&&c.role==="assistant");if(a>=0){const c=i[a];if(!((n=c.content)==null?void 0:n.some(d=>{var f;return(d==null?void 0:d.type)==="text"&&((f=d.text)==null?void 0:f.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(f=>f==null?void 0:f.type),contentPreview:(o=c.content)==null?void 0:o.map(f=>(f==null?void 0:f.type)==="text"?String(f.text).slice(0,100):f==null?void 0:f.type)});const d=[...i.slice(0,a),...i.slice(a+1)];return{...e,assemblingId:null,messages:d}}}return e}if(t.type==="checkpoint"){const s=t.checkpointNs??e.lastCheckpointNs??null,i=rx(e.messages,t.checkpointId,s);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:s,messages:i}}if(t.type==="error"){const s={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,s]}}if(t.type==="state_history"){const s=Vn(t),i=s.interrupt,a=s.latest,c=i===null?ex(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:i,lastCheckpointId:(a==null?void 0:a.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(a==null?void 0:a.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function dc(e={}){const t=y.useMemo(()=>wn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=y.useState(e.token??null),s=y.useRef(e.headers??{}),i=e.credentials??"include",[a,c]=y.useState(!1),[u,d]=y.useState(null),[f,h]=y.useState(""),[p,v]=y.useState(null),[b,g]=y.useState(0),[x,w]=y.useState(!1),C=y.useRef(null),T=y.useRef(!0),S=y.useRef(0),k=y.useRef(null),E=y.useRef(null),j=y.useRef(null),O=y.useRef(null),F=y.useCallback(P=>{o(P)},[]),H=y.useCallback(()=>{h(""),v(null),d(null),E.current=null,j.current=null,O.current=null},[]),U=y.useCallback(()=>{var P;console.debug("[use-chat] stop() invoked - aborting stream"),(P=C.current)==null||P.abort(),C.current=null,k.current=null,c(!1),w(!1),S.current=0,g(0)},[]),q=y.useCallback((P,z,I)=>{C.current&&(C.current.abort(),C.current=null),c(!0),d(null),e.autoAppendAssistant!==!1&&h(""),v(null),E.current=null,j.current=null,O.current=null;const D=new AbortController;C.current=D;let R=null,A=null,B=!1;return k.current={threadId:P.threadId??null,headers:{}},(async()=>{var _,V,ie,Q,oe,Y,L,K,te,G,X,he,fe,Z,le,be,_e,Ne;const W=$e=>{var Xe;try{const nt=JSON.parse(JSON.stringify($e));return(Xe=nt==null?void 0:nt.payload)!=null&&Xe.files_info&&Array.isArray(nt.payload.files_info)&&(nt.payload.files_info=nt.payload.files_info.map(Ve=>({...Ve,data:Ve!=null&&Ve.data?`<base64 ${String(Ve.data).length} chars>`:Ve==null?void 0:Ve.data}))),nt}catch{return $e}};try{let $e={};try{if(r)$e={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const qe=window.__AUTH_TOKEN__,dt=((_=window.localStorage)==null?void 0:_.getItem("authToken"))||null;let bt=null;try{const Ct=(V=window.localStorage)==null?void 0:V.getItem("chat-settings");Ct&&(bt=((ie=JSON.parse(Ct))==null?void 0:ie.apiKey)||null)}catch{}const Ue=qe||dt||bt||null;Ue&&($e={Authorization:`Bearer ${Ue}`})}}catch{}console.debug("[use-chat] POST",t+n,W(P));let Xe={};if(typeof window<"u")try{const Je=(Q=window.localStorage)==null?void 0:Q.getItem("authSessionId");Je&&(Xe={"X-Session-Id":Je})}catch{}const nt={...$e,...Xe,...s.current},Ve={"Content-Type":"application/json",Accept:"text/event-stream",...nt},Ke=await fetch(t+n,{method:"POST",headers:Ve,body:JSON.stringify(P),signal:D.signal,credentials:i});if(k.current&&(k.current.headers=nt),!Ke.ok||!Ke.body){const Je=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,Je==null?void 0:Je.slice(0,500));const qe=`stream ${Ke.status}${Je?": "+Je:""}`;throw(oe=I==null?void 0:I.onConnectionError)==null||oe.call(I,qe),B=!0,R="error",A=qe,new Error(qe)}w(!0);const ot=Ke.body.getReader(),kt=new TextDecoder;let lt="",Te=[];S.current=0,g(0);let Oe=0,at=null;const ht=()=>{if(Te.length){const Je=Te.join("");Te=[],T.current&&h(qe=>qe+Je)}at=null},Tt=()=>{typeof window<"u"&&at==null&&(at=requestAnimationFrame(ht))};let St=Date.now();const Le=setInterval(()=>{var Je;if(Date.now()-St>18e5){const qe="Stream idle timeout";d(qe),R="error",A=qe,D.abort(),(Je=I==null?void 0:I.onError)==null||Je.call(I,qe)}},5e3),Ht=1024*1024;try{const Je=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),qe=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),dt=Je??null,bt=String(qe??"").toLowerCase()==="true";for(k.current&&!k.current.threadId&&(k.current={...k.current,threadId:dt}),(Y=I==null?void 0:I.onOpen)==null||Y.call(I,{threadId:dt,created:bt});;){const{value:Ue,done:Ct}=await ot.read();if(Ct)break;lt+=kt.decode(Ue,{stream:!0}),lt.length>Ht&&(lt="",console.warn("Stream buffer reset: exceeded 1MB"));let M;for(;(M=lt.indexOf(`
|
|
35
|
+
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Un(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&No.assertOptions(r,{silentJSONParsing:un.transitional(un.boolean),forcedJSONParsing:un.transitional(un.boolean),clarifyTimeoutError:un.transitional(un.boolean)},!1),o!=null&&($.isFunction(o)?n.paramsSerializer={serialize:o}:No.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),No.assertOptions(n,{baseUrl:un.spelling("baseURL"),withXsrfToken:un.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&$.merge(s.common,s[n.method]);s&&$.forEach(["delete","get","head","post","put","patch","common"],v=>{delete s[v]}),n.headers=$t.concat(i,s);const a=[];let c=!0;this.interceptors.request.forEach(function(b){typeof b.runWhen=="function"&&b.runWhen(n)===!1||(c=c&&b.synchronous,a.unshift(b.fulfilled,b.rejected))});const u=[];this.interceptors.response.forEach(function(b){u.push(b.fulfilled,b.rejected)});let d,f=0,h;if(!c){const v=[Wl.bind(this),void 0];for(v.unshift(...a),v.push(...u),h=v.length,d=Promise.resolve(n);f<h;)d=d.then(v[f++],v[f++]);return d}h=a.length;let p=n;for(;f<h;){const v=a[f++],b=a[f++];try{p=v(p)}catch(g){b.call(this,g);break}}try{d=Wl.call(this,p)}catch(v){return Promise.reject(v)}for(f=0,h=u.length;f<h;)d=d.then(u[f++],u[f++]);return d}getUri(t){t=Un(this.defaults,t);const n=Rl(t.baseURL,t.url,t.allowAbsoluteUrls);return kl(n,t.params,t.paramsSerializer)}};$.forEach(["delete","get","head","options"],function(t){Wn.prototype[t]=function(n,r){return this.request(Un(r||{},{method:t,url:n,data:(r||{}).data}))}}),$.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Un(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Wn.prototype[t]=n(),Wn.prototype[t+"Form"]=n(!0)});let Pg=class um{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 cr(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 um(function(o){t=o}),cancel:t}}};function Og(e){return function(n){return e.apply(null,n)}}function Dg(e){return $.isObject(e)&&e.isAxiosError===!0}const di={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(di).forEach(([e,t])=>{di[t]=e});function Kl(e){const t=new Wn(e),n=cl(Wn.prototype.request,t);return $.extend(n,Wn.prototype,t,{allOwnKeys:!0}),$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Kl(Un(e,o))},n}const xt=Kl(Rr);xt.Axios=Wn,xt.CanceledError=cr,xt.CancelToken=Pg,xt.isCancel=Al,xt.VERSION=Vl,xt.toFormData=Co,xt.AxiosError=Me,xt.Cancel=xt.CanceledError,xt.all=function(t){return Promise.all(t)},xt.spread=Og,xt.isAxiosError=Dg,xt.mergeConfig=Un,xt.AxiosHeaders=$t,xt.formToJSON=e=>Il($.isHTMLForm(e)?new FormData(e):e),xt.getAdapter=Ul.getAdapter,xt.HttpStatusCode=di,xt.default=xt;const{Axios:fT,AxiosError:hT,CanceledError:pT,isCancel:mT,CancelToken:gT,VERSION:xT,all:vT,Cancel:bT,isAxiosError:wT,spread:yT,toFormData:ST,AxiosHeaders:CT,HttpStatusCode:kT,formToJSON:TT,getAdapter:ET,mergeConfig:IT}=xt,Gl=typeof window<"u"?window.__API_BASE_URL__:void 0,Yl=Gl?wn(Gl):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 Ao=null;const fi=new Set;function Xl(){return Ao}function jo(e){Ao=e,fi.forEach(t=>t(e))}function Jl(e){return fi.add(e),()=>fi.delete(e)}const Lg=3e4,$g=9e4,Kt=xt.create({...Yl?{baseURL:Yl}:{},timeout:Lg,withCredentials:!0});Kt.interceptors.request.use(e=>(Ao&&(e.headers.Authorization=`Bearer ${Ao}`),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),jo(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Gt(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function _o(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 Zl(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 hi(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Ft(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Ql{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&&jo(t.authToken)}getAuthToken(){return Xl()}setAuthToken(t){jo(t)}onTokenChange(t){return Jl(t)}async listThreads(){const t=await Gt("/threads"),n=Ft(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await Gt("/threads/shared"),n=Ft(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await _o("/threads",t?{title:t}:void 0);return Ft(r)}async updateThread(t,n){const r=await Zl(`/threads/${t}`,{title:n});return Ft(r)}async deleteThread(t){const n=await hi(`/threads/${t}`);return Ft(n)}async shareThread(t,n){const r=await _o(`/threads/${t}/share`,{shared_with_user_id:n});return Ft(r)}async threadInfo(t){const n=await Gt(`/threads/${t}/info`);return Ft(n)}async listAgents(){const t=await Gt("/agents"),n=Ft(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Gt(`/agents/${t}`);return Ft(n)}async getAgentSchema(t){const n=await Gt(`/agents/${t}/schema`);return Ft(n)}async getState(t){const n=await Gt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Ft(n)}async getStateHistory(t){const n=await Gt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:$g});return Ft(n)}async cancelRun(t){const n=await _o("/runs/cancel",{threadId:t});return Ft(n)}async unshareThread(t,n){const r=await hi(`/threads/${t}/share/${n}`);return Ft(r)}}const Tn=new Ql,ec=y.createContext(null);function Fg({children:e,apiConfig:t}){const n=Tn;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 l.jsx(ec.Provider,{value:r,children:e})}function pi(){const e=y.useContext(ec);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Bg(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 c=0;c<a;c++)i+=String.fromCharCode(s[c]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function zg(e=[]){const t=[],n=[];for(const r of e)try{const o=await Bg(r);n.push({filename:r.name,data:o,mime_type:r.type||"application/octet-stream"})}catch{}return{contentParts:t,filesInfo:n}}const tc=120;function Hg(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>tc?`${n.slice(0,tc-3)}…`:n:""}function nc(e){return Hg(e.content)||""}function Ug(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=nc(n);r&&t.set(n.id,r)}return t}function Wg(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=nc(o);s&&t.set(r.checkpointId,s)}}return t}function Or(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function ur(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Vg(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 rc(e){const t=Or(e);if(t)return Or(t.configurable)??t}function Vn(e){const r=[...(Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[]).map((s,i)=>qg(s,i)).filter(s=>!!s)].sort((s,i)=>oc(i.createdAt)-oc(s.createdAt)),o=r[0]??null;return{threadId:(e==null?void 0:e.threadId)??"",latest:o,checkpoints:r,interrupt:(o==null?void 0:o.interrupt)??null}}function qg(e,t){var w;if(!e)return null;const r=(Array.isArray((w=e.values)==null?void 0:w.messages)?e.values.messages:[]).filter(C=>!!(C&&typeof C=="object"&&typeof C.role=="string")),o=Or(e.metadata)??{},s=rc(e.config),i=Or(e.parent_config??e.parentConfig),a=rc(i),c=ur(s,["checkpoint_id","checkpointId"]),u=ur(s,["checkpoint_ns","checkpointNs"]),d=ur(a,["checkpoint_id","checkpointId"]),f=ur(a,["checkpoint_id","checkpointId"])??null,h=ur(a,["checkpoint_ns","checkpointNs"])??null,p=Or(e.config),v=Array.isArray(e.tasks)?e.tasks.map(C=>({...C})):e.tasks??null,b=Array.isArray(e.next)?[...e.next]:e.next??null,g=typeof e.created_at=="string"&&e.created_at.trim()?e.created_at:typeof e.createdAt=="string"&&e.createdAt.trim()?e.createdAt:new Date(Date.now()-t).toISOString(),x={...o,step:Vg(o,["step"])??0,source:ur(o,["source"])??null};return{checkpointId:c??null,checkpointNs:u??null,createdAt:g,parentId:d??null,messages:r,nextCursor:f,nextCursorNs:h,interrupt:Kg(r,t),metadata:x,config:p??null,parentConfig:i??null,next:b,tasks:v}}function Kg(e,t){return Gg(e,t)}function Gg(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 oc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Yg(e){return y.useMemo(()=>e.map((t,n)=>{var r;return{id:t.checkpointId??`cp-${n}`,label:t.metadata.source==="input"?"User Input":`Step ${t.metadata.step}`,messageId:((r=t.messages[t.messages.length-1])==null?void 0:r.id)??null,step:t.metadata.step,source:t.metadata.source,createdAt:t.createdAt??null,next:t.next&&t.next.length>0?String(t.next[0]):null,parentConfig:t.parentConfig??null}}),[e])}function Xg({api:e,seed:t,prepend:n,onError:r,currentThreadId:o,initialThreadId:s=null,initialCheckpointId:i=null,initialCheckpointNs:a=null,autoLoadInitial:c=!0,isStreaming:u,getMessages:d}){const[f,h]=y.useState(null),v=y.useMemo(()=>Vn(f),[f]).checkpoints,b=Yg(v),[g,x]=y.useState(!1),[w,C]=y.useState(null),[T,S]=y.useState(!1),[k,E]=y.useState(!1),[j,O]=y.useState(!1),[F,H]=y.useState(null),U=y.useRef(o),q=y.useRef(null),P=y.useRef(null),z=y.useRef(null),I=y.useRef(null),D=y.useRef(!1),R=y.useRef(null),A=y.useRef(new Map);y.useEffect(()=>{U.current=o},[o]);const B=y.useCallback(async G=>{var he,fe;if(!G.threadId)return;const X=G.threadId;(he=G.onStart)==null||he.call(G),G.setLoading(!0);try{await G.action(X)}catch(Z){if(U.current===X){const le=String(Z);(fe=G.handleError)==null||fe.call(G,le),r==null||r(le)}throw Z}finally{G.setLoading(!1)}},[r]),W=y.useCallback(async(G,X)=>{if(!G)return;const he=`${G}:${X??"latest"}`,fe=A.current.get(he);if(fe)return fe;const Z=B({threadId:G,setLoading:S,onStart:()=>H(null),handleError:le=>H(le),action:async le=>{const be=await e.getStateHistory({threadId:le,checkpointId:X??void 0});if(U.current!==le){console.log(`[useThreadHistoryState] Thread changed during load (was ${le}, now ${U.current}), discarding stale data`);return}const{checkpoints:_e}=Vn(be),Ne=_e.find($e=>$e.messages&&$e.messages.length>0)??(X?_e.find($e=>$e.checkpointId===X):null)??_e[0];t((Ne==null?void 0:Ne.messages)??[],{checkpointId:(Ne==null?void 0:Ne.checkpointId)??null,checkpointNs:(Ne==null?void 0:Ne.checkpointNs)??null}),h(be),x(!!(Ne!=null&&Ne.nextCursor)),C((Ne==null?void 0:Ne.nextCursor)??null)}});A.current.set(he,Z);try{await Z}finally{A.current.delete(he)}return U.current===G&&(R.current=he),Z},[e,t,B]),_=y.useCallback(async(G,X)=>{I.current=G;try{await W(G,X)}finally{I.current===G&&(I.current=null)}},[W]),V=y.useCallback(G=>{P.current=G},[]),ie=y.useCallback(G=>{z.current=G},[]),Q=y.useCallback(G=>{const X=G.threadId??U.current;if(!X||U.current&&U.current!==X)return;const{checkpoints:he}=Vn(G);if(!he.length)return;const fe=he.find(Z=>Z.messages&&Z.messages.length>0)??he.find(Z=>!!Z.checkpointId)??he[0];t((fe==null?void 0:fe.messages)??[],{checkpointId:(fe==null?void 0:fe.checkpointId)??null,checkpointNs:(fe==null?void 0:fe.checkpointNs)??null}),h(G),x(!!(fe!=null&&fe.nextCursor)),C((fe==null?void 0:fe.nextCursor)??null),R.current=`${X}:latest`,P.current=null,z.current=null},[t]),oe=y.useCallback(async(G,X)=>{const he=U.current;await B({threadId:he,setLoading:O,action:async fe=>{const Z=await e.getStateHistory({threadId:fe,checkpointId:G,checkpointNs:X??void 0});if(U.current!==fe){console.log(`[useThreadHistoryState] Thread changed during checkpoint navigation (was ${fe}, now ${U.current}), discarding stale data`);return}const{checkpoints:le}=Vn(Z),be=le.find(_e=>_e.checkpointId===G&&(X?_e.checkpointNs===X:!0));if(!be){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:G,checkpointNs:X});return}h(Z),t(be.messages??[],{checkpointId:be.checkpointId??null,checkpointNs:be.checkpointNs??null})}}).catch(()=>{})},[e,t,B]),Y=y.useCallback((G,X)=>{t(d(),{checkpointId:G??null,checkpointNs:X??null})},[d,t]),L=y.useCallback(async()=>{U.current&&await _(U.current)},[_]),K=y.useCallback(async()=>{const G=U.current;!G||!w||await B({threadId:G,setLoading:E,action:async X=>{const he=await e.getStateHistory({threadId:X,checkpointId:w});if(U.current!==X)return;const{checkpoints:fe}=Vn(he);if(fe.length>0){const Z=fe[fe.length-1];n((Z==null?void 0:Z.messages)??[]),x(!!(Z!=null&&Z.nextCursor)),C((Z==null?void 0:Z.nextCursor)??null)}}}).catch(()=>{})},[e,w,r,n,B]);y.useEffect(()=>{if(!c||!o||T||u)return;if(P.current===o){P.current=null,q.current=o;return}if(z.current===o){q.current=o;return}if(I.current===o){I.current=null,q.current=o;return}if(q.current===o)return;q.current=o;const G=!D.current&&!!i&&o===s;let X;G&&i?(X=i,D.current=!0,console.log("[useThreadHistoryState] Loading thread with checkpoint:",X,a?`(ns: ${a})`:"")):console.log("[useThreadHistoryState] Loading thread with latest checkpoint");const he=`${o}:${X??"latest"}`;R.current!==he&&_(o,X)},[c,o,i,a,s,T,u,_]);const te=y.useCallback(()=>{h(null),x(!1),C(null),S(!1),E(!1),O(!1),H(null),P.current=null,z.current=null,q.current=null,R.current=null,I.current=null},[]);return{threadCheckpoints:v,threadTimeline:b,isLoadingThread:T,isHistoryLoading:k,isLoadingCheckpoint:j,threadStateError:F,hasMoreHistory:g,loadThread:_,navigateToCheckpoint:oe,loadOlderMessages:K,setCurrentCheckpointId:Y,returnToLatest:L,handleStateHistoryEvent:Q,markSkipNextLoad:V,markStreamPendingThread:ie,resetHistoryState:te}}const Jg=["detail","message","error","description","title"];function Mo(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=Mo(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of Jg){const r=Mo(t[n]);if(r)return r}if("errors"in t){const n=Mo(t.errors);if(n)return n}}return null}function Zg(e){if(!e)return"Request failed";const t=e.response,n=Mo(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function Qg({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:o}){const[s,i]=y.useState([]),[a,c]=y.useState(t),[u,d]=y.useState(!1),[f,h]=y.useState(null),[p,v]=y.useState([]),[b,g]=y.useState(!1),[,x]=y.useState(null),[w,C]=y.useState(null),[T,S]=y.useState(!1),k=y.useRef(a),E=y.useRef(new Map);y.useEffect(()=>{k.current=a},[a]);const j=y.useCallback(async()=>{d(!0),h(null);try{const R=await e.listThreads();i(R??[])}catch(R){const A=String(R);h(A),n==null||n(A)}finally{d(!1)}},[e,n]),O=y.useCallback(async()=>{g(!0),x(null);try{const R=await e.listSharedThreads();v(R??[])}catch(R){const A=String(R);x(A),n==null||n(A)}finally{g(!1)}},[e,n]);y.useEffect(()=>{j()},[j]),y.useEffect(()=>{O()},[O]),y.useEffect(()=>{r==null||r(a)},[a,r]);const F=y.useCallback(async R=>{try{const A=await e.createThread(R);return c(A.threadId),await j(),A.threadId}catch(A){const B=String(A);return n==null||n(B),null}},[e,n,j]),H=y.useCallback(async R=>{const A=s;i(W=>W.filter(_=>_.threadId!==R));const B=new AbortController;E.current.set(R,B);try{await e.deleteThread(R),k.current===R&&(c(null),o==null||o())}catch(W){i(A);const _=String(W);n==null||n(_)}finally{E.current.delete(R)}},[e,o,n,s]),U=y.useCallback(async(R,A)=>{try{await e.updateThread(R,A),await j()}catch(B){n==null||n(String(B))}},[e,n,j]),q=y.useCallback(async(R,A)=>{S(!0),C("Sharing thread…");try{await e.shareThread(R,A),await O(),C("Shared successfully")}catch(B){const W=Zg(B);throw n==null||n(W),C(`Failed to share: ${W}`),new Error(W)}finally{S(!1)}},[e,n,O]),P=y.useCallback(async(R,A)=>{try{await e.unshareThread(R,A),await O()}catch(B){const W=String(B);throw n==null||n(W),B}},[e,n,O]),z=y.useMemo(()=>({createThread:F,deleteThread:H,renameThread:U,refreshThreads:j,refreshSharedThreads:O,shareThread:q,unshareThread:P}),[F,H,U,j,O,q,P]),I=y.useCallback(R=>{if(!(R!=null&&R.threadId))return;const A={threadId:R.threadId,title:R.title||`Thread ${R.threadId.slice(0,8)}`,createdAt:R.createdAt||new Date().toISOString(),updatedAt:R.updatedAt||new Date().toISOString(),messageCount:R.messageCount??1};i(B=>{let W=!1;const _=B.map(V=>V.threadId===A.threadId?(W=!0,console.debug("[useThreadsState] thread_info: updating existing thread",A.threadId),{...V,title:A.title??V.title,updatedAt:A.updatedAt??V.updatedAt,messageCount:A.messageCount??V.messageCount}):V);return W?_:(console.debug("[useThreadsState] thread_info: adding thread to list",A.threadId),[A,...B])})},[]),D=y.useCallback(()=>C(null),[]);return{threads:s,currentThreadId:a,currentThreadIdRef:k,setCurrentThreadId:c,isLoadingThreads:u,threadsError:f,sharedThreads:p,isLoadingSharedThreads:b,actions:z,addThreadFromEvent:I,shareInFlight:T,shareStatus:w,clearShareStatus:D}}function mi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content??[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content??[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function sc(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function ex(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 ic(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function ac(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function tx(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??ac(e);let c="",u=e.slice();if(s){const f=nx(a,s);if(f===""?c="":f===s?c=s:c=f,c){const h=u[u.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",v={...h,text:p+c};u=[...u.slice(0,u.length-1),v]}else u=[...u,{type:"text",text:c}];o.lastText=a+c}else o.lastText=a}i.length&&(u=[...u,...i]);const d=!!(c||i.length);return{newParts:u,newMeta:o,changed:d}}function lc(e){return e.replace(/\s+/g," ").trim()}function nx(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=lc(e),o=lc(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 rx(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 sc(e,r,s)}return e}function ox(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const sx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null};function ix(e,t){var n;switch(t.type){case"reset":return{messages:mi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,pendingInterrupt:null,messagesStreamMeta:{}};case"user_message":{const{message:r,editingMessageId:o}=t.payload;if(o){const s=e.messages.findIndex(i=>i.id===o);if(s>=0){const i=e.messages.slice(0,s);return{...e,messages:[...i,r]}}}return{...e,messages:[...e.messages,r]}}case"seed":{const r=mi(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=mi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(a=>a.id)),s=r.filter(a=>!o.has(a.id));if(!s.length)return e;const i=[...s,...e.messages];return{...e,messages:i}}case"event":return uc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>uc(o,s),e):e}default:return e}}function cc(e=[]){const[t,n]=y.useReducer(ix,{...sx,messages:e}),r=y.useRef([]),o=y.useRef(null),s=y.useRef(null),i=y.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=y.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]),c=y.useCallback(d=>{r.current.push(d),a()},[a]);y.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const u=y.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,f)=>n({type:"user_message",payload:{message:d,editingMessageId:f}}),onEvent:c}),[c]);return{state:t,dispatch:n,...u}}function uc(e,t){var n,r,o;if(t.type==="message.start"&&t.role==="assistant"){const s=t.id,i=ox(t.model);if(e.messages.some(u=>u.id===s)){const u=e.messagesStreamMeta??{},d={...u,[s]:u[s]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:s,messagesStreamMeta:d}}const c={id:s,role:"assistant",name:i||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:s,messages:[...e.messages,c]}}if(t.type==="message.delta"){const s=e.assemblingId??ic(e.messages);if(!s)return e;const i=e.messages,a=i.findIndex(S=>S.id===s&&S.role==="assistant");if(a===-1)return e;const c=i[a],u=e.messagesStreamMeta,d=u??{},f=d[s],h=f??{lastSeq:null,lastText:ac(c.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof h.lastSeq=="number"&&p<=h.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:h.lastSeq}),e;const{newParts:v,newMeta:b,changed:g}=tx(c.content,t.delta,h,p);if(!g)return e;const x={...c,content:v},w=sc(i,a,x),C=!f||f.lastSeq!==b.lastSeq||f.lastText!==b.lastText,T=C?{...d,[s]:b}:u;return C?{...e,messages:w,messagesStreamMeta:T}:{...e,messages:w}}if(t.type==="message.end"){const s=e.assemblingId??ic(e.messages);if(!s)return{...e,assemblingId:null};const i=e.messages,a=i.findIndex(c=>c.id===s&&c.role==="assistant");if(a>=0){const c=i[a];if(!((n=c.content)==null?void 0:n.some(d=>{var f;return(d==null?void 0:d.type)==="text"&&((f=d.text)==null?void 0:f.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(f=>f==null?void 0:f.type),contentPreview:(o=c.content)==null?void 0:o.map(f=>(f==null?void 0:f.type)==="text"?String(f.text).slice(0,100):f==null?void 0:f.type)});const d=[...i.slice(0,a),...i.slice(a+1)];return{...e,assemblingId:null,messages:d}}}return e}if(t.type==="checkpoint"){const s=t.checkpointNs??e.lastCheckpointNs??null,i=rx(e.messages,t.checkpointId,s);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:s,messages:i}}if(t.type==="error"){const s={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,s]}}if(t.type==="state_history"){const s=Vn(t),i=s.interrupt,a=s.latest,c=i===null?ex(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:i,lastCheckpointId:(a==null?void 0:a.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(a==null?void 0:a.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function dc(e={}){const t=y.useMemo(()=>wn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=y.useState(e.token??null),s=y.useRef(e.headers??{}),i=e.credentials??"include",[a,c]=y.useState(!1),[u,d]=y.useState(null),[f,h]=y.useState(""),[p,v]=y.useState(null),[b,g]=y.useState(0),[x,w]=y.useState(!1),C=y.useRef(null),T=y.useRef(!0),S=y.useRef(0),k=y.useRef(null),E=y.useRef(null),j=y.useRef(null),O=y.useRef(null),F=y.useCallback(P=>{o(P)},[]),H=y.useCallback(()=>{h(""),v(null),d(null),E.current=null,j.current=null,O.current=null},[]),U=y.useCallback(()=>{var P;console.debug("[use-chat] stop() invoked - aborting stream"),(P=C.current)==null||P.abort(),C.current=null,k.current=null,c(!1),w(!1),S.current=0,g(0)},[]),q=y.useCallback((P,z,I)=>{C.current&&(C.current.abort(),C.current=null),c(!0),d(null),e.autoAppendAssistant!==!1&&h(""),v(null),E.current=null,j.current=null,O.current=null;const D=new AbortController;C.current=D;let R=null,A=null,B=!1;return k.current={threadId:P.threadId??null,headers:{}},(async()=>{var _,V,ie,Q,oe,Y,L,K,te,G,X,he,fe,Z,le,be,_e,Ne;const W=$e=>{var Xe;try{const nt=JSON.parse(JSON.stringify($e));return(Xe=nt==null?void 0:nt.payload)!=null&&Xe.files_info&&Array.isArray(nt.payload.files_info)&&(nt.payload.files_info=nt.payload.files_info.map(Ve=>({...Ve,data:Ve!=null&&Ve.data?`<base64 ${String(Ve.data).length} chars>`:Ve==null?void 0:Ve.data}))),nt}catch{return $e}};try{let $e={};try{if(r)$e={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const qe=window.__AUTH_TOKEN__,dt=((_=window.localStorage)==null?void 0:_.getItem("authToken"))||null;let bt=null;try{const Ct=(V=window.localStorage)==null?void 0:V.getItem("chat-settings");Ct&&(bt=((ie=JSON.parse(Ct))==null?void 0:ie.apiKey)||null)}catch{}const Ue=qe||dt||bt||null;Ue&&($e={Authorization:`Bearer ${Ue}`})}}catch{}console.debug("[use-chat] POST",t+n,W(P));let Xe={};if(typeof window<"u")try{const Je=(Q=window.localStorage)==null?void 0:Q.getItem("authSessionId");Je&&(Xe={"X-Session-Id":Je})}catch{}const nt={...$e,...Xe,...s.current},Ve={"Content-Type":"application/json",Accept:"text/event-stream",...nt},Ke=await fetch(t+n,{method:"POST",headers:Ve,body:JSON.stringify(P),signal:D.signal,credentials:i});if(k.current&&(k.current.headers=nt),!Ke.ok||!Ke.body){const Je=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,Je==null?void 0:Je.slice(0,500));const qe=`stream ${Ke.status}${Je?": "+Je:""}`;throw(oe=I==null?void 0:I.onConnectionError)==null||oe.call(I,qe),B=!0,R="error",A=qe,new Error(qe)}w(!0);const ot=Ke.body.getReader(),kt=new TextDecoder;let lt="",Te=[];S.current=0,g(0);let Oe=0,at=null;const ht=()=>{if(Te.length){const Je=Te.join("");Te=[],T.current&&h(qe=>qe+Je)}at=null},Tt=()=>{typeof window<"u"&&at==null&&(at=requestAnimationFrame(ht))};let St=Date.now();const Le=setInterval(()=>{var Je;if(Date.now()-St>18e5){const qe="Stream idle timeout";d(qe),R="error",A=qe,D.abort(),(Je=I==null?void 0:I.onError)==null||Je.call(I,qe)}},5e3),Ht=1024*1024;try{const Je=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),qe=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),dt=Je??null,bt=String(qe??"").toLowerCase()==="true";for(k.current&&!k.current.threadId&&(k.current={...k.current,threadId:dt}),(Y=I==null?void 0:I.onOpen)==null||Y.call(I,{threadId:dt,created:bt});;){const{value:Ue,done:Ct}=await ot.read();if(Ct)break;lt+=kt.decode(Ue,{stream:!0}),lt.length>Ht&&(lt="",console.warn("Stream buffer reset: exceeded 1MB"));let M;for(;(M=lt.indexOf(`
|
|
36
36
|
|
|
37
37
|
`))>=0;){const se=lt.slice(0,M);lt=lt.slice(M+2);const me=lx(se);if(!me)continue;let We;try{We=JSON.parse(me)}catch{console.debug("[use-chat] malformed SSE:",me.slice(0,200));continue}const Pe=ax(We)?We.data:We;St=Date.now();const mt=Pe.seq;if(mt!==void 0){if(mt<=Oe){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:mt,lastProcessedSeq:Oe,type:Pe.type});continue}Oe>0&&mt>Oe+1&&((L=I==null?void 0:I.onGap)==null||L.call(I,{from:Oe,to:mt})),Oe=mt,S.current=mt,g(mt)}if(Pe.type==="checkpoint")E.current=Pe.checkpointId??null,j.current=Pe.checkpointNs??null,v(Pe.checkpointId??null);else if(Pe.type==="state_history"){O.current=Pe;try{const Nt=Vn(Pe).latest;Nt&&(E.current=Nt.checkpointId??null,j.current=Nt.checkpointNs??null,v(Nt.checkpointId??null))}catch(Ze){console.warn("[use-chat] Failed to hydrate state_history payload",Ze)}}try{z==null||z(Pe)}catch(Ze){console.error("[use-chat] Error in onEvent callback:",Ze,"for event:",Pe.type)}if(Pe.type==="message.delta"){const Ze=Pe.delta.filter(Nt=>Nt.type==="text").map(Nt=>Nt.text).join("");Ze&&e.autoAppendAssistant!==!1&&(Te.push(Ze),Tt())}else if(Pe.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(K=I==null?void 0:I.onHeartbeat)==null||K.call(I,Pe)}catch(Ze){console.warn("[use-chat] heartbeat callback failed",Ze)}}else if(at!==null&&cancelAnimationFrame(at),ht(),Pe.type==="checkpoint")v(Pe.checkpointId);else if(Pe.type==="error"){const Ze=Pe;if(d(Ze.message),R="error",A=Ze.message,Ze.error_type==="auth_error"||Ze.code==="TOKEN_EXPIRED"||((te=Ze.message)==null?void 0:te.includes("token"))||((G=Ze.message)==null?void 0:G.includes("401"))||((X=Ze.message)==null?void 0:X.includes("unauthorized"))||((he=Ze.message)==null?void 0:he.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Ze.message);try{(fe=I==null?void 0:I.onAuthError)==null||fe.call(I,Ze.message)}catch(mo){console.warn("[use-chat] onAuthError handler failed",mo)}D.abort()}}}}ht(),R===null&&!D.signal.aborted&&(R="complete")}catch(Je){if(Je.name==="AbortError")R=R??"aborted";else{const qe=Je.message||String(Je);R="error",A=qe,d(qe),(Z=I==null?void 0:I.onError)==null||Z.call(I,qe)}}finally{try{await ot.cancel()}catch{}finally{(le=ot.releaseLock)==null||le.call(ot)}at!==null&&typeof window<"u"&&window.cancelAnimationFrame(at),clearInterval(Le)}}catch($e){if($e.name==="AbortError")R=R??"aborted";else{const Xe=$e.message||String($e);R="error",A=Xe,d(Xe),(be=I==null?void 0:I.onError)==null||be.call(I,Xe),B||((_e=I==null?void 0:I.onConnectionError)==null||_e.call(I,Xe),B=!0)}}finally{const $e=S.current,Xe=E.current,nt=j.current,Ve=O.current,Ke=R??(D.signal.aborted?"aborted":A?"error":"complete");try{(Ne=I==null?void 0:I.onClosed)==null||Ne.call(I,{reason:Ke,lastSeq:$e,lastCheckpointId:Xe,lastCheckpointNs:nt,lastStateHistory:Ve,error:A})}catch(ot){console.warn("[use-chat] onClosed callback failed",ot)}c(!1),w(!1),C.current=null,S.current=0,g(0),k.current=null}})(),{close:()=>D.abort()}},[t,n,r,e.autoAppendAssistant]);return y.useEffect(()=>()=>{var P;T.current=!1,(P=C.current)==null||P.abort()},[]),{isStreaming:a,error:u,assistantText:f,lastCheckpointId:p,lastSeq:b,connected:x,stream:q,stop:U,clear:H,setToken:F}}function ax(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function lx(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
|
`)}const cx=["message.start","message.delta","message.end"],ux=["tool.start","tool.end","tool.progress"],dx=["thread_info","checkpoint"],fx=["error","interrupt","heartbeat","state_history","cancelled"],hx=[...cx,...ux,...dx,...fx],px=new Set(hx);function mx(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return px.has(t)}const fc=200;function gx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:c,onHeartbeat:u,onToolEvent:d}){const f=y.useRef(null),h=y.useRef(null),p=y.useRef(new Map),v=y.useRef(null),b=y.useRef(null),g=y.useCallback(I=>{try{const D=globalThis.structuredClone;if(typeof D=="function")return D(I)}catch{}try{return JSON.parse(JSON.stringify(I))}catch{return I}},[]),x=y.useCallback((I,D)=>{if(!I)return;const R=p.current.get(I)??[],A=g(D),B=R.length>=fc?[...R.slice(R.length-fc+1),A]:[...R,A];p.current.set(I,B)},[g]),w=y.useCallback(I=>{I&&p.current.set(I,[])},[]),C=y.useCallback(I=>{const D=I??h.current;if(!D)return;const R=p.current.get(D);R!=null&&R.length&&R.forEach(A=>{try{n(A)}catch(B){console.error("[useChatStreamingService] Failed to replay buffered event",B)}})},[n]),T=y.useCallback(I=>{h.current=I.threadId,v.current&&(v.current.threadIdGuess=I.threadId),b.current=I,w(I.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",I);try{t(I)}catch(D){console.error("[useChatStreamingService] Error in onThreadInfo handler:",D)}},[w,t]),S=y.useCallback(I=>{try{u==null||u(I)}catch(D){console.error("[useChatStreamingService] Error in onHeartbeat handler:",D)}},[u]),k=y.useCallback(I=>{var A,B,W,_;const D=I;if(D.error_type==="auth_error"||D.code==="TOKEN_EXPIRED"||((A=D.message)==null?void 0:A.includes("token"))||((B=D.message)==null?void 0:B.includes("401"))||((W=D.message)==null?void 0:W.includes("unauthorized"))||((_=D.message)==null?void 0:_.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",D.message);try{c==null||c(D.message)}catch(V){console.warn("[useChatStreamingService] onAuthError handler failed",V)}}},[c]),E=y.useMemo(()=>({thread_info:I=>(T(I),!0),heartbeat:I=>(S(I),!0),error:I=>(k(I),!1)}),[T,S,k]),j=y.useCallback(I=>{var B;const D=I.seq??null;if(D!==null){const W=f.current;if(W!==null){if(D<=W)return;D>W+1&&(s==null||s({from:W,to:D}))}f.current=D}const R=E[I.type];if(R&&R(I))return;const A=I.threadId??(I.type==="state_history"?I.threadId:void 0)??h.current??((B=v.current)==null?void 0:B.threadIdGuess)??null;if(I.type==="state_history"){h.current=A??h.current;try{r==null||r(I)}catch(W){console.error("[useChatStreamingService] onStateHistory handler failed",W)}}if(mx(I)){(I.type==="tool.start"||I.type==="tool.end")&&(d==null||d(I)),I.type==="checkpoint"||I.type==="state_history"?w(A??null):x(A??null,I);try{n(I)}catch(W){console.error("[useChatStreamingService] Error in onMessageEvent handler:",W)}return}try{o==null||o(I)}catch(W){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",W)}},[x,w,n,s,r,o,E]),{stream:O,stop:F,isStreaming:H,error:U,setToken:q}=dc({baseUrl:e,token:void 0}),P=y.useCallback((I,D)=>{f.current=null,b.current=null,h.current=I.threadId??null,v.current={request:I,callbacks:D,manualStop:!1,threadIdGuess:I.threadId??null},O(I,j,{onOpen:D==null?void 0:D.onOpen,onError:R=>{var A;(A=D==null?void 0:D.onError)==null||A.call(D,R)},onGap:(D==null?void 0:D.onGap)??s,onConnectionError:R=>{var A;a==null||a(R),(A=D==null?void 0:D.onConnectionError)==null||A.call(D,R)},onAuthError:R=>{var A;c==null||c(R),(A=D==null?void 0:D.onAuthError)==null||A.call(D,R)},onHeartbeat:R=>{var A;try{u==null||u(R)}catch(B){console.warn("[useChatStreamingService] onHeartbeat handler failed",B)}try{(A=D==null?void 0:D.onHeartbeat)==null||A.call(D,R)}catch(B){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",B)}},onClosed:R=>{var _,V,ie,Q;const A=((_=v.current)==null?void 0:_.manualStop)??!1,B=h.current??((V=v.current)==null?void 0:V.threadIdGuess)??((ie=R.lastStateHistory)==null?void 0:ie.threadId)??null;(R.reason==="complete"||R.reason==="aborted"&&A)&&w(B);const W={...R,threadId:B,threadInfo:b.current,manualStop:A};try{i==null||i(W)}catch(oe){console.warn("[useChatStreamingService] onStreamClosed handler failed",oe)}try{(Q=D==null?void 0:D.onClosed)==null||Q.call(D,W)}catch(oe){console.warn("[useChatStreamingService] downstream onClosed handler failed",oe)}v.current&&(v.current=null)}})},[w,j,c,a,u,s,i,O]),z=y.useCallback(()=>{v.current&&(v.current.manualStop=!0),F()},[F]);return y.useMemo(()=>({startStream:P,stop:z,isStreaming:H,error:U,setAuthToken:q,replayBufferedEvents:C}),[P,z,H,U,q,C])}const hc=y.createContext(null),pc=y.createContext(null),mc=y.createContext(null);y.createContext(!1);function xx({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:c,onToolEnd:u}){const{api:d,baseUrl:f}=pi(),h=y.useMemo(()=>wn(f),[f]),{state:p,seed:v,prepend:b,pushUser:g,onEvent:x}=cc(),{threads:w,currentThreadId:C,setCurrentThreadId:T,currentThreadIdRef:S,isLoadingThreads:k,threadsError:E,sharedThreads:j,isLoadingSharedThreads:O,actions:F,addThreadFromEvent:H,shareInFlight:U,shareStatus:q,clearShareStatus:P}=Qg({api:d,initialThreadId:t,onError:s,onThreadChange:a,onCurrentThreadDeleted:()=>v([],{})}),[z,I]=y.useState(!1),D=y.useCallback(()=>p.messages,[p.messages]),{threadCheckpoints:R,threadTimeline:A,isLoadingThread:B,isHistoryLoading:W,isLoadingCheckpoint:_,threadStateError:V,hasMoreHistory:ie,loadThread:Q,navigateToCheckpoint:oe,loadOlderMessages:Y,setCurrentCheckpointId:L,returnToLatest:K,handleStateHistoryEvent:te,markSkipNextLoad:G,markStreamPendingThread:X,resetHistoryState:he}=Xg({api:d,seed:v,prepend:b,onError:s,currentThreadId:C,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:z,getMessages:D}),fe=y.useMemo(()=>Wg(R),[R]),Z=y.useCallback(Te=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",Te.threadId),H(Te),S.current!==Te.threadId&&((Te.created??!S.current)&&G(Te.threadId),X(Te.threadId),console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),T(Te.threadId))},[H,G,X]),{startStream:le,stop:be,isStreaming:_e,error:Ne,setAuthToken:$e}=gx({baseUrl:h,onThreadInfo:Z,onMessageEvent:x,onStateHistory:te,onUnhandledEvent:Te=>{console.warn("[ChatSessionProvider] Unhandled event:",Te.type)},onAuthError:i,onConnectionError:c,onToolEvent:Te=>{Te.type==="tool.end"&&(u==null||u(Te))}});y.useEffect(()=>{I(_e)},[_e]);const Xe=y.useCallback(async()=>{v([],{}),T(null),be(),he();try{await d.getAgent("default")}catch(Te){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",Te)}},[v,be,d,he]),nt=y.useCallback(async(Te,Oe,at)=>{const ht=S.current;if(!ht)throw new Error("No active thread to handle interrupt");const Tt=Oe?at??!0:!1;try{const St={threadId:ht,checkpointId:p.lastCheckpointId??void 0,checkpointNs:p.lastCheckpointNs??void 0,command:{kind:"resume",value:Tt}};le(St)}catch(St){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${Te}:`,St),St}},[p.lastCheckpointId,p.lastCheckpointNs,le]),Ve=y.useCallback(async(Te,Oe)=>{let at=S.current;const ht=(Te==null?void 0:Te.text)??"",Tt=(Te==null?void 0:Te.attachments)??[],St=(ht==null?void 0:ht.trim())??"",Le={...(Te==null?void 0:Te.payload)??{}},Ht=Array.isArray(Le.messages)?Le.messages:void 0;Ht&&delete Le.messages;const Je=!!(Ht&&Ht.length);if(!at&&!St&&Tt.length===0&&!Je)return;if(!at){const mt=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Ze=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);at=`${mt}${Ze}`,G(at),T(at)}const{contentParts:qe,filesInfo:dt}=await zg(Tt),bt=[...qe];St&&bt.push({type:"text",text:ht});const Ue=Oe==null?void 0:Oe.originalMessageId,Ct=!!(Oe!=null&&Oe.edit&&Ue),M=!Je&&bt.length>0;let se=null;M&&(se={id:Ct?Ue:`msg-${Date.now()}`,role:"user",content:bt,createdAt:new Date().toISOString()},Ct?g(se,Ue):g(se));const me=Je?Ht:se?[se]:[],We={...Le,...dt.length?{files_info:dt}:{}};me.length?We.messages=me:"messages"in We||(We.messages=[]);const Pe={threadId:at,payload:We,checkpointId:(Oe==null?void 0:Oe.checkpointId)??p.lastCheckpointId??void 0,checkpointNs:(Oe==null?void 0:Oe.checkpointNs)??p.lastCheckpointNs??void 0,edit:!!(Oe!=null&&Oe.edit),timelineCheckpoints:A};le(Pe)},[d,g,p,le,A]),Ke=y.useMemo(()=>({threads:w,currentThreadId:C,setCurrentThreadId:T,isLoading:k,error:E,sharedThreads:j,isLoadingSharedThreads:O,actions:F,shareInFlight:U,shareStatus:q,clearShareStatus:P}),[w,C,T,k,E,j,O,F,U,q,P]),ot=y.useMemo(()=>{const Te=p.assemblingId??null;return Te?{assemblingMessageId:Te}:null},[p.assemblingId]),kt=y.useMemo(()=>({threadId:C,messages:p.messages,interrupt:null,checkpoint:{id:p.lastCheckpointId??null,namespace:p.lastCheckpointNs??null},checkpoints:R,timelineCheckpoints:A,metadata:ot,isLoading:B,isHistoryLoading:W,isLoadingCheckpoint:_,error:V,hasMore:ie,loadOlder:Y,clearState:Xe,navigateToCheckpoint:oe,setCurrentCheckpointId:L,returnToLatest:K,loadThread:Q,clearThread:Xe,respondToInterrupt:nt,messagePreviews:fe}),[C,p,R,A,B,W,_,V,ie,Y,Xe,oe,L,K,Q,nt,fe,ot]),lt=y.useMemo(()=>({isStreaming:_e,error:Ne,connectionState:_e?"connected":"idle",submit:Ve,send:Ve,stop:be,setAuthToken:$e}),[_e,Ne,Ve,be,$e]);return l.jsx(hc.Provider,{value:Ke,children:l.jsx(pc.Provider,{value:kt,children:l.jsx(mc.Provider,{value:lt,children:e})})})}function Ro(){const e=y.useContext(hc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Po(){const e=y.useContext(pc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function gc(){const e=y.useContext(mc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Oo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:c,onThreadChange:u,onToolEnd:d}){return l.jsx(Fg,{apiConfig:t,children:l.jsx(xx,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:c,onConnectionError:i,onThreadChange:u,onToolEnd:d,children:e})})}function ne(...e){return fm.twMerge(dm.clsx(e))}const vx=xo.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"}}),et=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?zn.Slot:"button";return l.jsx(i,{className:ne(vx({variant:t,size:n,className:e})),ref:s,...o})});et.displayName="Button";const xc=m.forwardRef(({className:e,...t},n)=>l.jsx("textarea",{className:ne("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}));xc.displayName="Textarea";function vc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:c,onCancelEdit:u,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const v=i!==void 0,[b,g]=y.useState(e),x=(v?i:b)??"",[w,C]=y.useTransition(),T=y.useRef(null),S=y.useRef(0),k=y.useRef(null);y.useEffect(()=>{v||(g(e??""),k.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,v]);const E=y.useCallback(()=>{const z=T.current;z&&(z.style.height="auto",z.style.height=`${z.scrollHeight}px`)},[]);y.useEffect(()=>{E()},[E,x]);const j=y.useCallback((z,{fromUser:I})=>{v||g(z),I&&(a==null||a(z))},[v,a]),O=y.useCallback(async z=>{z&&z.preventDefault();const I=(x??"").trim();if(!I&&!p)return;const D=++S.current;k.current={id:D,shouldClear:!0},C(()=>{var R,A,B;try{const W=c(I);W&&typeof W.then=="function"?W.then(()=>{var _,V;((_=k.current)==null?void 0:_.id)===D&&k.current.shouldClear&&(v||(g(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((V=k.current)==null?void 0:V.id)===D&&(k.current=null)}).catch(()=>{var _;((_=k.current)==null?void 0:_.id)===D&&(k.current=null)}):(((R=k.current)==null?void 0:R.id)===D&&k.current.shouldClear&&(v||(g(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((A=k.current)==null?void 0:A.id)===D&&(k.current=null))}catch{((B=k.current)==null?void 0:B.id)===D&&(k.current=null)}})},[x,c,p,v,a]),F=y.useCallback(z=>{const I=z.target.value;j(I,{fromUser:!0}),k.current&&(k.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[j]),H=y.useCallback(z=>{z.key==="Enter"&&!z.shiftKey?(z.preventDefault(),O()):z.key==="Escape"&&t&&(z.preventDefault(),u==null||u())},[O,t,u]),P=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return l.jsx("form",{onSubmit:z=>void O(z),className:`w-full ${f}`,children:l.jsxs("div",{className:"flex items-end gap-2",children:[l.jsx("div",{className:"flex-1",children:l.jsx(xc,{ref:T,value:x,onChange:F,onKeyDown:H,placeholder:t?"Edit your message...":n,className:P,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),l.jsx("div",{children:r?l.jsx(et,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:l.jsx(ae.Square,{size:16})}):l.jsx(et,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||w,children:l.jsx(ae.Send,{size:16})})})]})})}const bx=y.memo(vc);function pe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function bc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function En(...e){return t=>{let n=!1;const r=e.map(o=>{const s=bc(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():bc(e[o],null)}}}}function ze(...e){return m.useCallback(En(...e),e)}function wx(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,c=m.useMemo(()=>a,Object.values(a));return l.jsx(n.Provider,{value:c,children:i})};r.displayName=e+"Provider";function o(s){const i=m.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 yn(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),c=n.length;n=[...n,i];const u=f=>{var x;const{scope:h,children:p,...v}=f,b=((x=h==null?void 0:h[e])==null?void 0:x[c])||a,g=m.useMemo(()=>v,Object.values(v));return l.jsx(b.Provider,{value:g,children:p})};u.displayName=s+"Provider";function d(f,h){var b;const p=((b=h==null?void 0:h[e])==null?void 0:b[c])||a,v=m.useContext(p);if(v)return v;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[u,d]}const o=()=>{const s=n.map(i=>m.createContext(i));return function(a){const c=(a==null?void 0:a[e])||s;return m.useMemo(()=>({[`__scope${e}`]:{...a,[e]:c}}),[a,c])}};return o.scopeName=e,[r,yx(o,...t)]}function yx(...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:c,scopeName:u})=>{const f=c(s)[`__scope${u}`];return{...a,...f}},{});return m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Et=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},Sx=m[" useInsertionEffect ".trim().toString()]||Et;function dr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Cx({defaultProp:t,onChange:n}),a=e!==void 0,c=a?e:o;{const d=m.useRef(e!==void 0);m.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 u=m.useCallback(d=>{var f;if(a){const h=kx(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[c,u]}function Cx({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return Sx(()=>{s.current=t},[t]),m.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function kx(e){return typeof e=="function"}var Tx=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ye=Tx.reduce((e,t)=>{const n=zn.createSlot(`Primitive.${t}`),r=m.forwardRef((o,s)=>{const{asChild:i,...a}=o,c=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l.jsx(c,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function wc(e,t){e&&vo.flushSync(()=>e.dispatchEvent(t))}function gi(e){const t=e+"CollectionProvider",[n,r]=yn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=b=>{const{scope:g,children:x}=b,w=y.useRef(null),C=y.useRef(new Map).current;return l.jsx(o,{scope:g,itemMap:C,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",c=zn.createSlot(a),u=y.forwardRef((b,g)=>{const{scope:x,children:w}=b,C=s(a,x),T=ze(g,C.collectionRef);return l.jsx(c,{ref:T,children:w})});u.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=zn.createSlot(d),p=y.forwardRef((b,g)=>{const{scope:x,children:w,...C}=b,T=y.useRef(null),S=ze(g,T),k=s(d,x);return y.useEffect(()=>(k.itemMap.set(T,{ref:T,...C}),()=>void k.itemMap.delete(T))),l.jsx(h,{[f]:"",ref:S,children:w})});p.displayName=d;function v(b){const g=s(e+"CollectionConsumer",b);return y.useCallback(()=>{const w=g.collectionRef.current;if(!w)return[];const C=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(g.itemMap.values()).sort((k,E)=>C.indexOf(k.ref.current)-C.indexOf(E.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:i,Slot:u,ItemSlot:p},v,r]}var Ex=m.createContext(void 0);function Do(e){const t=m.useContext(Ex);return e||t||"ltr"}function It(e){const t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ix(e,t=globalThis==null?void 0:globalThis.document){const n=It(e);m.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 Nx="DismissableLayer",xi="dismissableLayer.update",Ax="dismissableLayer.pointerDownOutside",jx="dismissableLayer.focusOutside",yc,Sc=m.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Lo=m.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...c}=e,u=m.useContext(Sc),[d,f]=m.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=m.useState({}),v=ze(t,E=>f(E)),b=Array.from(u.layers),[g]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),x=b.indexOf(g),w=d?b.indexOf(d):-1,C=u.layersWithOutsidePointerEventsDisabled.size>0,T=w>=x,S=Rx(E=>{const j=E.target,O=[...u.branches].some(F=>F.contains(j));!T||O||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),k=Px(E=>{const j=E.target;[...u.branches].some(F=>F.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return Ix(E=>{w===u.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),m.useEffect(()=>{if(d)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(yc=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(d)),u.layers.add(d),Cc(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=yc)}},[d,h,n,u]),m.useEffect(()=>()=>{d&&(u.layers.delete(d),u.layersWithOutsidePointerEventsDisabled.delete(d),Cc())},[d,u]),m.useEffect(()=>{const E=()=>p({});return document.addEventListener(xi,E),()=>document.removeEventListener(xi,E)},[]),l.jsx(ye.div,{...c,ref:v,style:{pointerEvents:C?T?"auto":"none":void 0,...e.style},onFocusCapture:pe(e.onFocusCapture,k.onFocusCapture),onBlurCapture:pe(e.onBlurCapture,k.onBlurCapture),onPointerDownCapture:pe(e.onPointerDownCapture,S.onPointerDownCapture)})});Lo.displayName=Nx;var _x="DismissableLayerBranch",Mx=m.forwardRef((e,t)=>{const n=m.useContext(Sc),r=m.useRef(null),o=ze(t,r);return m.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),l.jsx(ye.div,{...e,ref:o})});Mx.displayName=_x;function Rx(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=m.useRef(!1),o=m.useRef(()=>{});return m.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let c=function(){kc(Ax,n,u,{discrete:!0})};const u={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:!0})):c()}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 Px(e,t=globalThis==null?void 0:globalThis.document){const n=It(e),r=m.useRef(!1);return m.useEffect(()=>{const o=s=>{s.target&&!r.current&&kc(jx,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 Cc(){const e=new CustomEvent(xi);document.dispatchEvent(e)}function kc(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?wc(o,s):o.dispatchEvent(s)}var vi=0;function bi(){m.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Tc()),document.body.insertAdjacentElement("beforeend",e[1]??Tc()),vi++,()=>{vi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),vi--}},[])}function Tc(){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",yi="focusScope.autoFocusOnUnmount",Ec={bubbles:!1,cancelable:!0},Ox="FocusScope",$o=m.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,c]=m.useState(null),u=It(o),d=It(s),f=m.useRef(null),h=ze(t,b=>c(b)),p=m.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;m.useEffect(()=>{if(r){let b=function(C){if(p.paused||!a)return;const T=C.target;a.contains(T)?f.current=T:In(f.current,{select:!0})},g=function(C){if(p.paused||!a)return;const T=C.relatedTarget;T!==null&&(a.contains(T)||In(f.current,{select:!0}))},x=function(C){if(document.activeElement===document.body)for(const S of C)S.removedNodes.length>0&&In(a)};document.addEventListener("focusin",b),document.addEventListener("focusout",g);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",g),w.disconnect()}}},[r,a,p.paused]),m.useEffect(()=>{if(a){Ac.add(p);const b=document.activeElement;if(!a.contains(b)){const x=new CustomEvent(wi,Ec);a.addEventListener(wi,u),a.dispatchEvent(x),x.defaultPrevented||(Dx(zx(Ic(a)),{select:!0}),document.activeElement===b&&In(a))}return()=>{a.removeEventListener(wi,u),setTimeout(()=>{const x=new CustomEvent(yi,Ec);a.addEventListener(yi,d),a.dispatchEvent(x),x.defaultPrevented||In(b??document.body,{select:!0}),a.removeEventListener(yi,d),Ac.remove(p)},0)}}},[a,u,d,p]);const v=m.useCallback(b=>{if(!n&&!r||p.paused)return;const g=b.key==="Tab"&&!b.altKey&&!b.ctrlKey&&!b.metaKey,x=document.activeElement;if(g&&x){const w=b.currentTarget,[C,T]=Lx(w);C&&T?!b.shiftKey&&x===T?(b.preventDefault(),n&&In(C,{select:!0})):b.shiftKey&&x===C&&(b.preventDefault(),n&&In(T,{select:!0})):x===w&&b.preventDefault()}},[n,r,p.paused]);return l.jsx(ye.div,{tabIndex:-1,...i,ref:h,onKeyDown:v})});$o.displayName=Ox;function Dx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(In(r,{select:t}),document.activeElement!==n)return}function Lx(e){const t=Ic(e),n=Nc(t,e),r=Nc(t.reverse(),e);return[n,r]}function Ic(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 Nc(e,t){for(const n of e)if(!$x(n,{upTo:t}))return n}function $x(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 Fx(e){return e instanceof HTMLInputElement&&"select"in e}function In(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Fx(e)&&t&&e.select()}}var Ac=Bx();function Bx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=jc(e,t),e.unshift(t)},remove(t){var n;e=jc(e,t),(n=e[0])==null||n.resume()}}}function jc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zx(e){return e.filter(t=>t.tagName!=="A")}var Hx=m[" useId ".trim().toString()]||(()=>{}),Ux=0;function Pt(e){const[t,n]=m.useState(Hx());return Et(()=>{n(r=>r??String(Ux++))},[e]),t?`radix-${t}`:""}const Wx=["top","right","bottom","left"],Nn=Math.min,Ut=Math.max,Fo=Math.round,Bo=Math.floor,dn=e=>({x:e,y:e}),Vx={left:"right",right:"left",bottom:"top",top:"bottom"},qx={start:"end",end:"start"};function Si(e,t,n){return Ut(e,Nn(t,n))}function Sn(e,t){return typeof e=="function"?e(t):e}function Cn(e){return e.split("-")[0]}function fr(e){return e.split("-")[1]}function Ci(e){return e==="x"?"y":"x"}function ki(e){return e==="y"?"height":"width"}const Kx=new Set(["top","bottom"]);function fn(e){return Kx.has(Cn(e))?"y":"x"}function Ti(e){return Ci(fn(e))}function Gx(e,t,n){n===void 0&&(n=!1);const r=fr(e),o=Ti(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=zo(i)),[i,zo(i)]}function Yx(e){const t=zo(e);return[Ei(e),t,Ei(t)]}function Ei(e){return e.replace(/start|end/g,t=>qx[t])}const _c=["left","right"],Mc=["right","left"],Xx=["top","bottom"],Jx=["bottom","top"];function Zx(e,t,n){switch(e){case"top":case"bottom":return n?t?Mc:_c:t?_c:Mc;case"left":case"right":return t?Xx:Jx;default:return[]}}function Qx(e,t,n,r){const o=fr(e);let s=Zx(Cn(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ei)))),s}function zo(e){return e.replace(/left|right|bottom|top/g,t=>Vx[t])}function ev(e){return{top:0,right:0,bottom:0,left:0,...e}}function Rc(e){return typeof e!="number"?ev(e):{top:e,right:e,bottom:e,left:e}}function Ho(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 Pc(e,t,n){let{reference:r,floating:o}=e;const s=fn(t),i=Ti(t),a=ki(i),c=Cn(t),u=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(c){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(fr(t)){case"start":p[i]-=h*(n&&u?-1:1);break;case"end":p[i]+=h*(n&&u?-1:1);break}return p}const tv=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),c=await(i.isRTL==null?void 0:i.isRTL(t));let u=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Pc(u,r,c),h=r,p={},v=0;for(let b=0;b<a.length;b++){const{name:g,fn:x}=a[b],{x:w,y:C,data:T,reset:S}=await x({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:u,platform:i,elements:{reference:e,floating:t}});d=w??d,f=C??f,p={...p,[g]:{...p[g],...T}},S&&v<=50&&(v++,typeof S=="object"&&(S.placement&&(h=S.placement),S.rects&&(u=S.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):S.rects),{x:d,y:f}=Pc(u,h,c)),b=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function Dr(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:c}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=Sn(t,e),v=Rc(p),g=a[h?f==="floating"?"reference":"floating":f],x=Ho(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(g)))==null||n?g:g.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:u,rootBoundary:d,strategy:c})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,C=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),T=await(s.isElement==null?void 0:s.isElement(C))?await(s.getScale==null?void 0:s.getScale(C))||{x:1,y:1}:{x:1,y:1},S=Ho(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:C,strategy:c}):w);return{top:(x.top-S.top+v.top)/T.y,bottom:(S.bottom-x.bottom+v.bottom)/T.y,left:(x.left-S.left+v.left)/T.x,right:(S.right-x.right+v.right)/T.x}}const nv=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:c}=t,{element:u,padding:d=0}=Sn(e,t)||{};if(u==null)return{};const f=Rc(d),h={x:n,y:r},p=Ti(o),v=ki(p),b=await i.getDimensions(u),g=p==="y",x=g?"top":"left",w=g?"bottom":"right",C=g?"clientHeight":"clientWidth",T=s.reference[v]+s.reference[p]-h[p]-s.floating[v],S=h[p]-s.reference[p],k=await(i.getOffsetParent==null?void 0:i.getOffsetParent(u));let E=k?k[C]:0;(!E||!await(i.isElement==null?void 0:i.isElement(k)))&&(E=a.floating[C]||s.floating[v]);const j=T/2-S/2,O=E/2-b[v]/2-1,F=Nn(f[x],O),H=Nn(f[w],O),U=F,q=E-b[v]-H,P=E/2-b[v]/2+j,z=Si(U,P,q),I=!c.arrow&&fr(o)!=null&&P!==z&&s.reference[v]/2-(P<U?F:H)-b[v]/2<0,D=I?P<U?P-U:P-q:0;return{[p]:h[p]+D,data:{[p]:z,centerOffset:P-z-D,...I&&{alignmentOffset:D}},reset:I}}}),rv=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:c,elements:u}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:b=!0,...g}=Sn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=Cn(o),w=fn(a),C=Cn(a)===a,T=await(c.isRTL==null?void 0:c.isRTL(u.floating)),S=h||(C||!b?[zo(a)]:Yx(a)),k=v!=="none";!h&&k&&S.push(...Qx(a,b,v,T));const E=[a,...S],j=await Dr(t,g),O=[];let F=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&O.push(j[x]),f){const P=Gx(o,i,T);O.push(j[P[0]],j[P[1]])}if(F=[...F,{placement:o,overflows:O}],!O.every(P=>P<=0)){var H,U;const P=(((H=s.flip)==null?void 0:H.index)||0)+1,z=E[P];if(z&&(!(f==="alignment"?w!==fn(z):!1)||F.every(R=>fn(R.placement)===w?R.overflows[0]>0:!0)))return{data:{index:P,overflows:F},reset:{placement:z}};let I=(U=F.filter(D=>D.overflows[0]<=0).sort((D,R)=>D.overflows[1]-R.overflows[1])[0])==null?void 0:U.placement;if(!I)switch(p){case"bestFit":{var q;const D=(q=F.filter(R=>{if(k){const A=fn(R.placement);return A===w||A==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(A=>A>0).reduce((A,B)=>A+B,0)]).sort((R,A)=>R[1]-A[1])[0])==null?void 0:q[0];D&&(I=D);break}case"initialPlacement":I=a;break}if(o!==I)return{reset:{placement:I}}}return{}}}};function Oc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Dc(e){return Wx.some(t=>e[t]>=0)}const ov=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Sn(e,t);switch(r){case"referenceHidden":{const s=await Dr(t,{...o,elementContext:"reference"}),i=Oc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Dc(i)}}}case"escaped":{const s=await Dr(t,{...o,altBoundary:!0}),i=Oc(s,n.floating);return{data:{escapedOffsets:i,escaped:Dc(i)}}}default:return{}}}}},Lc=new Set(["left","top"]);async function sv(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Cn(n),a=fr(n),c=fn(n)==="y",u=Lc.has(i)?-1:1,d=s&&c?-1:1,f=Sn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:v}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof v=="number"&&(p=a==="end"?v*-1:v),c?{x:p*d,y:h*u}:{x:h*u,y:p*d}}const iv=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,c=await sv(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+c.x,y:s+c.y,data:{...c,placement:i}}}}},av=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:g=>{let{x,y:w}=g;return{x,y:w}}},...c}=Sn(e,t),u={x:n,y:r},d=await Dr(t,c),f=fn(Cn(o)),h=Ci(f);let p=u[h],v=u[f];if(s){const g=h==="y"?"top":"left",x=h==="y"?"bottom":"right",w=p+d[g],C=p-d[x];p=Si(w,p,C)}if(i){const g=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=v+d[g],C=v-d[x];v=Si(w,v,C)}const b=a.fn({...t,[h]:p,[f]:v});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[h]:s,[f]:i}}}}}},lv=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:c=!0,crossAxis:u=!0}=Sn(e,t),d={x:n,y:r},f=fn(o),h=Ci(f);let p=d[h],v=d[f];const b=Sn(a,t),g=typeof b=="number"?{mainAxis:b,crossAxis:0}:{mainAxis:0,crossAxis:0,...b};if(c){const C=h==="y"?"height":"width",T=s.reference[h]-s.floating[C]+g.mainAxis,S=s.reference[h]+s.reference[C]-g.mainAxis;p<T?p=T:p>S&&(p=S)}if(u){var x,w;const C=h==="y"?"width":"height",T=Lc.has(Cn(o)),S=s.reference[f]-s.floating[C]+(T&&((x=i.offset)==null?void 0:x[f])||0)+(T?0:g.crossAxis),k=s.reference[f]+s.reference[C]+(T?0:((w=i.offset)==null?void 0:w[f])||0)-(T?g.crossAxis:0);v<S?v=S:v>k&&(v=k)}return{[h]:p,[f]:v}}}},cv=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:c=()=>{},...u}=Sn(e,t),d=await Dr(t,u),f=Cn(o),h=fr(o),p=fn(o)==="y",{width:v,height:b}=s.floating;let g,x;f==="top"||f==="bottom"?(g=f,x=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,g=h==="end"?"top":"bottom");const w=b-d.top-d.bottom,C=v-d.left-d.right,T=Nn(b-d[g],w),S=Nn(v-d[x],C),k=!t.middlewareData.shift;let E=T,j=S;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=C),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),k&&!h){const F=Ut(d.left,0),H=Ut(d.right,0),U=Ut(d.top,0),q=Ut(d.bottom,0);p?j=v-2*(F!==0||H!==0?F+H:Ut(d.left,d.right)):E=b-2*(U!==0||q!==0?U+q:Ut(d.top,d.bottom))}await c({...t,availableWidth:j,availableHeight:E});const O=await i.getDimensions(a.floating);return v!==O.width||b!==O.height?{reset:{rects:!0}}:{}}}};function Uo(){return typeof window<"u"}function hr(e){return $c(e)?(e.nodeName||"").toLowerCase():"#document"}function Wt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function hn(e){var t;return(t=($c(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function $c(e){return Uo()?e instanceof Node||e instanceof Wt(e).Node:!1}function rn(e){return Uo()?e instanceof Element||e instanceof Wt(e).Element:!1}function pn(e){return Uo()?e instanceof HTMLElement||e instanceof Wt(e).HTMLElement:!1}function Fc(e){return!Uo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Wt(e).ShadowRoot}const uv=new Set(["inline","contents"]);function Lr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=on(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!uv.has(o)}const dv=new Set(["table","td","th"]);function fv(e){return dv.has(hr(e))}const hv=[":popover-open",":modal"];function Wo(e){return hv.some(t=>{try{return e.matches(t)}catch{return!1}})}const pv=["transform","translate","scale","rotate","perspective"],mv=["transform","translate","scale","rotate","perspective","filter"],gv=["paint","layout","strict","content"];function Ii(e){const t=Ni(),n=rn(e)?on(e):e;return pv.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)||mv.some(r=>(n.willChange||"").includes(r))||gv.some(r=>(n.contain||"").includes(r))}function xv(e){let t=An(e);for(;pn(t)&&!pr(t);){if(Ii(t))return t;if(Wo(t))return null;t=An(t)}return null}function Ni(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const vv=new Set(["html","body","#document"]);function pr(e){return vv.has(hr(e))}function on(e){return Wt(e).getComputedStyle(e)}function Vo(e){return rn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function An(e){if(hr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Fc(e)&&e.host||hn(e);return Fc(t)?t.host:t}function Bc(e){const t=An(e);return pr(t)?e.ownerDocument?e.ownerDocument.body:e.body:pn(t)&&Lr(t)?t:Bc(t)}function $r(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Bc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Wt(o);if(s){const a=Ai(i);return t.concat(i,i.visualViewport||[],Lr(o)?o:[],a&&n?$r(a):[])}return t.concat(o,$r(o,[],n))}function Ai(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function zc(e){const t=on(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=pn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Fo(n)!==s||Fo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ji(e){return rn(e)?e:e.contextElement}function mr(e){const t=ji(e);if(!pn(t))return dn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=zc(t);let i=(s?Fo(n.width):n.width)/r,a=(s?Fo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const bv=dn(0);function Hc(e){const t=Wt(e);return!Ni()||!t.visualViewport?bv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function wv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Wt(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=mr(r)):i=mr(e));const a=wv(s,n,r)?Hc(s):dn(0);let c=(o.left+a.x)/i.x,u=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=Wt(s),p=r&&rn(r)?Wt(r):r;let v=h,b=Ai(v);for(;b&&r&&p!==v;){const g=mr(b),x=b.getBoundingClientRect(),w=on(b),C=x.left+(b.clientLeft+parseFloat(w.paddingLeft))*g.x,T=x.top+(b.clientTop+parseFloat(w.paddingTop))*g.y;c*=g.x,u*=g.y,d*=g.x,f*=g.y,c+=C,u+=T,v=Wt(b),b=Ai(v)}}return Ho({width:d,height:f,x:c,y:u})}function qo(e,t){const n=Vo(e).scrollLeft;return t?t.left+n:qn(hn(e)).left+n}function Uc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-qo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function yv(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=hn(r),a=t?Wo(t.floating):!1;if(r===i||a&&s)return n;let c={scrollLeft:0,scrollTop:0},u=dn(1);const d=dn(0),f=pn(r);if((f||!f&&!s)&&((hr(r)!=="body"||Lr(i))&&(c=Vo(r)),pn(r))){const p=qn(r);u=mr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Uc(i,c):dn(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-c.scrollLeft*u.x+d.x+h.x,y:n.y*u.y-c.scrollTop*u.y+d.y+h.y}}function Sv(e){return Array.from(e.getClientRects())}function Cv(e){const t=hn(e),n=Vo(e),r=e.ownerDocument.body,o=Ut(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ut(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+qo(e);const a=-n.scrollTop;return on(r).direction==="rtl"&&(i+=Ut(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Wc=25;function kv(e,t){const n=Wt(e),r=hn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,c=0;if(o){s=o.width,i=o.height;const d=Ni();(!d||d&&t==="fixed")&&(a=o.offsetLeft,c=o.offsetTop)}const u=qo(r);if(u<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,v=Math.abs(r.clientWidth-f.clientWidth-p);v<=Wc&&(s-=v)}else u<=Wc&&(s+=u);return{width:s,height:i,x:a,y:c}}const Tv=new Set(["absolute","fixed"]);function Ev(e,t){const n=qn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=pn(e)?mr(e):dn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,c=o*s.x,u=r*s.y;return{width:i,height:a,x:c,y:u}}function Vc(e,t,n){let r;if(t==="viewport")r=kv(e,n);else if(t==="document")r=Cv(hn(e));else if(rn(t))r=Ev(t,n);else{const o=Hc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Ho(r)}function qc(e,t){const n=An(e);return n===t||!rn(n)||pr(n)?!1:on(n).position==="fixed"||qc(n,t)}function Iv(e,t){const n=t.get(e);if(n)return n;let r=$r(e,[],!1).filter(a=>rn(a)&&hr(a)!=="body"),o=null;const s=on(e).position==="fixed";let i=s?An(e):e;for(;rn(i)&&!pr(i);){const a=on(i),c=Ii(i);!c&&a.position==="fixed"&&(o=null),(s?!c&&!o:!c&&a.position==="static"&&!!o&&Tv.has(o.position)||Lr(i)&&!c&&qc(e,i))?r=r.filter(d=>d!==i):o=a,i=An(i)}return t.set(e,r),r}function Nv(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Wo(t)?[]:Iv(t,this._c):[].concat(n),r],a=i[0],c=i.reduce((u,d)=>{const f=Vc(t,d,o);return u.top=Ut(f.top,u.top),u.right=Nn(f.right,u.right),u.bottom=Nn(f.bottom,u.bottom),u.left=Ut(f.left,u.left),u},Vc(t,a,o));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function Av(e){const{width:t,height:n}=zc(e);return{width:t,height:n}}function jv(e,t,n){const r=pn(t),o=hn(t),s=n==="fixed",i=qn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const c=dn(0);function u(){c.x=qo(o)}if(r||!r&&!s)if((hr(t)!=="body"||Lr(o))&&(a=Vo(t)),r){const p=qn(t,!0,s,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else o&&u();s&&!r&&o&&u();const d=o&&!r&&!s?Uc(o,a):dn(0),f=i.left+a.scrollLeft-c.x-d.x,h=i.top+a.scrollTop-c.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function _i(e){return on(e).position==="static"}function Kc(e,t){if(!pn(e)||on(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return hn(e)===n&&(n=n.ownerDocument.body),n}function Gc(e,t){const n=Wt(e);if(Wo(e))return n;if(!pn(e)){let o=An(e);for(;o&&!pr(o);){if(rn(o)&&!_i(o))return o;o=An(o)}return n}let r=Kc(e,t);for(;r&&fv(r)&&_i(r);)r=Kc(r,t);return r&&pr(r)&&_i(r)&&!Ii(r)?n:r||xv(e)||n}const _v=async function(e){const t=this.getOffsetParent||Gc,n=this.getDimensions,r=await n(e.floating);return{reference:jv(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Mv(e){return on(e).direction==="rtl"}const Rv={convertOffsetParentRelativeRectToViewportRelativeRect:yv,getDocumentElement:hn,getClippingRect:Nv,getOffsetParent:Gc,getElementRects:_v,getClientRects:Sv,getDimensions:Av,getScale:mr,isElement:rn,isRTL:Mv};function Yc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Pv(e,t){let n=null,r;const o=hn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),s();const u=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=u;if(a||t(),!h||!p)return;const v=Bo(f),b=Bo(o.clientWidth-(d+h)),g=Bo(o.clientHeight-(f+p)),x=Bo(d),C={rootMargin:-v+"px "+-b+"px "+-g+"px "+-x+"px",threshold:Ut(0,Nn(1,c))||1};let T=!0;function S(k){const E=k[0].intersectionRatio;if(E!==c){if(!T)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Yc(u,e.getBoundingClientRect())&&i(),T=!1}try{n=new IntersectionObserver(S,{...C,root:o.ownerDocument})}catch{n=new IntersectionObserver(S,C)}n.observe(e)}return i(!0),s}function Ov(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:c=!1}=r,u=ji(e),d=o||s?[...u?$r(u):[],...$r(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=u&&a?Pv(u,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(x=>{let[w]=x;w&&w.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var C;(C=p)==null||C.observe(t)})),n()}),u&&!c&&p.observe(u),p.observe(t));let v,b=c?qn(e):null;c&&g();function g(){const x=qn(e);b&&!Yc(b,x)&&n(),b=x,v=requestAnimationFrame(g)}return n(),()=>{var x;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(x=p)==null||x.disconnect(),p=null,c&&cancelAnimationFrame(v)}}const Dv=iv,Lv=av,$v=rv,Fv=cv,Bv=ov,Xc=nv,zv=lv,Hv=(e,t,n)=>{const r=new Map,o={platform:Rv,...n},s={...o.platform,_c:r};return tv(e,t,{...o,platform:s})};var Uv=typeof document<"u",Wv=function(){},Ko=Uv?y.useLayoutEffect:Wv;function Go(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(!Go(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)&&!Go(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Jc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Zc(e,t){const n=Jc(e);return Math.round(t*n)/n}function Mi(e){const t=m.useRef(e);return Ko(()=>{t.current=e}),t}function Vv(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:c,open:u}=e,[d,f]=m.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=m.useState(r);Go(h,r)||p(r);const[v,b]=m.useState(null),[g,x]=m.useState(null),w=m.useCallback(R=>{R!==k.current&&(k.current=R,b(R))},[]),C=m.useCallback(R=>{R!==E.current&&(E.current=R,x(R))},[]),T=s||v,S=i||g,k=m.useRef(null),E=m.useRef(null),j=m.useRef(d),O=c!=null,F=Mi(c),H=Mi(o),U=Mi(u),q=m.useCallback(()=>{if(!k.current||!E.current)return;const R={placement:t,strategy:n,middleware:h};H.current&&(R.platform=H.current),Hv(k.current,E.current,R).then(A=>{const B={...A,isPositioned:U.current!==!1};P.current&&!Go(j.current,B)&&(j.current=B,vo.flushSync(()=>{f(B)}))})},[h,t,n,H,U]);Ko(()=>{u===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,f(R=>({...R,isPositioned:!1})))},[u]);const P=m.useRef(!1);Ko(()=>(P.current=!0,()=>{P.current=!1}),[]),Ko(()=>{if(T&&(k.current=T),S&&(E.current=S),T&&S){if(F.current)return F.current(T,S,q);q()}},[T,S,q,F,O]);const z=m.useMemo(()=>({reference:k,floating:E,setReference:w,setFloating:C}),[w,C]),I=m.useMemo(()=>({reference:T,floating:S}),[T,S]),D=m.useMemo(()=>{const R={position:n,left:0,top:0};if(!I.floating)return R;const A=Zc(I.floating,d.x),B=Zc(I.floating,d.y);return a?{...R,transform:"translate("+A+"px, "+B+"px)",...Jc(I.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:A,top:B}},[n,a,I.floating,d.x,d.y]);return m.useMemo(()=>({...d,update:q,refs:z,elements:I,floatingStyles:D}),[d,q,z,I,D])}const qv=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?Xc({element:r.current,padding:o}).fn(n):{}:r?Xc({element:r,padding:o}).fn(n):{}}}},Kv=(e,t)=>({...Dv(e),options:[e,t]}),Gv=(e,t)=>({...Lv(e),options:[e,t]}),Yv=(e,t)=>({...zv(e),options:[e,t]}),Xv=(e,t)=>({...$v(e),options:[e,t]}),Jv=(e,t)=>({...Fv(e),options:[e,t]}),Zv=(e,t)=>({...Bv(e),options:[e,t]}),Qv=(e,t)=>({...qv(e),options:[e,t]});var eb="Arrow",Qc=m.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return l.jsx(ye.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:l.jsx("polygon",{points:"0,0 30,0 15,10"})})});Qc.displayName=eb;var tb=Qc;function eu(e){const[t,n]=m.useState(void 0);return Et(()=>{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 c=s.borderBoxSize,u=Array.isArray(c)?c[0]:c;i=u.inlineSize,a=u.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ri="Popper",[tu,Yo]=yn(Ri),[nb,nu]=tu(Ri),ru=e=>{const{__scopePopper:t,children:n}=e,[r,o]=m.useState(null);return l.jsx(nb,{scope:t,anchor:r,onAnchorChange:o,children:n})};ru.displayName=Ri;var ou="PopperAnchor",su=m.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=nu(ou,n),i=m.useRef(null),a=ze(t,i),c=m.useRef(null);return m.useEffect(()=>{const u=c.current;c.current=(r==null?void 0:r.current)||i.current,u!==c.current&&s.onAnchorChange(c.current)}),r?null:l.jsx(ye.div,{...o,ref:a})});su.displayName=ou;var Pi="PopperContent",[rb,ob]=tu(Pi),iu=m.forwardRef((e,t)=>{var Y,L,K,te,G,X;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:c=!0,collisionBoundary:u=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:v,...b}=e,g=nu(Pi,n),[x,w]=m.useState(null),C=ze(t,he=>w(he)),[T,S]=m.useState(null),k=eu(T),E=(k==null?void 0:k.width)??0,j=(k==null?void 0:k.height)??0,O=r+(s!=="center"?"-"+s:""),F=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},H=Array.isArray(u)?u:[u],U=H.length>0,q={padding:F,boundary:H.filter(ib),altBoundary:U},{refs:P,floatingStyles:z,placement:I,isPositioned:D,middlewareData:R}=Vv({strategy:"fixed",placement:O,whileElementsMounted:(...he)=>Ov(...he,{animationFrame:p==="always"}),elements:{reference:g.anchor},middleware:[Kv({mainAxis:o+j,alignmentAxis:i}),c&&Gv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Yv():void 0,...q}),c&&Xv({...q}),Jv({...q,apply:({elements:he,rects:fe,availableWidth:Z,availableHeight:le})=>{const{width:be,height:_e}=fe.reference,Ne=he.floating.style;Ne.setProperty("--radix-popper-available-width",`${Z}px`),Ne.setProperty("--radix-popper-available-height",`${le}px`),Ne.setProperty("--radix-popper-anchor-width",`${be}px`),Ne.setProperty("--radix-popper-anchor-height",`${_e}px`)}}),T&&Qv({element:T,padding:a}),ab({arrowWidth:E,arrowHeight:j}),h&&Zv({strategy:"referenceHidden",...q})]}),[A,B]=cu(I),W=It(v);Et(()=>{D&&(W==null||W())},[D,W]);const _=(Y=R.arrow)==null?void 0:Y.x,V=(L=R.arrow)==null?void 0:L.y,ie=((K=R.arrow)==null?void 0:K.centerOffset)!==0,[Q,oe]=m.useState();return Et(()=>{x&&oe(window.getComputedStyle(x).zIndex)},[x]),l.jsx("div",{ref:P.setFloating,"data-radix-popper-content-wrapper":"",style:{...z,transform:D?z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[(te=R.transformOrigin)==null?void 0:te.x,(G=R.transformOrigin)==null?void 0:G.y].join(" "),...((X=R.hide)==null?void 0:X.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:l.jsx(rb,{scope:n,placedSide:A,onArrowChange:S,arrowX:_,arrowY:V,shouldHideArrow:ie,children:l.jsx(ye.div,{"data-side":A,"data-align":B,...b,ref:C,style:{...b.style,animation:D?void 0:"none"}})})})});iu.displayName=Pi;var au="PopperArrow",sb={top:"bottom",right:"left",bottom:"top",left:"right"},lu=m.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=ob(au,r),i=sb[s.placedSide];return l.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:l.jsx(tb,{...o,ref:n,style:{...o.style,display:"block"}})})});lu.displayName=au;function ib(e){return e!==null}var ab=e=>({name:"transformOrigin",options:e,fn(t){var g,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((g=o.arrow)==null?void 0:g.centerOffset)!==0,a=i?0:e.arrowWidth,c=i?0:e.arrowHeight,[u,d]=cu(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,p=(((w=o.arrow)==null?void 0:w.y)??0)+c/2;let v="",b="";return u==="bottom"?(v=i?f:`${h}px`,b=`${-c}px`):u==="top"?(v=i?f:`${h}px`,b=`${r.floating.height+c}px`):u==="right"?(v=`${-c}px`,b=i?f:`${p}px`):u==="left"&&(v=`${r.floating.width+c}px`,b=i?f:`${p}px`),{data:{x:v,y:b}}}});function cu(e){const[t,n="center"]=e.split("-");return[t,n]}var uu=ru,du=su,fu=iu,hu=lu,lb="Portal",Xo=m.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=m.useState(!1);Et(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Zs.createPortal(l.jsx(ye.div,{...r,ref:t}),i):null});Xo.displayName=lb;function cb(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Yt=e=>{const{present:t,children:n}=e,r=ub(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=ze(r.ref,db(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};Yt.displayName="Presence";function ub(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,c]=cb(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const u=Jo(r.current);s.current=a==="mounted"?u:"none"},[a]),Et(()=>{const u=r.current,d=o.current;if(d!==e){const h=s.current,p=Jo(u);e?c("MOUNT"):p==="none"||(u==null?void 0:u.display)==="none"?c("UNMOUNT"):c(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),Et(()=>{if(t){let u;const d=t.ownerDocument.defaultView??window,f=p=>{const b=Jo(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&b&&(c("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",u=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},h=p=>{p.target===t&&(s.current=Jo(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(u),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function Jo(e){return(e==null?void 0:e.animationName)||"none"}function db(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 Oi="rovingFocusGroup.onEntryFocus",fb={bubbles:!1,cancelable:!0},Fr="RovingFocusGroup",[Di,pu,hb]=gi(Fr),[pb,mu]=yn(Fr,[hb]),[mb,gb]=pb(Fr),gu=m.forwardRef((e,t)=>l.jsx(Di.Provider,{scope:e.__scopeRovingFocusGroup,children:l.jsx(Di.Slot,{scope:e.__scopeRovingFocusGroup,children:l.jsx(xb,{...e,ref:t})})}));gu.displayName=Fr;var xb=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:c,onEntryFocus:u,preventScrollOnEntryFocus:d=!1,...f}=e,h=m.useRef(null),p=ze(t,h),v=Do(s),[b,g]=dr({prop:i,defaultProp:a??null,onChange:c,caller:Fr}),[x,w]=m.useState(!1),C=It(u),T=pu(n),S=m.useRef(!1),[k,E]=m.useState(0);return m.useEffect(()=>{const j=h.current;if(j)return j.addEventListener(Oi,C),()=>j.removeEventListener(Oi,C)},[C]),l.jsx(mb,{scope:n,orientation:r,dir:v,loop:o,currentTabStopId:b,onItemFocus:m.useCallback(j=>g(j),[g]),onItemShiftTab:m.useCallback(()=>w(!0),[]),onFocusableItemAdd:m.useCallback(()=>E(j=>j+1),[]),onFocusableItemRemove:m.useCallback(()=>E(j=>j-1),[]),children:l.jsx(ye.div,{tabIndex:x||k===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:pe(e.onMouseDown,()=>{S.current=!0}),onFocus:pe(e.onFocus,j=>{const O=!S.current;if(j.target===j.currentTarget&&O&&!x){const F=new CustomEvent(Oi,fb);if(j.currentTarget.dispatchEvent(F),!F.defaultPrevented){const H=T().filter(I=>I.focusable),U=H.find(I=>I.active),q=H.find(I=>I.id===b),z=[U,q,...H].filter(Boolean).map(I=>I.ref.current);bu(z,d)}}S.current=!1}),onBlur:pe(e.onBlur,()=>w(!1))})})}),xu="RovingFocusGroupItem",vu=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,c=Pt(),u=s||c,d=gb(xu,n),f=d.currentTabStopId===u,h=pu(n),{onFocusableItemAdd:p,onFocusableItemRemove:v,currentTabStopId:b}=d;return m.useEffect(()=>{if(r)return p(),()=>v()},[r,p,v]),l.jsx(Di.ItemSlot,{scope:n,id:u,focusable:r,active:o,children:l.jsx(ye.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:pe(e.onMouseDown,g=>{r?d.onItemFocus(u):g.preventDefault()}),onFocus:pe(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:pe(e.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){d.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const x=wb(g,d.orientation,d.dir);if(x!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let C=h().filter(T=>T.focusable).map(T=>T.ref.current);if(x==="last")C.reverse();else if(x==="prev"||x==="next"){x==="prev"&&C.reverse();const T=C.indexOf(g.currentTarget);C=d.loop?yb(C,T+1):C.slice(T+1)}setTimeout(()=>bu(C))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:b!=null}):i})})});vu.displayName=xu;var vb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bb(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function wb(e,t,n){const r=bb(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return vb[r]}function bu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function yb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Sb=gu,Cb=vu,kb=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},gr=new WeakMap,Zo=new WeakMap,Qo={},Li=0,wu=function(e){return e&&(e.host||wu(e.parentNode))},Tb=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=wu(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})},Eb=function(e,t,n,r){var o=Tb(t,Array.isArray(e)?e:[e]);Qo[n]||(Qo[n]=new WeakMap);var s=Qo[n],i=[],a=new Set,c=new Set(o),u=function(f){!f||a.has(f)||(a.add(f),u(f.parentNode))};o.forEach(u);var d=function(f){!f||c.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),v=p!==null&&p!=="false",b=(gr.get(h)||0)+1,g=(s.get(h)||0)+1;gr.set(h,b),s.set(h,g),i.push(h),b===1&&v&&Zo.set(h,!0),g===1&&h.setAttribute(n,"true"),v||h.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",h,x)}})};return d(t),a.clear(),Li++,function(){i.forEach(function(f){var h=gr.get(f)-1,p=s.get(f)-1;gr.set(f,h),s.set(f,p),h||(Zo.has(f)||f.removeAttribute(r),Zo.delete(f)),p||f.removeAttribute(n)}),Li--,Li||(gr=new WeakMap,gr=new WeakMap,Zo=new WeakMap,Qo={})}},$i=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=kb(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Eb(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 yu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function Ib(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 es="right-scroll-bar-position",ts="width-before-scroll-bar",Nb="with-scroll-bars-hidden",Ab="--removed-body-scroll-bar-size";function Fi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function jb(e,t){var n=y.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 _b=typeof window<"u"?m.useLayoutEffect:m.useEffect,Su=new WeakMap;function Mb(e,t){var n=jb(null,function(r){return e.forEach(function(o){return Fi(o,r)})});return _b(function(){var r=Su.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Fi(a,null)}),s.forEach(function(a){o.has(a)||Fi(a,i)})}Su.set(n,e)},[e]),n}function Rb(e){return e}function Pb(e,t){t===void 0&&(t=Rb);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 c=function(){var d=i;i=[],d.forEach(s)},u=function(){return Promise.resolve().then(c)};u(),n={push:function(d){i.push(d),u()},filter:function(d){return i=i.filter(d),n}}}};return o}function Ob(e){e===void 0&&(e={});var t=Pb(null);return t.options=mn({async:!0,ssr:!1},e),t}var Cu=function(e){var t=e.sideCar,n=yu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return m.createElement(r,mn({},n))};Cu.isSideCarExport=!0;function Db(e,t){return e.useMedium(t),Cu}var ku=Ob(),Bi=function(){},ns=m.forwardRef(function(e,t){var n=m.useRef(null),r=m.useState({onScrollCapture:Bi,onWheelCapture:Bi,onTouchMoveCapture:Bi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,c=e.className,u=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,v=e.noIsolation,b=e.inert,g=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,C=e.gapMode,T=yu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,k=Mb([n,t]),E=mn(mn({},T),o);return m.createElement(m.Fragment,null,d&&m.createElement(S,{sideCar:ku,removeScrollBar:u,shards:f,noRelative:p,noIsolation:v,inert:b,setCallbacks:s,allowPinchZoom:!!g,lockRef:n,gapMode:C}),i?m.cloneElement(m.Children.only(a),mn(mn({},E),{ref:k})):m.createElement(w,mn({},E,{className:c,ref:k}),a))});ns.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ns.classNames={fullWidth:ts,zeroRight:es};var Lb=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function $b(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Lb();return t&&e.setAttribute("nonce",t),e}function Fb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Bb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var zb=function(){var e=0,t=null;return{add:function(n){e==0&&(t=$b())&&(Fb(t,n),Bb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Hb=function(){var e=zb();return function(t,n){m.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Tu=function(){var e=Hb(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Ub={left:0,top:0,right:0,gap:0},zi=function(e){return parseInt(e||"",10)||0},Wb=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[zi(n),zi(r),zi(o)]},Vb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Ub;var t=Wb(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])}},qb=Tu(),xr="data-scroll-locked",Kb=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
package/package.json
CHANGED