teodor-new-chat-ui 4.3.158 → 4.3.159

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -2412,17 +2412,17 @@ const gy = 3e4, xy = 9e4, Nn = $t.create({
2412
2412
  Nn.interceptors.request.use((e) => (Ps && (e.headers.Authorization = `Bearer ${Ps}`), e));
2413
2413
  Nn.interceptors.response.use(
2414
2414
  (e) => {
2415
- var t;
2415
+ var t, n;
2416
2416
  if (typeof window < "u" && (e != null && e.data))
2417
2417
  try {
2418
- const n = (t = e.data) == null ? void 0 : t.token;
2419
- n && typeof n == "string" && (localStorage.setItem("authToken", n), Ea(n), window.dispatchEvent(
2418
+ const r = (t = e.data) == null ? void 0 : t.token, o = (n = e.data) == null ? void 0 : n.expires_at;
2419
+ r && typeof r == "string" && (localStorage.setItem("authToken", r), Ea(r)), o && typeof o == "number" && localStorage.setItem("authTokenExpiresAt", o.toString()), window.dispatchEvent(
2420
2420
  new CustomEvent("smartorg:chat-token-updated", {
2421
- detail: { token: n }
2421
+ detail: { token: r, expiresAt: o }
2422
2422
  })
2423
- ));
2424
- } catch (n) {
2425
- console.warn("[chat-api] Error storing token:", n);
2423
+ );
2424
+ } catch (r) {
2425
+ console.warn("[chat-api] Error storing token:", r);
2426
2426
  }
2427
2427
  return e;
2428
2428
  },
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[fc]=this[fc]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=go(i);r[a]||(ey(o,i),r[a]=!0)}return M.isArray(t)?t.forEach(s):s(t),this}};ln.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),M.reduceDescriptors(ln.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),M.freezeMethods(ln);function Hi(e,t){const n=this||mo,r=t||n,o=ln.from(r.headers);let s=r.data;return M.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function hc(e){return!!(e&&e.__CANCEL__)}function Ur(e,t,n){Fe.call(this,e??"canceled",Fe.ERR_CANCELED,t,n),this.name="CanceledError"}M.inherits(Ur,Fe,{__CANCEL__:!0});function pc(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Fe("Request failed with status code "+n.status,[Fe.ERR_BAD_REQUEST,Fe.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function ty(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function ny(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(h*1e3/p):void 0}}function ry(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const ns=(e,t,n=3)=>{let r=0;const o=ny(50,250);return ry(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},mc=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},gc=e=>(...t)=>M.asap(()=>e(...t)),oy=Qt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Qt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Qt.origin),Qt.navigator&&/(msie|trident)/i.test(Qt.navigator.userAgent)):()=>!0,sy=Qt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];M.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),M.isString(r)&&i.push("path="+r),M.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 iy(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ay(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function yc(e,t,n){let r=!iy(t);return e&&(r||n==!1)?ay(e,t):t}const xc=e=>e instanceof ln?{...e}:e;function br(e,t){t=t||{};const n={};function r(c,d,f,h){return M.isPlainObject(c)&&M.isPlainObject(d)?M.merge.call({caseless:h},c,d):M.isPlainObject(d)?M.merge({},d):M.isArray(d)?d.slice():d}function o(c,d,f,h){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c,f,h)}else return r(c,d,f,h)}function s(c,d){if(!M.isUndefined(d))return r(void 0,d)}function i(c,d){if(M.isUndefined(d)){if(!M.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(xc(c),xc(d),f,!0)};return M.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,h=f(e[d],t[d],d);M.isUndefined(h)&&f!==a||(n[d]=h)}),n}const vc=e=>{const t=br({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=ln.from(i),t.url=lc(yc(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),M.isFormData(n)){if(Qt.hasStandardBrowserEnv||Qt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(M.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(Qt.hasStandardBrowserEnv&&(r&&M.isFunction(r)&&(r=r(t)),r||r!==!1&&oy(t.url))){const l=o&&s&&sy.read(s);l&&i.set(o,l)}return t},ly=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=vc(e);let s=o.data;const i=ln.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,h,p,m;function g(){p&&p(),m&&m(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function x(){if(!y)return;const C=ln.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),k={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:C,config:e,request:y};pc(function(E){n(E),g()},function(E){r(E),g()},k),y=null}"onloadend"in y?y.onloadend=x:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(x)},y.onabort=function(){y&&(r(new Fe("Request aborted",Fe.ECONNABORTED,e,y)),y=null)},y.onerror=function(T){const k=T&&T.message?T.message:"Network Error",S=new Fe(k,Fe.ERR_NETWORK,e,y);S.event=T||null,r(S),y=null},y.ontimeout=function(){let T=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const k=o.transitional||uc;o.timeoutErrorMessage&&(T=o.timeoutErrorMessage),r(new Fe(T,k.clarifyTimeoutError?Fe.ETIMEDOUT:Fe.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&M.forEach(i.toJSON(),function(T,k){y.setRequestHeader(k,T)}),M.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([h,m]=ns(c,!0),y.addEventListener("progress",h)),l&&y.upload&&([f,p]=ns(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(d=C=>{y&&(r(!C||C.type?new Ur(null,e,y):C),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const w=ty(o.url);if(w&&Qt.protocols.indexOf(w)===-1){r(new Fe("Unsupported protocol "+w+":",Fe.ERR_BAD_REQUEST,e));return}y.send(s||null)})},cy=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof Fe?d:new Ur(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Fe(`timeout ${t} of ms exceeded`,Fe.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>M.asap(a),l}},uy=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},dy=async function*(e,t){for await(const n of fy(e))yield*uy(n,t)},fy=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()}},wc=(e,t,n,r)=>{const o=dy(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let h=s+=f;n(h)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},bc=64*1024,{isFunction:rs}=M,hy=(({Request:e,Response:t})=>({Request:e,Response:t}))(M.global),{ReadableStream:Sc,TextEncoder:Cc}=M.global,kc=(e,...t)=>{try{return!!e(...t)}catch{return!1}},py=e=>{e=M.merge.call({skipUndefined:!0},hy,e);const{fetch:t,Request:n,Response:r}=e,o=t?rs(t):typeof fetch=="function",s=rs(n),i=rs(r);if(!o)return!1;const a=o&&rs(Sc),l=o&&(typeof Cc=="function"?(m=>g=>m.encode(g))(new Cc):async m=>new Uint8Array(await new n(m).arrayBuffer())),c=s&&a&&kc(()=>{let m=!1;const g=new n(Qt.origin,{body:new Sc,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!g}),d=i&&a&&kc(()=>M.isReadableStream(new r("").body)),f={stream:d&&(m=>m.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(g,y)=>{let x=g&&g[m];if(x)return x.call(g);throw new Fe(`Response type '${m}' is not supported`,Fe.ERR_NOT_SUPPORT,y)})});const h=async m=>{if(m==null)return 0;if(M.isBlob(m))return m.size;if(M.isSpecCompliantForm(m))return(await new n(Qt.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(M.isArrayBufferView(m)||M.isArrayBuffer(m))return m.byteLength;if(M.isURLSearchParams(m)&&(m=m+""),M.isString(m))return(await l(m)).byteLength},p=async(m,g)=>{const y=M.toFiniteNumber(m.getContentLength());return y??h(g)};return async m=>{let{url:g,method:y,data:x,signal:w,cancelToken:C,timeout:T,onDownloadProgress:k,onUploadProgress:S,responseType:E,headers:j,withCredentials:_="same-origin",fetchOptions:P}=vc(m),D=t||fetch;E=E?(E+"").toLowerCase():"text";let z=cy([w,C&&C.toAbortSignal()],T),B=null;const O=z&&z.unsubscribe&&(()=>{z.unsubscribe()});let H;try{if(S&&c&&y!=="get"&&y!=="head"&&(H=await p(j,x))!==0){let Q=new n(g,{method:"POST",body:x,duplex:"half"}),ye;if(M.isFormData(x)&&(ye=Q.headers.get("content-type"))&&j.setContentType(ye),Q.body){const[_e,J]=mc(H,ns(gc(S)));x=wc(Q.body,bc,_e,J)}}M.isString(_)||(_=_?"include":"omit");const R=s&&"credentials"in n.prototype,V={...P,signal:z,method:y.toUpperCase(),headers:j.normalize().toJSON(),body:x,duplex:"half",credentials:R?_:void 0};B=s&&new n(g,V);let $=await(s?D(B,P):D(g,V));const F=d&&(E==="stream"||E==="response");if(d&&(k||F&&O)){const Q={};["status","statusText","headers"].forEach(ue=>{Q[ue]=$[ue]});const ye=M.toFiniteNumber($.headers.get("content-length")),[_e,J]=k&&mc(ye,ns(gc(k),!0))||[];$=new r(wc($.body,bc,_e,()=>{J&&J(),O&&O()}),Q)}E=E||"text";let ne=await f[M.findKey(f,E)||"text"]($,m);return!F&&O&&O(),await new Promise((Q,ye)=>{pc(Q,ye,{data:ne,headers:ln.from($.headers),status:$.status,statusText:$.statusText,config:m,request:B})})}catch(R){throw O&&O(),R&&R.name==="TypeError"&&/Load failed|fetch/i.test(R.message)?Object.assign(new Fe("Network Error",Fe.ERR_NETWORK,m,B),{cause:R.cause||R}):Fe.from(R,R&&R.code,m,B)}}},my=new Map,Tc=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=my;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:py(t)),d=c;return c};Tc();const Ui={http:Lg,xhr:ly,fetch:{get:Tc}};M.forEach(Ui,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Ec=e=>`- ${e}`,gy=e=>M.isFunction(e)||e===null||e===!1,Ic={getAdapter:(e,t)=>{e=M.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,!gy(r)&&(o=Ui[(a=String(r)).toLowerCase()],o===void 0))throw new Fe(`Unknown adapter '${a}'`);if(o&&(M.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
33
33
  `+i.map(Ec).join(`
34
34
  `):" "+Ec(i[0]):"as no adapter specified";throw new Fe("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:Ui};function Wi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ur(null,e)}function Nc(e){return Wi(e),e.headers=ln.from(e.headers),e.data=Hi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ic.getAdapter(e.adapter||mo.adapter,e)(e).then(function(r){return Wi(e),r.data=Hi.call(e,e.transformResponse,r),r.headers=ln.from(r.headers),r},function(r){return hc(r)||(Wi(e),r&&r.response&&(r.response.data=Hi.call(e,e.transformResponse,r.response),r.response.headers=ln.from(r.response.headers))),Promise.reject(r)})}const Ac="1.12.2",os={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{os[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const _c={};os.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Ac+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Fe(o(i," has been removed"+(n?" in "+n:"")),Fe.ERR_DEPRECATED);return n&&!_c[i]&&(_c[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}},os.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function yy(e,t,n){if(typeof e!="object")throw new Fe("options must be an object",Fe.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new Fe("option "+s+" must be "+l,Fe.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Fe("Unknown option "+s,Fe.ERR_BAD_OPTION)}}const ss={assertOptions:yy,validators:os},zn=ss.validators;let Sr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new cc,response:new cc}}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=br(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ss.assertOptions(r,{silentJSONParsing:zn.transitional(zn.boolean),forcedJSONParsing:zn.transitional(zn.boolean),clarifyTimeoutError:zn.transitional(zn.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:ss.assertOptions(o,{encode:zn.function,serialize:zn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ss.assertOptions(n,{baseUrl:zn.spelling("baseURL"),withXsrfToken:zn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=ln.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,f=0,h;if(!l){const m=[Nc.bind(this),void 0];for(m.unshift(...a),m.push(...c),h=m.length,d=Promise.resolve(n);f<h;)d=d.then(m[f++],m[f++]);return d}h=a.length;let p=n;for(;f<h;){const m=a[f++],g=a[f++];try{p=m(p)}catch(y){g.call(this,y);break}}try{d=Nc.call(this,p)}catch(m){return Promise.reject(m)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=br(this.defaults,t);const n=yc(t.baseURL,t.url,t.allowAbsoluteUrls);return lc(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){Sr.prototype[t]=function(n,r){return this.request(br(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(br(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Sr.prototype[t]=n(),Sr.prototype[t+"Form"]=n(!0)});let xy=class Gm{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Gm(function(o){t=o}),cancel:t}}};function vy(e){return function(n){return e.apply(null,n)}}function wy(e){return M.isObject(e)&&e.isAxiosError===!0}const Vi={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(Vi).forEach(([e,t])=>{Vi[t]=e});function jc(e){const t=new Sr(e),n=ql(Sr.prototype.request,t);return M.extend(n,Sr.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return jc(br(e,o))},n}const Pt=jc(mo);Pt.Axios=Sr,Pt.CanceledError=Ur,Pt.CancelToken=xy,Pt.isCancel=hc,Pt.VERSION=Ac,Pt.toFormData=es,Pt.AxiosError=Fe,Pt.Cancel=Pt.CanceledError,Pt.all=function(t){return Promise.all(t)},Pt.spread=vy,Pt.isAxiosError=wy,Pt.mergeConfig=br,Pt.AxiosHeaders=ln,Pt.formToJSON=e=>dc(M.isHTMLForm(e)?new FormData(e):e),Pt.getAdapter=Ic.getAdapter,Pt.HttpStatusCode=Vi,Pt.default=Pt;const{Axios:ST,AxiosError:CT,CanceledError:kT,isCancel:TT,CancelToken:ET,VERSION:IT,all:NT,Cancel:AT,isAxiosError:_T,spread:jT,toFormData:PT,AxiosHeaders:RT,HttpStatusCode:OT,formToJSON:MT,getAdapter:DT,mergeConfig:LT}=Pt,Pc=typeof window<"u"?window.__API_BASE_URL__:void 0,Rc=Pc?Zn(Pc):void 0;function Zn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let is=null;const Ki=new Set;function Oc(){return is}function as(e){is=e,Ki.forEach(t=>t(e))}function Mc(e){return Ki.add(e),()=>Ki.delete(e)}const by=3e4,Sy=9e4,vn=Pt.create({...Rc?{baseURL:Rc}:{},timeout:by,withCredentials:!0});vn.interceptors.request.use(e=>(is&&(e.headers.Authorization=`Bearer ${is}`),e)),vn.interceptors.response.use(e=>{var t;if(typeof window<"u"&&(e!=null&&e.data))try{const n=(t=e.data)==null?void 0:t.token;n&&typeof n=="string"&&(localStorage.setItem("authToken",n),as(n),window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:n}})))}catch(n){console.warn("[chat-api] Error storing token:",n)}return e},e=>Promise.reject(e));async function wn(e,t){return vn.defaults.baseURL?(await vn.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function qi(e,t,n){return vn.defaults.baseURL?(await vn.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Dc(e,t,n){return vn.defaults.baseURL?(await vn.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Lc(e,t){return vn.defaults.baseURL?(await vn.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function bn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Fc{get baseUrl(){const t=vn.defaults.baseURL;return t?Zn(String(t)):""}updateConfig(t){t.baseUrl&&(vn.defaults.baseURL=Zn(String(t.baseUrl))),t.authToken!==void 0&&as(t.authToken)}getAuthToken(){return Oc()}setAuthToken(t){as(t)}onTokenChange(t){return Mc(t)}async listThreads(){const t=await wn("/threads"),n=bn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await qi("/threads",t?{title:t}:void 0);return bn(r)}async updateThread(t,n){const r=await Dc(`/threads/${t}`,{title:n});return bn(r)}async deleteThread(t){const n=await Lc(`/threads/${t}`);return bn(n)}async threadInfo(t){const n=await wn(`/threads/${t}/info`);return bn(n)}async listAgents(){const t=await wn("/agents"),n=bn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await wn(`/agents/${t}`);return bn(n)}async getAgentSchema(t){const n=await wn(`/agents/${t}/schema`);return bn(n)}async getState(t){const n=await wn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return bn(n)}async getStateHistory(t){const n=await wn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sy});return bn(n)}async cancelRun(t){const n=await qi("/runs/cancel",{threadId:t});return bn(n)}async listCheckpointSummaries(t){const n=await wn(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=bn(n);return(r==null?void 0:r.items)??[]}}const sr=new Fc,$c=b.createContext(null);function Cy({children:e,apiConfig:t}){const n=sr;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx($c.Provider,{value:r,children:e})}function Gi(){const e=b.useContext($c);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function ky(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Ty(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await ky(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Ey={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Yi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Wr(e,t){return`${e??""}::${t??""}`}function ls(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!Yi(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ny(t),i=zc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function zc(e,t){if(!Yi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,P)=>My(_,P)).filter(_=>!!_),d=cn(e.config),f=cn(d==null?void 0:d.configurable),h=Lt(f,["checkpoint_id","checkpointId"]),p=Lt(f,["checkpoint_ns","checkpointNs"]),m=cn(e==null?void 0:e.parentConfig),g=cn(m==null?void 0:m.configurable),y=Lt(g,["checkpoint_id","checkpointId"])??null,x=Lt(g,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,C=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=cn(e==null?void 0:e.metadata),S=Lt(k,["branch_label","branchLabel"]),E=Lt(g,["checkpoint_id","checkpointId"]),j=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:y,nextCursorNs:x,interrupt:Iy(a,c,t),createdAt:C,parentId:E??null,branchLabel:S??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:m??null,next:j??null,tasks:l??null,values:i??null}}function Iy(e,t,n){const r=Ry(e,n);return r||Py(t,n)}function Ny(e){const t=new Map;e.forEach((o,s)=>{if(!Yi(o))return;const i=zc(o,s);if(!(i!=null&&i.checkpointId))return;const a=Wr(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Ay(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Hc(s.createdAt??"")-Hc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function Ay(e,t){return{...e,metadata:cs(e.metadata,t.metadata)??null,config:cs(e.config,t.config)??null,parentConfig:cs(e.parentConfig,t.parentConfig)??null,next:_y(e.next,t.next)??null,tasks:jy(e.tasks,t.tasks)??null,values:cs(e.values,t.values)??null}}function cs(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function _y(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function jy(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Py(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 Ry(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Oy(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=yo(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=yo(r.state,`${o}-state`);if(s)return s}}return null}function Oy(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,m=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",g=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:m,interrupts:g,state:y!==void 0?y:f}}const n=cn(e);if(!n)return null;const r=Lt(n,["id","task_id","taskId"])??t,o=Lt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function yo(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Bc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=yo(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=yo(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=yo(l,t,n+1,r);if(c)return c}}return null}function Bc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=Lt(n,["type","event","kind"]),o=Lt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Bc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Hc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function My(e,t){if(!e||typeof e!="object")return null;const n=e,r=cn(e)??{},o=cn(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Ey[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=cn(o.additional_kwargs)??cn(o.additionalKwargs),d=cn(o.response_metadata)??cn(o.responseMetadata),f=Lt(c,["createdAt","created_at"])??Lt(o,["created_at","createdAt"]),h=Lt(c,["checkpointId","checkpoint_id"]),p=Lt(c,["checkpointNs","checkpoint_ns"]),m=Dy(o.content),g={id:l,role:i,content:m};f&&(g.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(g.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(g.model=String(d.model_name)),!g.model&&typeof o.model=="string"&&(g.model=o.model),h&&(g.checkpointId=h),p&&(g.checkpointNs=p);const y=zy(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),x=d?{...d}:void 0;y&&Object.keys(y).length&&(g.additionalKwargs=y),x&&Object.keys(x).length&&(g.responseMetadata=x);const w=Ly((c==null?void 0:c.tool_calls)??o.tool_calls);if(w.length&&(g.content=[...g.content,...w]),i==="tool"){const C=Fy(o,g.content);C&&(g.content=C)}return g}function Dy(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Uc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Uc(e);return t?[t]:[]}return[]}function Uc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=Lt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=Lt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Wc(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=Lt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Wc(e,t){var s;const n=Lt(e,["id","call_id"])??t,r=Lt(e,["name"])??Lt(cn(e.function),["name"]);if(!n||!r)return null;const o=$y(e.args??e.arguments??((s=cn(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Ly(e){return Array.isArray(e)?e.map((t,n)=>Wc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Fy(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function $y(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function cn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Lt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function zy(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function By(e){return e.type!=="thread_info"&&e.type!=="token"}const Hy={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Uy(e,t){var n;switch(t.type){case"reset":return{messages:Xi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=Xi(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=Xi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return Kc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>Kc(o,s),e):e}case"interrupt_response":return{...e,messages:qc(e.messages),pendingInterrupt:null};default:return e}}function Vc(e=[]){const[t,n]=b.useReducer(Uy,{...Hy,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function Kc(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=qy(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},h={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:h}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??Gc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(T=>T.id===a&&T.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:Jc(d.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:m,newMeta:g,changed:y}=Wy(d.content,t.delta,h,p);if(!y)return e;const x={...d,content:m},w=us(l,c,x),C={...f,[a]:g};return{...e,messages:w,messagesStreamMeta:C}}if(t.type==="message_end"){const a=e.assemblingId??Gc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(h=>{var p;return(h==null?void 0:h.type)==="text"&&((p=h.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=d.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const h=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:h}}}return e}if(t.type==="tool_start"){const a=Yc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=Xc(e,d,c),h=f>=0?e.messages[f]:null,p=l??d[0]??`${c}-${Date.now()}`,m=(h==null?void 0:h.id)??`tool-${p}`,g=d[0]??p,y={type:"tool_call",id:g,name:c,args:t.args};if(h){const C=Zi(h,d,c,t.args),T={...h,name:h.name??c,additionalKwargs:C},k=f,S=k>=0?us(e.messages,k,T):e.messages,E=ds(T,d),j=Qi(e.toolIndex,m,E);return{...e,messages:S,toolIndex:j}}const x={id:m,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:Zi(void 0,d.length?d:[g],c,t.args)},w=ds(x,d.length?d:[g]);return{...e,messages:[...e.messages,x],toolIndex:Qi(e.toolIndex,m,w)}}if(t.type==="tool_end"){const a=Yc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=Xc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",h=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,p=(d==null?void 0:d.id)??`tool-${h}`,m=ds(d,a);let g=t.output;if(typeof t.output=="string")try{const S=t.output.trim();(S.startsWith("{")||S.startsWith("["))&&(g=JSON.parse(S))}catch{g=t.output}const y={type:"text",text:typeof g=="string"?g:JSON.stringify(g)},x=(d==null?void 0:d.createdAt)??new Date().toISOString(),w=Zi(d??void 0,m.length?m:a,f),C={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:x,additionalKwargs:w},T=c>=0?us(e.messages,c,C):[...e.messages,C],k=ds(C,a.length?a:m);return{...e,messages:T,toolIndex:Qi(e.toolIndex,p,k)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Ky(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=ls(t),l=a.interrupt,c=a.latest,d=l===null?qc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return e}function Xi(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function us(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function qc(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 Gc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Yc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function Ji(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function Zi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=Ji(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function ds(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Ji(e);for(const o of r)n.add(o);return Array.from(n)}function Qi(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function Xc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(Ji(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function Jc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Wy(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??Jc(e);let l="",c=e.slice();if(s){const f=Vy(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",m={...h,text:p+l};c=[...c.slice(0,c.length-1),m]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function Zc(e){return e.replace(/\s+/g," ").trim()}function Vy(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=Zc(e),o=Zc(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 Ky(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 us(e,r,s)}return e}function qy(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Qc(e={}){const t=b.useMemo(()=>Zn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,h]=b.useState(""),[p,m]=b.useState(null),[g,y]=b.useState(0),[x,w]=b.useState(!1),C=b.useRef(null),T=b.useRef(!0),k=b.useRef(0),S=b.useRef(null),E=b.useRef(null),j=b.useRef(null),_=b.useRef(null),P=b.useCallback(O=>{o(O)},[]),D=b.useCallback(()=>{h(""),m(null),d(null),E.current=null,j.current=null,_.current=null},[]),z=b.useCallback(()=>{var O;console.debug("[use-chat] stop() invoked - aborting stream"),(O=C.current)==null||O.abort(),C.current=null,S.current=null,l(!1),w(!1),k.current=0,y(0)},[]),B=b.useCallback((O,H,R)=>{C.current&&(C.current.abort(),C.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),m(null),E.current=null,j.current=null,_.current=null;const V=new AbortController;C.current=V;let $=null,F=null,ne=!1;return S.current={threadId:O.threadId??null,headers:{}},(async()=>{var ye,_e,J,ue,ke,te,L,q,ie,ce,U,We,re,xe,Pe,$e,rt,Se;const Q=Ye=>{var ot;try{const et=JSON.parse(JSON.stringify(Ye));return(ot=et==null?void 0:et.payload)!=null&&ot.files_info&&Array.isArray(et.payload.files_info)&&(et.payload.files_info=et.payload.files_info.map(Xe=>({...Xe,data:Xe!=null&&Xe.data?`<base64 ${String(Xe.data).length} chars>`:Xe==null?void 0:Xe.data}))),et}catch{return Ye}};try{let Ye={};try{if(r)Ye={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ve=window.__AUTH_TOKEN__,Mt=((ye=window.localStorage)==null?void 0:ye.getItem("authToken"))||null;let _t=null;try{const Te=(_e=window.localStorage)==null?void 0:_e.getItem("chat-settings");Te&&(_t=((J=JSON.parse(Te))==null?void 0:J.apiKey)||null)}catch{}const G=Ve||Mt||_t||null;G&&(Ye={Authorization:`Bearer ${G}`})}}catch{}console.debug("[use-chat] POST",t+n,Q(O));let ot={};if(typeof window<"u")try{const ft=(ue=window.localStorage)==null?void 0:ue.getItem("authSessionId");ft&&(ot={"X-Session-Id":ft})}catch{}const et={...Ye,...ot,...s.current},Xe={"Content-Type":"application/json",Accept:"text/event-stream",...et},Ke=await fetch(t+n,{method:"POST",headers:Xe,body:JSON.stringify(O),signal:V.signal,credentials:i});if(S.current&&(S.current.headers=et),!Ke.ok||!Ke.body){const ft=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,ft==null?void 0:ft.slice(0,500));const Ve=`stream ${Ke.status}${ft?": "+ft:""}`;throw(ke=R==null?void 0:R.onConnectionError)==null||ke.call(R,Ve),ne=!0,$="error",F=Ve,new Error(Ve)}w(!0);const tt=Ke.body.getReader(),Ot=new TextDecoder;let St="",nt=[];k.current=0,y(0);let yt=0,Nt=null;const st=()=>{if(nt.length){const ft=nt.join("");nt=[],T.current&&h(Ve=>Ve+ft)}Nt=null},Gt=()=>{typeof window<"u"&&Nt==null&&(Nt=requestAnimationFrame(st))};let Yt=Date.now();const Xt=setInterval(()=>{var ft;if(Date.now()-Yt>18e5){const Ve="Stream idle timeout";d(Ve),$="error",F=Ve,V.abort(),(ft=R==null?void 0:R.onError)==null||ft.call(R,Ve)}},5e3),Jt=1024*1024;try{const ft=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),Ve=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),Mt=ft??null,_t=String(Ve??"").toLowerCase()==="true";for(S.current&&!S.current.threadId&&(S.current={...S.current,threadId:Mt}),(te=R==null?void 0:R.onOpen)==null||te.call(R,{threadId:Mt,created:_t});;){const{value:G,done:Te}=await tt.read();if(Te)break;St+=Ot.decode(G,{stream:!0}),St.length>Jt&&(St="",console.warn("Stream buffer reset: exceeded 1MB"));let ve;for(;(ve=St.indexOf(`
35
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=br(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ss.assertOptions(r,{silentJSONParsing:zn.transitional(zn.boolean),forcedJSONParsing:zn.transitional(zn.boolean),clarifyTimeoutError:zn.transitional(zn.boolean)},!1),o!=null&&(M.isFunction(o)?n.paramsSerializer={serialize:o}:ss.assertOptions(o,{encode:zn.function,serialize:zn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ss.assertOptions(n,{baseUrl:zn.spelling("baseURL"),withXsrfToken:zn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&M.merge(s.common,s[n.method]);s&&M.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=ln.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,f=0,h;if(!l){const m=[Nc.bind(this),void 0];for(m.unshift(...a),m.push(...c),h=m.length,d=Promise.resolve(n);f<h;)d=d.then(m[f++],m[f++]);return d}h=a.length;let p=n;for(;f<h;){const m=a[f++],g=a[f++];try{p=m(p)}catch(y){g.call(this,y);break}}try{d=Nc.call(this,p)}catch(m){return Promise.reject(m)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=br(this.defaults,t);const n=yc(t.baseURL,t.url,t.allowAbsoluteUrls);return lc(n,t.params,t.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(t){Sr.prototype[t]=function(n,r){return this.request(br(r||{},{method:t,url:n,data:(r||{}).data}))}}),M.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(br(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Sr.prototype[t]=n(),Sr.prototype[t+"Form"]=n(!0)});let xy=class Gm{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new Ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Gm(function(o){t=o}),cancel:t}}};function vy(e){return function(n){return e.apply(null,n)}}function wy(e){return M.isObject(e)&&e.isAxiosError===!0}const Vi={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(Vi).forEach(([e,t])=>{Vi[t]=e});function jc(e){const t=new Sr(e),n=ql(Sr.prototype.request,t);return M.extend(n,Sr.prototype,t,{allOwnKeys:!0}),M.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return jc(br(e,o))},n}const Pt=jc(mo);Pt.Axios=Sr,Pt.CanceledError=Ur,Pt.CancelToken=xy,Pt.isCancel=hc,Pt.VERSION=Ac,Pt.toFormData=es,Pt.AxiosError=Fe,Pt.Cancel=Pt.CanceledError,Pt.all=function(t){return Promise.all(t)},Pt.spread=vy,Pt.isAxiosError=wy,Pt.mergeConfig=br,Pt.AxiosHeaders=ln,Pt.formToJSON=e=>dc(M.isHTMLForm(e)?new FormData(e):e),Pt.getAdapter=Ic.getAdapter,Pt.HttpStatusCode=Vi,Pt.default=Pt;const{Axios:ST,AxiosError:CT,CanceledError:kT,isCancel:TT,CancelToken:ET,VERSION:IT,all:NT,Cancel:AT,isAxiosError:_T,spread:jT,toFormData:PT,AxiosHeaders:RT,HttpStatusCode:OT,formToJSON:MT,getAdapter:DT,mergeConfig:LT}=Pt,Pc=typeof window<"u"?window.__API_BASE_URL__:void 0,Rc=Pc?Zn(Pc):void 0;function Zn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let is=null;const Ki=new Set;function Oc(){return is}function as(e){is=e,Ki.forEach(t=>t(e))}function Mc(e){return Ki.add(e),()=>Ki.delete(e)}const by=3e4,Sy=9e4,vn=Pt.create({...Rc?{baseURL:Rc}:{},timeout:by,withCredentials:!0});vn.interceptors.request.use(e=>(is&&(e.headers.Authorization=`Bearer ${is}`),e)),vn.interceptors.response.use(e=>{var t,n;if(typeof window<"u"&&(e!=null&&e.data))try{const r=(t=e.data)==null?void 0:t.token,o=(n=e.data)==null?void 0:n.expires_at;r&&typeof r=="string"&&(localStorage.setItem("authToken",r),as(r)),o&&typeof o=="number"&&localStorage.setItem("authTokenExpiresAt",o.toString()),window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(r){console.warn("[chat-api] Error storing token:",r)}return e},e=>Promise.reject(e));async function wn(e,t){return vn.defaults.baseURL?(await vn.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function qi(e,t,n){return vn.defaults.baseURL?(await vn.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Dc(e,t,n){return vn.defaults.baseURL?(await vn.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Lc(e,t){return vn.defaults.baseURL?(await vn.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function bn(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Fc{get baseUrl(){const t=vn.defaults.baseURL;return t?Zn(String(t)):""}updateConfig(t){t.baseUrl&&(vn.defaults.baseURL=Zn(String(t.baseUrl))),t.authToken!==void 0&&as(t.authToken)}getAuthToken(){return Oc()}setAuthToken(t){as(t)}onTokenChange(t){return Mc(t)}async listThreads(){const t=await wn("/threads"),n=bn(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await qi("/threads",t?{title:t}:void 0);return bn(r)}async updateThread(t,n){const r=await Dc(`/threads/${t}`,{title:n});return bn(r)}async deleteThread(t){const n=await Lc(`/threads/${t}`);return bn(n)}async threadInfo(t){const n=await wn(`/threads/${t}/info`);return bn(n)}async listAgents(){const t=await wn("/agents"),n=bn(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await wn(`/agents/${t}`);return bn(n)}async getAgentSchema(t){const n=await wn(`/agents/${t}/schema`);return bn(n)}async getState(t){const n=await wn(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return bn(n)}async getStateHistory(t){const n=await wn(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sy});return bn(n)}async cancelRun(t){const n=await qi("/runs/cancel",{threadId:t});return bn(n)}async listCheckpointSummaries(t){const n=await wn(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=bn(n);return(r==null?void 0:r.items)??[]}}const sr=new Fc,$c=b.createContext(null);function Cy({children:e,apiConfig:t}){const n=sr;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx($c.Provider,{value:r,children:e})}function Gi(){const e=b.useContext($c);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function ky(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Ty(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await ky(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Ey={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Yi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Wr(e,t){return`${e??""}::${t??""}`}function ls(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!Yi(r))return{threadId:n,latest:null,checkpoints:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ny(t),i=zc(r,0);return{threadId:n,latest:i,checkpoints:o,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function zc(e,t){if(!Yi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,P)=>My(_,P)).filter(_=>!!_),d=cn(e.config),f=cn(d==null?void 0:d.configurable),h=Lt(f,["checkpoint_id","checkpointId"]),p=Lt(f,["checkpoint_ns","checkpointNs"]),m=cn(e==null?void 0:e.parentConfig),g=cn(m==null?void 0:m.configurable),y=Lt(g,["checkpoint_id","checkpointId"])??null,x=Lt(g,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,C=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),T=c[c.length-1]??null,k=cn(e==null?void 0:e.metadata),S=Lt(k,["branch_label","branchLabel"]),E=Lt(g,["checkpoint_id","checkpointId"]),j=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:y,nextCursorNs:x,interrupt:Iy(a,c,t),createdAt:C,parentId:E??null,branchLabel:S??null,lastMessageId:(T==null?void 0:T.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:k??null,config:d??null,parentConfig:m??null,next:j??null,tasks:l??null,values:i??null}}function Iy(e,t,n){const r=Ry(e,n);return r||Py(t,n)}function Ny(e){const t=new Map;e.forEach((o,s)=>{if(!Yi(o))return;const i=zc(o,s);if(!(i!=null&&i.checkpointId))return;const a=Wr(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Ay(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Hc(s.createdAt??"")-Hc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function Ay(e,t){return{...e,metadata:cs(e.metadata,t.metadata)??null,config:cs(e.config,t.config)??null,parentConfig:cs(e.parentConfig,t.parentConfig)??null,next:_y(e.next,t.next)??null,tasks:jy(e.tasks,t.tasks)??null,values:cs(e.values,t.values)??null}}function cs(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function _y(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function jy(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Py(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 Ry(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Oy(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=yo(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=yo(r.state,`${o}-state`);if(s)return s}}return null}function Oy(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,m=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",g=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:m,interrupts:g,state:y!==void 0?y:f}}const n=cn(e);if(!n)return null;const r=Lt(n,["id","task_id","taskId"])??t,o=Lt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function yo(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Bc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=yo(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=yo(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=yo(l,t,n+1,r);if(c)return c}}return null}function Bc(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=Lt(n,["type","event","kind"]),o=Lt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Bc(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Hc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function My(e,t){if(!e||typeof e!="object")return null;const n=e,r=cn(e)??{},o=cn(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Ey[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=cn(o.additional_kwargs)??cn(o.additionalKwargs),d=cn(o.response_metadata)??cn(o.responseMetadata),f=Lt(c,["createdAt","created_at"])??Lt(o,["created_at","createdAt"]),h=Lt(c,["checkpointId","checkpoint_id"]),p=Lt(c,["checkpointNs","checkpoint_ns"]),m=Dy(o.content),g={id:l,role:i,content:m};f&&(g.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(g.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(g.model=String(d.model_name)),!g.model&&typeof o.model=="string"&&(g.model=o.model),h&&(g.checkpointId=h),p&&(g.checkpointNs=p);const y=zy(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),x=d?{...d}:void 0;y&&Object.keys(y).length&&(g.additionalKwargs=y),x&&Object.keys(x).length&&(g.responseMetadata=x);const w=Ly((c==null?void 0:c.tool_calls)??o.tool_calls);if(w.length&&(g.content=[...g.content,...w]),i==="tool"){const C=Fy(o,g.content);C&&(g.content=C)}return g}function Dy(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Uc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Uc(e);return t?[t]:[]}return[]}function Uc(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=Lt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=Lt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Wc(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=Lt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Wc(e,t){var s;const n=Lt(e,["id","call_id"])??t,r=Lt(e,["name"])??Lt(cn(e.function),["name"]);if(!n||!r)return null;const o=$y(e.args??e.arguments??((s=cn(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Ly(e){return Array.isArray(e)?e.map((t,n)=>Wc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Fy(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function $y(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function cn(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function Lt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function zy(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}function By(e){return e.type!=="thread_info"&&e.type!=="token"}const Hy={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,messagesStreamMeta:{},pendingInterrupt:null};function Uy(e,t){var n;switch(t.type){case"reset":return{messages:Xi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},lastBranch:null,pendingInterrupt:null};case"seed":{const r=Xi(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=Xi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(i=>i.id)),s=r.filter(i=>!o.has(i.id));return s.length?{...e,messages:[...s,...e.messages]}:e}case"user_message":{const r=t.payload.message;return e.messages.some(o=>o.id===r.id)?e:{...e,messages:[...e.messages,r]}}case"event":return Kc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>Kc(o,s),e):e}case"interrupt_response":return{...e,messages:qc(e.messages),pendingInterrupt:null};default:return e}}function Vc(e=[]){const[t,n]=b.useReducer(Uy,{...Hy,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function Kc(e,t){var n,r,o,s,i;if(t.type==="message_start"&&t.role==="assistant"){const a=t.id,l=qy(t.model);if(e.messages.some(f=>f.id===a)){const f=e.messagesStreamMeta??{},h={...f,[a]:f[a]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:a,messagesStreamMeta:h}}const d={id:a,role:"assistant",name:l||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:a,messages:[...e.messages,d]}}if(t.type==="message_delta"){const a=e.assemblingId??Gc(e.messages);if(!a)return e;const l=e.messages,c=l.findIndex(T=>T.id===a&&T.role==="assistant");if(c===-1)return e;const d=l[c],f=e.messagesStreamMeta??{},h=f[a]??{lastSeq:null,lastText:Jc(d.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:m,newMeta:g,changed:y}=Wy(d.content,t.delta,h,p);if(!y)return e;const x={...d,content:m},w=us(l,c,x),C={...f,[a]:g};return{...e,messages:w,messagesStreamMeta:C}}if(t.type==="message_end"){const a=e.assemblingId??Gc(e.messages);if(!a)return{...e,assemblingId:null};const l=e.messages,c=l.findIndex(d=>d.id===a&&d.role==="assistant");if(c>=0){const d=l[c];if(!((n=d.content)==null?void 0:n.some(h=>{var p;return(h==null?void 0:h.type)==="text"&&((p=h.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:d.id,contentTypes:(r=d.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=d.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const h=[...l.slice(0,c),...l.slice(c+1)];return{...e,assemblingId:null,messages:h}}}return e}if(t.type==="tool_start"){const a=Yc(t),l=a[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),c=t.name??t.tool??"tool";!l&&a.length===0&&a.push(`${c}-${Date.now()}`);const d=a.length?a:l?[l]:[],f=Xc(e,d,c),h=f>=0?e.messages[f]:null,p=l??d[0]??`${c}-${Date.now()}`,m=(h==null?void 0:h.id)??`tool-${p}`,g=d[0]??p,y={type:"tool_call",id:g,name:c,args:t.args};if(h){const C=Zi(h,d,c,t.args),T={...h,name:h.name??c,additionalKwargs:C},k=f,S=k>=0?us(e.messages,k,T):e.messages,E=ds(T,d),j=Qi(e.toolIndex,m,E);return{...e,messages:S,toolIndex:j}}const x={id:m,role:"tool",name:c,createdAt:new Date().toISOString(),content:[y],additionalKwargs:Zi(void 0,d.length?d:[g],c,t.args)},w=ds(x,d.length?d:[g]);return{...e,messages:[...e.messages,x],toolIndex:Qi(e.toolIndex,m,w)}}if(t.type==="tool_end"){const a=Yc(t);if(!a.length&&!(typeof t.id=="string"&&t.id))return e;const l=t.name??null,c=Xc(e,a,l),d=c>=0?e.messages[c]:null,f=l??(d==null?void 0:d.name)??((s=d==null?void 0:d.additionalKwargs)==null?void 0:s.toolName)??"tool",h=a[0]??((i=d==null?void 0:d.id)==null?void 0:i.replace(/^tool-/,""))??`${f}-${Date.now()}`,p=(d==null?void 0:d.id)??`tool-${h}`,m=ds(d,a);let g=t.output;if(typeof t.output=="string")try{const S=t.output.trim();(S.startsWith("{")||S.startsWith("["))&&(g=JSON.parse(S))}catch{g=t.output}const y={type:"text",text:typeof g=="string"?g:JSON.stringify(g)},x=(d==null?void 0:d.createdAt)??new Date().toISOString(),w=Zi(d??void 0,m.length?m:a,f),C={id:p,role:"tool",name:f??(d==null?void 0:d.name)??"tool",content:[y],createdAt:x,additionalKwargs:w},T=c>=0?us(e.messages,c,C):[...e.messages,C],k=ds(C,a.length?a:m);return{...e,messages:T,toolIndex:Qi(e.toolIndex,p,k)}}if(t.type==="checkpoint"){const a=t.checkpointNs??e.lastCheckpointNs??null,l=Ky(e.messages,t.checkpointId,a);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:a,messages:l}}if(t.type==="branch"){const a=t.checkpointId??e.lastCheckpointId,l=t.checkpointNs??e.lastCheckpointNs;return{...e,lastBranch:t,lastCheckpointId:a??null,lastCheckpointNs:l??null}}if(t.type==="error"){const a={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,a]}}if(t.type==="state_history"){const a=ls(t),l=a.interrupt,c=a.latest,d=l===null?qc(e.messages):e.messages;return{...e,messages:d,pendingInterrupt:l,lastCheckpointId:(c==null?void 0:c.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(c==null?void 0:c.checkpointNs)??e.lastCheckpointNs}}return e}function Xi(e){return e.filter(t=>{if(t.role!=="assistant")return!0;const n=(t.content||[]).some(o=>{var s;return o&&o.type==="text"&&((s=o.text)==null?void 0:s.trim())}),r=(t.content||[]).some(o=>o&&o.type==="image_url");return!!(n||r)})}function us(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function qc(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 Gc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function Yc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function Ji(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function Zi(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};if(e){const l=Ji(e);for(const c of l)s(c)}for(const l of t)s(l);const i=Array.from(o),a={...(e==null?void 0:e.additionalKwargs)??{}};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function ds(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=Ji(e);for(const o of r)n.add(o);return Array.from(n)}function Qi(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function Xc(e,t,n){var o,s;const r=new Set(t.filter(i=>typeof i=="string"&&i.trim()));for(const i of r){const a=e.toolIndex[i];if(a){const l=e.messages.findIndex(c=>c.id===a);if(l!==-1)return l}}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(Ji(a).some(c=>r.has(c)))return i}if(typeof n=="string"&&n.trim())for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool"||a.name&&a.name!==n)continue;if(!((o=a.content)==null?void 0:o.some(c=>c.type!=="tool_call")))return i}for(let i=e.messages.length-1;i>=0;i--){const a=e.messages[i];if(a.role!=="tool")continue;if(!((s=a.content)==null?void 0:s.some(c=>c.type!=="tool_call")))return i}return-1}function Jc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function Wy(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??Jc(e);let l="",c=e.slice();if(s){const f=Vy(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",m={...h,text:p+l};c=[...c.slice(0,c.length-1),m]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function Zc(e){return e.replace(/\s+/g," ").trim()}function Vy(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=Zc(e),o=Zc(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 Ky(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 us(e,r,s)}return e}function qy(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function Qc(e={}){const t=b.useMemo(()=>Zn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,h]=b.useState(""),[p,m]=b.useState(null),[g,y]=b.useState(0),[x,w]=b.useState(!1),C=b.useRef(null),T=b.useRef(!0),k=b.useRef(0),S=b.useRef(null),E=b.useRef(null),j=b.useRef(null),_=b.useRef(null),P=b.useCallback(O=>{o(O)},[]),D=b.useCallback(()=>{h(""),m(null),d(null),E.current=null,j.current=null,_.current=null},[]),z=b.useCallback(()=>{var O;console.debug("[use-chat] stop() invoked - aborting stream"),(O=C.current)==null||O.abort(),C.current=null,S.current=null,l(!1),w(!1),k.current=0,y(0)},[]),B=b.useCallback((O,H,R)=>{C.current&&(C.current.abort(),C.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),m(null),E.current=null,j.current=null,_.current=null;const V=new AbortController;C.current=V;let $=null,F=null,ne=!1;return S.current={threadId:O.threadId??null,headers:{}},(async()=>{var ye,_e,J,ue,ke,te,L,q,ie,ce,U,We,re,xe,Pe,$e,rt,Se;const Q=Ye=>{var ot;try{const et=JSON.parse(JSON.stringify(Ye));return(ot=et==null?void 0:et.payload)!=null&&ot.files_info&&Array.isArray(et.payload.files_info)&&(et.payload.files_info=et.payload.files_info.map(Xe=>({...Xe,data:Xe!=null&&Xe.data?`<base64 ${String(Xe.data).length} chars>`:Xe==null?void 0:Xe.data}))),et}catch{return Ye}};try{let Ye={};try{if(r)Ye={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Ve=window.__AUTH_TOKEN__,Mt=((ye=window.localStorage)==null?void 0:ye.getItem("authToken"))||null;let _t=null;try{const Te=(_e=window.localStorage)==null?void 0:_e.getItem("chat-settings");Te&&(_t=((J=JSON.parse(Te))==null?void 0:J.apiKey)||null)}catch{}const G=Ve||Mt||_t||null;G&&(Ye={Authorization:`Bearer ${G}`})}}catch{}console.debug("[use-chat] POST",t+n,Q(O));let ot={};if(typeof window<"u")try{const ft=(ue=window.localStorage)==null?void 0:ue.getItem("authSessionId");ft&&(ot={"X-Session-Id":ft})}catch{}const et={...Ye,...ot,...s.current},Xe={"Content-Type":"application/json",Accept:"text/event-stream",...et},Ke=await fetch(t+n,{method:"POST",headers:Xe,body:JSON.stringify(O),signal:V.signal,credentials:i});if(S.current&&(S.current.headers=et),!Ke.ok||!Ke.body){const ft=await Ke.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ke.status,ft==null?void 0:ft.slice(0,500));const Ve=`stream ${Ke.status}${ft?": "+ft:""}`;throw(ke=R==null?void 0:R.onConnectionError)==null||ke.call(R,Ve),ne=!0,$="error",F=Ve,new Error(Ve)}w(!0);const tt=Ke.body.getReader(),Ot=new TextDecoder;let St="",nt=[];k.current=0,y(0);let yt=0,Nt=null;const st=()=>{if(nt.length){const ft=nt.join("");nt=[],T.current&&h(Ve=>Ve+ft)}Nt=null},Gt=()=>{typeof window<"u"&&Nt==null&&(Nt=requestAnimationFrame(st))};let Yt=Date.now();const Xt=setInterval(()=>{var ft;if(Date.now()-Yt>18e5){const Ve="Stream idle timeout";d(Ve),$="error",F=Ve,V.abort(),(ft=R==null?void 0:R.onError)==null||ft.call(R,Ve)}},5e3),Jt=1024*1024;try{const ft=Ke.headers.get("X-Thread-Id")||Ke.headers.get("x-thread-id"),Ve=Ke.headers.get("X-Thread-Created")||Ke.headers.get("x-thread-created"),Mt=ft??null,_t=String(Ve??"").toLowerCase()==="true";for(S.current&&!S.current.threadId&&(S.current={...S.current,threadId:Mt}),(te=R==null?void 0:R.onOpen)==null||te.call(R,{threadId:Mt,created:_t});;){const{value:G,done:Te}=await tt.read();if(Te)break;St+=Ot.decode(G,{stream:!0}),St.length>Jt&&(St="",console.warn("Stream buffer reset: exceeded 1MB"));let ve;for(;(ve=St.indexOf(`
36
36
 
37
37
  `))>=0;){const pt=St.slice(0,ve);St=St.slice(ve+2);const mt=Yy(pt);if(!mt)continue;let ct;try{ct=JSON.parse(mt)}catch{console.debug("[use-chat] malformed SSE:",mt.slice(0,200));continue}const Me=Gy(ct)?ct.data:ct;Yt=Date.now();const Ut=Me.seq;if(Ut!==void 0){if(Ut<=yt){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Ut,lastProcessedSeq:yt,type:Me.type});continue}yt>0&&Ut>yt+1&&((L=R==null?void 0:R.onGap)==null||L.call(R,{from:yt,to:Ut})),yt=Ut,k.current=Ut,y(Ut)}if(console.debug("[use-chat] received event",{seq:Me.seq,type:Me.type,preview:(()=>{var Le;try{return Me.type==="message_delta"?{deltaTypes:(Le=Me.delta)==null?void 0:Le.map(xt=>xt.type),textLen:(Me.delta||[]).filter(xt=>xt.type==="text").map(xt=>String(xt.text||"").length)}:Me.content||Me.delta?{hasContent:!0}:{}}catch(xt){return{err:String(xt)}}})()}),Me.type==="checkpoint")E.current=Me.checkpointId??null,j.current=Me.checkpointNs??null,m(Me.checkpointId??null);else if(Me.type==="state_history"){_.current=Me;try{const xt=ls(Me).latest;xt&&(E.current=xt.checkpointId??null,j.current=xt.checkpointNs??null,m(xt.checkpointId??null))}catch(Le){console.warn("[use-chat] Failed to hydrate state_history payload",Le)}}try{H==null||H(Me)}catch(Le){console.error("[use-chat] Error in onEvent callback:",Le,"for event:",Me.type)}if(Me.type==="token"&&e.autoAppendAssistant!==!1)nt.push(Me.content),Gt();else if(Me.type==="message_delta"){const Le=Me.delta.filter(xt=>xt.type==="text").map(xt=>xt.text).join("");Le&&e.autoAppendAssistant!==!1&&(nt.push(Le),Gt())}else if(Me.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(q=R==null?void 0:R.onHeartbeat)==null||q.call(R,Me)}catch(Le){console.warn("[use-chat] heartbeat callback failed",Le)}}else if(Nt!==null&&cancelAnimationFrame(Nt),st(),Me.type==="checkpoint")m(Me.checkpointId);else if(Me.type==="error"){const Le=Me;if(d(Le.message),$="error",F=Le.message,Le.error_type==="auth_error"||Le.code==="TOKEN_EXPIRED"||((ie=Le.message)==null?void 0:ie.includes("token"))||((ce=Le.message)==null?void 0:ce.includes("401"))||((U=Le.message)==null?void 0:U.includes("unauthorized"))||((We=Le.message)==null?void 0:We.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Le.message);try{(re=R==null?void 0:R.onAuthError)==null||re.call(R,Le.message)}catch(Ln){console.warn("[use-chat] onAuthError handler failed",Ln)}V.abort()}}}}st(),$===null&&!V.signal.aborted&&($="complete")}catch(ft){if(ft.name==="AbortError")$=$??"aborted";else{const Ve=ft.message||String(ft);$="error",F=Ve,d(Ve),(xe=R==null?void 0:R.onError)==null||xe.call(R,Ve)}}finally{try{await tt.cancel()}catch{}finally{(Pe=tt.releaseLock)==null||Pe.call(tt)}Nt!==null&&typeof window<"u"&&window.cancelAnimationFrame(Nt),clearInterval(Xt)}}catch(Ye){if(Ye.name==="AbortError")$=$??"aborted";else{const ot=Ye.message||String(Ye);$="error",F=ot,d(ot),($e=R==null?void 0:R.onError)==null||$e.call(R,ot),ne||((rt=R==null?void 0:R.onConnectionError)==null||rt.call(R,ot),ne=!0)}}finally{const Ye=k.current,ot=E.current,et=j.current,Xe=_.current,Ke=$??(V.signal.aborted?"aborted":F?"error":"complete");try{(Se=R==null?void 0:R.onClosed)==null||Se.call(R,{reason:Ke,lastSeq:Ye,lastCheckpointId:ot,lastCheckpointNs:et,lastStateHistory:Xe,error:F})}catch(tt){console.warn("[use-chat] onClosed callback failed",tt)}l(!1),w(!1),C.current=null,k.current=0,y(0),S.current=null}})(),{close:()=>V.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var O;T.current=!1,(O=C.current)==null||O.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:g,connected:x,stream:B,stop:z,clear:D,setToken:P}}function Gy(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Yy(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 eu=200;function Xy({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onUnhandledEvent:r,onSequenceGap:o,onStreamClosed:s,onConnectionError:i,onAuthError:a,onHeartbeat:l}){const c=b.useRef(null),d=b.useRef(null),f=b.useRef(new Map),h=b.useRef(null),p=b.useCallback(_=>{try{const P=globalThis.structuredClone;if(typeof P=="function")return P(_)}catch{}try{return JSON.parse(JSON.stringify(_))}catch{return _}},[]),m=b.useCallback((_,P)=>{if(!_)return;const D=f.current.get(_)??[],z=p(P),B=D.length>=eu?[...D.slice(D.length-eu+1),z]:[...D,z];f.current.set(_,B)},[p]),g=b.useCallback(_=>{_&&f.current.set(_,[])},[]),y=b.useCallback(_=>{const P=_??d.current;if(!P)return;const D=f.current.get(P);D!=null&&D.length&&D.forEach(z=>{try{n(z)}catch(B){console.error("[useChatStreamingService] Failed to replay buffered event",B)}})},[n]),x=b.useCallback(_=>{var z,B,O,H,R;const P=_.seq??null;if(P!==null){const V=c.current;if(V!==null){if(P<=V)return;P>V+1&&(o==null||o({from:V,to:P}))}c.current=P}if(_.type==="thread_info"){d.current=_.threadId,h.current&&(h.current.threadIdGuess=_.threadId),g(_.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",_);try{t(_)}catch(V){console.error("[useChatStreamingService] Error in onThreadInfo handler:",V)}return}if(_.type==="heartbeat"){try{l==null||l(_)}catch(V){console.error("[useChatStreamingService] Error in onHeartbeat handler:",V)}return}if(_.type==="error"){const V=_;if(V.error_type==="auth_error"||V.code==="TOKEN_EXPIRED"||((z=V.message)==null?void 0:z.includes("token"))||((B=V.message)==null?void 0:B.includes("401"))||((O=V.message)==null?void 0:O.includes("unauthorized"))||((H=V.message)==null?void 0:H.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",V.message);try{a==null||a(V.message)}catch(F){console.warn("[useChatStreamingService] onAuthError handler failed",F)}}}const D=_.threadId??(_.type==="state_history"?_.threadId:void 0)??d.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(_.type==="state_history"&&(d.current=D??d.current),By(_)){_.type==="checkpoint"||_.type==="state_history"?g(D??null):m(D??null,_);try{n(_)}catch(V){console.error("[useChatStreamingService] Error in onMessageEvent handler:",V)}return}try{r==null||r(_)}catch(V){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",V)}},[m,g,n,o,t,r]),{stream:w,stop:C,isStreaming:T,error:k,setToken:S}=Qc({baseUrl:e,token:void 0}),E=b.useCallback((_,P)=>{c.current=null,d.current=_.threadId??null,h.current={request:_,callbacks:P,manualStop:!1,threadIdGuess:_.threadId??null},w(_,x,{onOpen:P==null?void 0:P.onOpen,onError:D=>{var z;(z=P==null?void 0:P.onError)==null||z.call(P,D)},onGap:(P==null?void 0:P.onGap)??o,onConnectionError:D=>{var z;i==null||i(D),(z=P==null?void 0:P.onConnectionError)==null||z.call(P,D)},onAuthError:D=>{var z;a==null||a(D),(z=P==null?void 0:P.onAuthError)==null||z.call(P,D)},onHeartbeat:D=>{var z;try{l==null||l(D)}catch(B){console.warn("[useChatStreamingService] onHeartbeat handler failed",B)}try{(z=P==null?void 0:P.onHeartbeat)==null||z.call(P,D)}catch(B){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",B)}},onClosed:D=>{var H,R,V,$;const z=((H=h.current)==null?void 0:H.manualStop)??!1,B=d.current??((R=h.current)==null?void 0:R.threadIdGuess)??((V=D.lastStateHistory)==null?void 0:V.threadId)??null;(D.reason==="complete"||D.reason==="aborted"&&z)&&g(B);const O={...D,threadId:B,manualStop:z};try{s==null||s(O)}catch(F){console.warn("[useChatStreamingService] onStreamClosed handler failed",F)}try{($=P==null?void 0:P.onClosed)==null||$.call(P,O)}catch(F){console.warn("[useChatStreamingService] downstream onClosed handler failed",F)}h.current&&(h.current=null)}})},[g,x,a,i,l,o,s,w]),j=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),C()},[C]);return b.useMemo(()=>({startStream:E,stop:j,isStreaming:T,error:k,setAuthToken:S,replayBufferedEvents:y}),[E,j,T,k,S,y])}const tu=50,Jy=750,ea="chat-history@1",Zy=5,Qy=1e3,ex=15e3,fs=300;function nu(e,t=fs){if(typeof window<"u"&&"requestIdleCallback"in window)try{window.requestIdleCallback(e,{timeout:t});return}catch{}window.setTimeout(e,t)}function Cr(){return typeof window<"u"&&typeof window.localStorage<"u"}function ta(e){if(!Cr())return null;try{return window.localStorage.getItem(e)}catch{return null}}function na(e,t){if(!Cr())return!1;try{return window.localStorage.setItem(e,t),!0}catch{return!1}}function ra(e){if(Cr())try{window.localStorage.removeItem(e)}catch{}}function oa(e){return e==null?e:{...e}}function tx(e){return e==null?e:{...e}}function nx(e){if(Array.isArray(e))return e.slice();if(e==null)return e}function rx(e){if(Array.isArray(e))return e.map(t=>({...t}));if(e==null)return e}function un(e,t={}){const n=t.cloneMessages??!1,r=Array.isArray(e==null?void 0:e.messages)?e.messages:[],o=oa(e==null?void 0:e.metadata),s=oa(e==null?void 0:e.config),i=oa(e==null?void 0:e.parentConfig),a=nx(e==null?void 0:e.next),l=rx(e==null?void 0:e.tasks),c=tx(e==null?void 0:e.values),d={checkpointId:(e==null?void 0:e.checkpointId)??null,checkpointNs:(e==null?void 0:e.checkpointNs)??null,createdAt:(e==null?void 0:e.createdAt)??null,parentId:(e==null?void 0:e.parentId)??null,branchLabel:(e==null?void 0:e.branchLabel)??null,lastMessageId:(e==null?void 0:e.lastMessageId)??null,messagesLen:typeof(e==null?void 0:e.messagesLen)=="number"?e.messagesLen:r.length,hasMessages:typeof(e==null?void 0:e.hasMessages)=="boolean"?e.hasMessages:r.length>0,messages:n?r.slice():r,nextCursor:(e==null?void 0:e.nextCursor)??null,nextCursorNs:(e==null?void 0:e.nextCursorNs)??null,interrupt:(e==null?void 0:e.interrupt)??null};return o!==void 0&&(d.metadata=o),s!==void 0&&(d.config=s),i!==void 0&&(d.parentConfig=i),a!==void 0&&(d.next=a),l!==void 0&&(d.tasks=l),c!==void 0&&(d.values=c),d}function ox(e){var t;for(let n=e.length-1;n>=0;n--){const r=((t=e[n])==null?void 0:t.content)??[];for(let o=r.length-1;o>=0;o--){const s=r[o];if((s==null?void 0:s.type)==="interrupt"){const i=s.id;return{id:(typeof i=="string"?i:null)??`interrupt-${e[n].id??o}`,value:s.value}}}}return null}function ru(e,t){if(!e&&!t)return!0;if(!e||!t||e.id!==t.id)return!1;try{return JSON.stringify(e.value)===JSON.stringify(t.value)}catch{return e.value===t.value}}function sa(e,t){return`${e}${t}`}function sx(e,t){const n=ta(sa(e,t));if(!n)return null;try{const r=JSON.parse(n);return typeof(r==null?void 0:r.threadId)!="string"?null:{threadId:r.threadId,snapshot:un(r.snapshot,{cloneMessages:!0}),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0}}catch{return null}}function ix(e,t,n=100){if(!Cr())return;const r=un(t.snapshot,{cloneMessages:!0}),o={threadId:t.threadId,snapshot:{...r,messages:r.messages.slice(-n)},updatedAt:Date.now()},s=sa(e,t.threadId),i=JSON.stringify(o);if(!na(s,i))try{const a=[];for(let l=0;l<window.localStorage.length;l++){const c=window.localStorage.key(l);if(!c||c===s||!c.startsWith(e))continue;const d=window.localStorage.getItem(c);if(!d){a.push({key:c,updatedAt:0});continue}try{const f=JSON.parse(d),h=typeof(f==null?void 0:f.updatedAt)=="number"&&Number.isFinite(f.updatedAt)?f.updatedAt:0;a.push({key:c,updatedAt:h})}catch{a.push({key:c,updatedAt:0})}}a.sort((l,c)=>l.updatedAt-c.updatedAt);for(const l of a)if(window.localStorage.removeItem(l.key),na(s,i))break}catch{}}function ax(e,t){ra(sa(e,t))}function lx(e){if(Cr())try{for(let t=0;t<window.localStorage.length;t++){const n=window.localStorage.key(t);n&&n.startsWith(e)&&window.localStorage.removeItem(n)}}catch{}}function ou(e,t,n){return`${e}__${t??""}__${n??""}`}function hs(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?{...e}:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function cx(e,t){return hs(e,t)}function ux(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function dx(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function su(e,t){const n=hs(e.metadata,t.metadata),r=hs(e.config,t.config),o=hs(e.parentConfig,t.parentConfig),s=ux(e.next,t.next),i=dx(e.tasks,t.tasks),a=cx(e.values,t.values),l={};return n!==void 0&&(l.metadata=n??null),r!==void 0&&(l.config=r??null),o!==void 0&&(l.parentConfig=o??null),s!==void 0&&(l.next=s??null),i!==void 0&&(l.tasks=i??null),a!==void 0&&(l.values=a??null),l}function iu(e){return Array.isArray(e)?e.filter(t=>!!(t&&(t.checkpointId||t.checkpointNs))).map(t=>{const n=un(t,{cloneMessages:!0});return{...n,messages:Array.isArray(n.messages)?n.messages:[],values:n.values??null}}):[]}const fx="cachedThreads",hx="v1",ia=200;function px(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}function aa(e,t){return`cachedThreads:v1:${e}:${px(t||"anon")}`}function mx(){const e=ta(fx);if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>{if(!n||typeof n!="object")return!1;const r=n;return typeof r.threadId=="string"&&typeof r.title=="string"}):[]}catch{return[]}}function gx(e){const t=ta(e);if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n.filter(r=>{if(!r||typeof r!="object")return!1;const o=r;return typeof o.threadId=="string"&&typeof o.title=="string"}):[]}catch{return[]}}function la(e,t){na(e,JSON.stringify(t))}function ca(e){const t=gx(e);if(t.length>0)return t;const n=mx();if(n.length>0)try{la(e,n.slice(0,ia))}catch{}return n}function ps(e){const t={},n=[];for(const r of e)!r||typeof r.threadId!="string"||t[r.threadId]||(t[r.threadId]=r,n.push(r.threadId));return{byId:t,order:n}}function ua(e){return e.order.map(t=>e.byId[t]).filter(Boolean)}function yx({currentThreadId:e,currentThreadIdRef:t}){const[n,r]=b.useState([]),o=b.useRef(new Map),s=b.useRef(new Map),i=b.useCallback(m=>{if(!m){r([]);return}const g=o.current.get(m);if(!g||!g.length){r([]);return}r(g.map(y=>un(y,{cloneMessages:!0})))},[]);b.useEffect(()=>{i(e)},[e,i]);const a=b.useCallback((m,g,y)=>{if(!m)return;const x=y==="replace"?[]:o.current.get(m)??[],w=y==="replace"?g:[...g,...x];if(!w.length){y==="replace"&&o.current.set(m,[]),m===t.current&&r([]);return}const C=new Map;for(const k of w){if(!(k!=null&&k.checkpointId))continue;const S=`${k.checkpointId}::${k.checkpointNs??""}`,E=un(k,{cloneMessages:!0}),j=C.get(S);if(!j){C.set(S,E);continue}const _=su(j,E);C.set(S,{...j,..._})}const T=Array.from(C.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});o.current.set(m,T),m===t.current&&i(m)},[t,i]),l=b.useCallback((m,g,y)=>{if(!m)return;const x=s.current.get(m),w=y==="replace"||!x?new Map:new Map(x);if(g&&typeof g=="object")for(const[C,T]of Object.entries(g)){if(!(T!=null&&T.checkpointId))continue;const k=C||Wr(T.checkpointId,T.checkpointNs??null);w.set(k,un(T,{cloneMessages:!0}))}s.current.set(m,w)},[]),c=b.useCallback((m,g)=>{if(!m)return!1;const y=iu(g);if(!y.length)return!1;const x=o.current.get(m)??[],w=new Map,C=(k,{preferExisting:S})=>{for(const E of k){if(!(E!=null&&E.checkpointId)&&!(E!=null&&E.checkpointNs))continue;const j=Wr(E.checkpointId??null,E.checkpointNs??null);j&&(S&&w.has(j)?w.set(j,E):w.has(j)&&S||w.set(j,E))}};C(y,{preferExisting:!1}),C(x,{preferExisting:!0});const T=Array.from(w.values()).sort((k,S)=>{const E=Number.isFinite(Date.parse(k.createdAt??""))?Date.parse(k.createdAt??""):0;return(Number.isFinite(Date.parse(S.createdAt??""))?Date.parse(S.createdAt??""):0)-E});return o.current.set(m,T),m===t.current&&r(T.map(k=>un(k,{cloneMessages:!0}))),!0},[t]),d=b.useCallback(m=>{m&&(o.current.delete(m),s.current.delete(m),m===t.current&&r([]))},[t]),f=b.useCallback(()=>{r([])},[]),h=b.useCallback(m=>m?s.current.get(m)??null:null,[]),p=b.useCallback((m,g)=>{var y;if(m)return(y=s.current.get(m))==null?void 0:y.get(g)},[]);return{threadCheckpoints:n,syncActiveThreadCheckpoints:i,updateCheckpointCache:a,updateCheckpointSnapshots:l,applyCheckpointSummaries:c,clearThreadCaches:d,resetThreadCheckpoints:f,getSnapshotCache:h,getSnapshotFromCache:p}}const au=b.createContext(null),lu=b.createContext(null),cu=b.createContext(null),xx=b.createContext(!1);function vx({children:e,initialThreadId:t=null,autoLoadInitial:n=!0,disableAutoRestore:r=!1,enableFileAgentRouting:o=!1,fileAgentId:s="invoice_reader",onError:i,onAuthError:a,onThreadChange:l}){const{api:c,baseUrl:d}=Gi(),f=b.useMemo(()=>Zn(d),[d]),h=b.useMemo(()=>{try{return new URL(d).host}catch{return"unknown"}},[d]),p=b.useMemo(()=>`threadPayload:${hx}:${h}:`,[h]),m=b.useCallback(I=>sx(p,I),[p]),g=b.useCallback((I,A=100)=>{ix(p,I,A)},[p]),y=b.useCallback(I=>{ax(p,I)},[p]),x=b.useCallback(()=>{lx(p)},[p]),[w,C]=b.useState(()=>{var I;return aa(h,(I=c.getAuthToken)==null?void 0:I.call(c))}),[T,k]=b.useState(()=>{var A;const I=ca(aa(h,(A=c.getAuthToken)==null?void 0:A.call(c)));return ps(I)}),S=b.useMemo(()=>ua(T),[T]),[E,j]=b.useState(t),[_,P]=b.useState(!1),[D,z]=b.useState(!1),[B,O]=b.useState(null),[H,R]=b.useState(null),[V,$]=b.useState(null),F=b.useCallback(()=>{const I=ca(w);b.startTransition(()=>{k(ps(I))})},[w]),[ne,Q]=b.useState(!1),[ye,_e]=b.useState(!1),[J,ue]=b.useState(null),[ke,te]=b.useState(void 0),[L,q]=b.useState(void 0),[ie,ce]=b.useState(void 0),{state:U,dispatch:We,seed:re,prepend:xe,pushUser:Pe,onEvent:$e,reset:rt}=Vc(),Se=b.useRef(E);b.useEffect(()=>{Se.current=E},[E]);const Ye=b.useRef(!1),ot=b.useRef([]),et=b.useRef(null),Xe=b.useRef(null),Ke=b.useRef(new Map),tt=b.useRef(E),Ot=b.useRef(!1),St=b.useRef(null),nt=b.useRef(new Map),yt=b.useRef(new Map),{threadCheckpoints:Nt,syncActiveThreadCheckpoints:st,updateCheckpointCache:Gt,updateCheckpointSnapshots:Yt,applyCheckpointSummaries:Xt,clearThreadCaches:Jt,resetThreadCheckpoints:ft,getSnapshotCache:Ve,getSnapshotFromCache:Mt}=yx({currentThreadId:E,currentThreadIdRef:Se}),_t=b.useCallback(()=>{var K;const I=yt.current;if(I.size<=tu)return;const A=Array.from(I.entries()).sort((fe,le)=>fe[1].timestamp-le[1].timestamp),W=I.size-tu;for(let fe=0;fe<W;fe++){const le=(K=A[fe])==null?void 0:K[0];le&&I.delete(le)}},[]),G=b.useCallback((I,A)=>{if(!I)return null;const W=Array.isArray(I.checkpoints)?I.checkpoints:[];return W.length===0?null:{version:I.version===ea?I.version:ea,threadId:I.threadId??A,checkpoints:W}},[]),Te=b.useCallback((I,A)=>{const{threadId:W,checkpointId:K=null,checkpointNs:fe=null}=I,le=ou(W,K,fe);if(A!=null&&A.force)nt.current.delete(le),yt.current.delete(le);else{if(A!=null&&A.preferCache){const kt=yt.current.get(le);if(kt)return Promise.resolve(kt.result)}const Be=nt.current.get(le);if(Be)return Be}const bt=(async()=>{try{const Be=await c.getStateHistory({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0}),kt=G(Be,W);if(kt)return{payload:kt,usedHistoryApi:!0};throw new Error("History response missing checkpoints")}catch(Be){console.warn("[ChatSessionProvider] getStateHistory failed, falling back to getState:",Be);const kt=await c.getState({threadId:W,checkpointId:K??void 0,checkpointNs:fe??void 0});return{payload:{version:ea,threadId:W,checkpoints:[kt]},usedHistoryApi:!1}}})().then(Be=>(yt.current.set(le,{result:Be,timestamp:Date.now()}),_t(),Be)).finally(()=>{nt.current.get(le)===bt&&nt.current.delete(le)});return nt.current.set(le,bt),bt},[c,G,_t]),ve=b.useCallback((I,A)=>new Promise((W,K)=>{const fe=async()=>{Ye.current=!0;try{await I(),W()}catch(le){K(le)}finally{Ye.current=!1;const le=ot.current.shift();le&&le().catch(()=>{})}};Ye.current?ot.current.push(fe):fe().catch(le=>{K(le)})}),[]),pt=b.useRef(S.length),mt=b.useRef(!1);b.useEffect(()=>{pt.current=S.length},[S.length]),b.useEffect(()=>{const I=U.pendingInterrupt??ox(U.messages);ru(V,I)||$(I??null)},[V,U.messages,U.pendingInterrupt]);const ct=b.useCallback(async()=>{const I=pt.current>0;I||P(!0);try{const A=await c.listThreads();b.startTransition(()=>{k(W=>{const K=ht=>ht.map(bt=>`${bt.threadId}:${bt.updatedAt??""}:${bt.messageCount??""}`).join("|"),fe=ua(W);return K(fe)===K(A)||A.length===0&&fe.length>0&&!mt.current?W:ps(A)})}),O(null),mt.current||(mt.current=!0)}catch(A){i==null||i(String(A)),console.error("[ChatSessionProvider] Failed to refresh threads:",A),O(String(A))}finally{I||P(!1)}},[c,i]),Me=b.useRef(!1),Ut=b.useRef(null),Le=b.useRef(null),xt=b.useRef(""),[Ln,Dt]=b.useState("idle"),fn=b.useRef({attempts:0,timer:null,reason:null}),io=b.useRef(null),ao=b.useRef(0),Lr=b.useRef(()=>{}),Fr=b.useRef(()=>{}),N=b.useRef(()=>{}),Y=I=>{if(!I||typeof I!="object")return!1;const A=I;return A.code==="ECONNABORTED"?!0:(typeof A.message=="string"?A.message.toLowerCase():"").includes("timeout")},ae=b.useCallback(async I=>{const A=await c.listCheckpointSummaries(I);return iu(A??[])},[c]),Ce=b.useCallback((I,A)=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const W=I.map(fe=>`${fe.threadId}:${fe.updatedAt??""}:${fe.messageCount??""}`).join("|");if(I.length===0){try{ra(w)}catch{}xt.current="";return}if(W===xt.current)return;const K=()=>{try{const fe=I.slice(0,ia);la(w,fe),xt.current=W}catch{}finally{Le.current=null}};if(A!=null&&A.immediate){K();return}Le.current=window.setTimeout(()=>{nu(K)},fs)},[w]),Ge=b.useCallback(()=>{Ce(S,{immediate:!0})},[Ce,S]),qe=b.useCallback((I,A,W,K)=>{var Hl;const fe=W??Se.current;if(!fe)return;const le=un(I),ht=fe===Se.current,bt=(K==null?void 0:K.persist)!==!1;if(A==="replace"){if(bt){const Vt={threadId:fe,snapshot:un(I,{cloneMessages:!0})};Ke.current.set(fe,Vt),tt.current=fe}if(!ht)return;re(le.messages,{checkpointId:le.checkpointId??null,checkpointNs:le.checkpointNs??null,pendingInterrupt:le.interrupt??null}),$(le.interrupt??null),ue(le.nextCursor??null),Q(!!le.nextCursor),te(le.checkpointId??void 0),q(le.checkpointNs??void 0),ce(le.nextCursorNs??void 0);return}const Be=Ke.current.get(fe),kt=(Be==null?void 0:Be.snapshot)??null,Ht=Array.isArray(kt==null?void 0:kt.messages)?kt.messages:[],pn=un(kt),Jn=Array.isArray(I==null?void 0:I.messages)?I.messages:[],Wt=new Set,jt=[...Jn,...Ht].filter(Vt=>{const Ul=Vt==null?void 0:Vt.id;return Ul?Wt.has(Ul)?!1:(Wt.add(Ul),!0):!0}),or=su(pn,le),$r={checkpointId:pn.checkpointId??le.checkpointId??null,checkpointNs:pn.checkpointNs??le.checkpointNs??null,createdAt:le.createdAt??pn.createdAt??null,parentId:le.parentId??pn.parentId??null,branchLabel:le.branchLabel??pn.branchLabel??null,lastMessageId:((Hl=jt[jt.length-1])==null?void 0:Hl.id)??null,messagesLen:jt.length,hasMessages:jt.length>0,messages:jt,nextCursor:le.nextCursor??pn.nextCursor??null,nextCursorNs:le.nextCursorNs??pn.nextCursorNs??null,interrupt:pn.interrupt??le.interrupt??null,...or};if(Ke.current.set(fe,{threadId:fe,snapshot:un($r,{cloneMessages:!0})}),!ht)return;Jn.length&&xe(Jn);const lo=I&&Object.prototype.hasOwnProperty.call(I,"checkpointId")?I.checkpointId:void 0,An=I&&Object.prototype.hasOwnProperty.call(I,"checkpointNs")?I.checkpointNs:void 0,zr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursor")?I.nextCursor:void 0,xr=I&&Object.prototype.hasOwnProperty.call(I,"nextCursorNs")?I.nextCursorNs:void 0;ue(Vt=>zr!==void 0?zr??Vt??null:Vt??null),Q(Vt=>zr!==void 0?!!zr:Vt),te(Vt=>lo!==void 0?lo??Vt??void 0:Vt??void 0),q(Vt=>An!==void 0?An??Vt??void 0:Vt??void 0),ce(Vt=>xr!==void 0?xr??void 0:Vt)},[xe,re,$]),He=b.useCallback(I=>{if(I.threadId!=null&&I.threadId!==Se.current)return;const A=un(I.snapshot,{cloneMessages:!0});re(A.messages,{checkpointId:A.checkpointId??null,checkpointNs:A.checkpointNs??null,pendingInterrupt:A.interrupt??null}),$(A.interrupt??null),ue(A.nextCursor??null),Q(!!A.nextCursor),te(A.checkpointId??void 0),q(A.checkpointNs??void 0),ce(A.nextCursorNs??void 0),tt.current=I.threadId,st(I.threadId??Se.current??null)},[re,$,st]),Re=b.useCallback(I=>{if(!I)return;Ke.current.delete(I),y(I),Jt(I);const A=`${I}__`;for(const W of nt.current.keys())W.startsWith(A)&&nt.current.delete(W);for(const W of yt.current.keys())W.startsWith(A)&&yt.current.delete(W);tt.current===I&&(tt.current=null)},[Jt,y]),At=b.useCallback(()=>{const I=Se.current;I&&Re(I),rt([]),Q(!1),_e(!1),ue(null),te(void 0),q(void 0),ce(void 0)},[Re,rt]),gt=b.useCallback(({from:I,to:A})=>{const W=Se.current;W&&console.warn(`[ChatSessionProvider] Stream sequence gap detected (${I} -> ${A}) for thread ${W}`)},[]),Ct=b.useCallback(I=>{const A=I.threadId;console.log("[ChatSessionProvider] 📥 Handling thread_info event:",{threadId:A,title:I.title,created:I.created,currentThreads:S.length});const W={threadId:A,title:I.title||`Thread ${A.slice(0,8)}`,createdAt:I.createdAt||new Date().toISOString(),updatedAt:I.updatedAt||new Date().toISOString(),messageCount:I.messageCount||0};Se.current!==A&&(!Se.current&&U.messages.length<=1&&(Xe.current=A),j(A)),b.startTransition(()=>{k(K=>{const fe=K.byId[A];return fe?fe.title===W.title&&fe.updatedAt===W.updatedAt&&fe.messageCount===W.messageCount?K:{byId:{...K.byId,[A]:W},order:K.order}:{byId:{...K.byId,[A]:W},order:[A,...K.order]}})})},[U.messages.length]),{startStream:Zt,stop:Fn,isStreaming:hn,error:zt,setAuthToken:$n,replayBufferedEvents:Z}=Xy({baseUrl:f,onThreadInfo:Ct,onMessageEvent:$e,onUnhandledEvent:I=>{console.warn(`[ChatSessionProvider] Unhandled stream event: ${I.type}`,I)},onSequenceGap:gt,onStreamClosed:I=>{Lr.current(I)},onConnectionError:I=>{Fr.current(I)},onAuthError:a,onHeartbeat:I=>{N.current(I)}}),se=b.useCallback(()=>{const I=fn.current;I.timer!==null&&(window.clearTimeout(I.timer),I.timer=null),I.reason=null},[]),de=b.useCallback((I,A)=>{Dt("connecting"),Zt(I,{onOpen:W=>{var K;se(),fn.current.attempts=0,Dt("connected"),(K=A==null?void 0:A.onOpen)==null||K.call(A,W)},onError:W=>{var K;(K=A==null?void 0:A.onError)==null||K.call(A,W)},onGap:(A==null?void 0:A.onGap)??gt,onConnectionError:W=>{var K;Fr.current(W),(K=A==null?void 0:A.onConnectionError)==null||K.call(A,W)},onHeartbeat:W=>{var K;N.current(W),(K=A==null?void 0:A.onHeartbeat)==null||K.call(A,W)},onClosed:W=>{var K;Lr.current(W),(K=A==null?void 0:A.onClosed)==null||K.call(A,W)}})},[se,gt,Dt,Zt]),Ie=b.useCallback(()=>{const I=Se.current;if(!I)return null;const A=io.current,W=U.lastCheckpointId??(A==null?void 0:A.lastCheckpointId)??null,K=U.lastCheckpointNs??(A==null?void 0:A.lastCheckpointNs)??null,fe={};return W&&(fe.checkpointId=W),K&&(fe.checkpointNs=K),{threadId:I,checkpointId:W,checkpointNs:K,command:{kind:"resume",value:fe}}},[U.lastCheckpointId,U.lastCheckpointNs]),lt=b.useCallback(I=>{const A=fn.current;if(A.timer!==null)return;if(A.attempts>=Zy){Dt("error");return}A.attempts+=1,A.reason=I;const W=Math.min(Qy*Math.pow(2,A.attempts-1),ex);Dt("reconnecting"),A.timer=window.setTimeout(()=>{A.timer=null,A.reason=null;const K=Ie();if(!K){Dt("error");return}Z(K.threadId??void 0),de(K)},W)},[Ie,Z,Dt,de]),Je=b.useCallback(I=>{var A;if(io.current=I,I.manualStop||I.reason==="complete"){se(),fn.current.attempts=0,Dt("idle");return}if(I.error&&(I.error.includes("token")||I.error.includes("401")||I.error.includes("unauthorized")||I.error.includes("Unauthorized")||I.error.includes("TOKEN_EXPIRED")||I.error.includes("auth_error"))){console.error("[ChatSessionProvider] Auth error detected:",I.error);try{a==null||a(I.error)}catch(K){console.error("[ChatSessionProvider] Error in onAuthError handler:",K)}return}if(I.reason==="error"||I.reason==="aborted"){if((A=I.error)!=null&&A.includes("Stream idle timeout")){console.warn("[ChatSessionProvider] Idle timeout - not scheduling resume (watchdog is generous)");return}lt(`closed:${I.reason}`)}},[se,lt,Dt,a]),it=b.useCallback(I=>{console.warn("[ChatSessionProvider] Stream connection error:",I),lt("connection-error")},[lt]),Bt=b.useCallback(I=>{ao.current=Date.now(),Dt(A=>A==="reconnecting"?"connected":A)},[Dt]);Lr.current=Je,Fr.current=it,N.current=Bt,b.useEffect(()=>()=>{se()},[se]);const sn=b.useCallback(()=>{se(),fn.current.attempts=0,Dt("idle"),Fn()},[se,Dt,Fn]);b.useEffect(()=>{Me.current=hn},[hn]),b.useEffect(()=>{if(!Cr())return;Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);const I=S.map(W=>`${W.threadId}:${W.updatedAt??""}:${W.messageCount??""}`).join("|");if(S.length===0){try{ra(w)}catch{}xt.current="";return}if(I===xt.current)return;const A=()=>{try{const W=S.slice(0,ia);la(w,W),xt.current=I}catch{}finally{Le.current=null}};return Le.current=window.setTimeout(()=>{nu(A),Le.current=null},fs),()=>{Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)}},[S,Ce]),b.useEffect(()=>{var K;const I=c.getAuthToken();$n(I);const A=fe=>{const le=aa(h,fe);St.current!==le&&(St.current=le,Ot.current=!1),C(le);const ht=ca(le);b.startTransition(()=>{k(ps(ht))}),fe&&!Ot.current&&(Ot.current=!0)};A(I);const W=(K=c.onTokenChange)==null?void 0:K.call(c,fe=>{fe!==I&&($n(fe),x(),nt.current.clear(),yt.current.clear(),A(fe))});return()=>{W==null||W()}},[c,h,$n,x]);const Xn=b.useCallback(async I=>{var K;const A=`Thread ${(K=crypto.randomUUID)==null?void 0:K.call(crypto)}`,W={threadId:A,title:I||"New Chat",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0};k(fe=>({byId:{...fe.byId,[A]:W},order:[A,...fe.order]})),j(A);try{const fe=await c.createThread(I),le=typeof fe=="string"?fe:fe.threadId;return k(ht=>{const bt=ht.byId[A];if(!bt)return ht;const Be={...ht.byId};delete Be[A],Be[le]={...bt,threadId:le};const kt=ht.order.map(Ht=>Ht===A?le:Ht);return{byId:Be,order:kt}}),j(le),setTimeout(()=>ct(),10),O(null),le}catch(fe){throw k(le=>{if(!le.byId[A])return le;const ht={...le.byId};delete ht[A];const bt=le.order.filter(Be=>Be!==A);return{byId:ht,order:bt}}),j(null),O(String(fe)),fe}},[c,ct]),Ko=b.useCallback(async I=>{try{await c.deleteThread(I);let A=null;k(W=>{if(!W.byId[I])return W;const K={...W.byId};delete K[I];const fe=W.order.filter(ht=>ht!==I),le={byId:K,order:fe};return A=ua(le),le}),A&&Ce(A,{immediate:!0}),Re(I),Se.current===I&&(Xe.current=I,j(null),Se.current=null,tt.current=null,At()),await ct(),O(null)}catch(A){throw O(String(A)),A}},[c,At,Re,ct,Ce]),ji=b.useCallback(async(I,A)=>{try{await c.updateThread(I,A),k(W=>{const K=W.byId[I];return K?{byId:{...W.byId,[I]:{...K,title:A}},order:W.order}:W}),O(null)}catch(W){throw await ct(),O(String(W)),W}},[c,ct]),Nn=b.useCallback(async(I,A,W,K=!1)=>{await ve(async()=>{if(Xe.current===I&&!K){Xe.current=null;return}if(et.current===I&&!K)return;j(Wt=>Wt===I?Wt:I),Se.current=I;const ht=ou(I,A??null,W??null),bt=yt.current.get(ht),Be=!K&&!A&&!W&&bt&&Date.now()-bt.timestamp<Jy,kt=!K&&!A&&!W;let Ht=!1;if(kt){const Wt=Ke.current.get(I);if(Wt)He(Wt),Ht=!0;else{const jt=m(I);jt&&(Ke.current.set(I,jt),He(jt),Ht=!0)}}const pn=K||!Ht||!!A||!!W,Jn=async Wt=>{Wt&&z(!0),et.current=I;try{const jt=await Te({threadId:I,checkpointId:A,checkpointNs:W},{force:K}),{latest:or,checkpoints:$r,snapshots:lo}=ls(jt.payload);qe(or,"replace",I),Gt(I,$r,"replace"),Yt(I,lo,"replace"),R(null),jt.usedHistoryApi||ae(I).then(An=>{Xt(I,An)}).catch(An=>{console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries:",An)})}catch(jt){if(Y(jt))try{const or=await ae(I),$r=Xt(I,or);if(Q(!1),ue(null),ce(void 0),te(void 0),q(void 0),$r){R("History request timed out. Select a checkpoint to load manually.");return}}catch(or){console.warn("[ChatSessionProvider] Failed to fetch checkpoint summaries after timeout:",or)}throw(!Ht||K||Wt)&&(i==null||i(String(jt))),R(String(jt)),jt}finally{et.current=null,Wt&&z(!1)}};pn?await Jn(!0):kt&&Ht&&!Be&&Jn(!1).catch(Wt=>{console.warn("[ChatSessionProvider] Background refresh failed:",Wt)})},`loadThread-${I}`)},[He,Xt,qe,ve,ae,Te,Y,i,Gt,Yt]),Pi=b.useCallback(async()=>{await ve(async()=>{const I=Se.current;I&&Re(I),Xe.current=null,j(null),Se.current=null,tt.current=null,At(),te(void 0),q(void 0),ce(void 0),ft();try{localStorage.removeItem("lastThreadId")}catch(A){console.warn("[ChatSessionProvider] Failed to clear lastThreadId:",A)}},"clearCurrentThread")},[At,Re,ve,ft]),Hm=b.useCallback(async(I,A)=>{const W=Se.current;if(!W)throw new Error("No active thread");const K=Wr(I,A??null),fe=Mt(W,K);if(fe){await ve(async()=>{qe(fe,"replace",W,{persist:!1})},`navigateToCheckpoint-${W}-${K}`);return}await Nn(W,I,A??void 0,!0)},[qe,ve,Mt,Nn]),Um=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");await Nn(Se.current,void 0,void 0,!0)},[Nn]),Wm=b.useCallback(async()=>{if(!Se.current)throw new Error("No active thread");if(ye||!ne)return;const I=J;if(I){_e(!0);try{const A=Se.current,W=await Te({threadId:A,checkpointId:I??ke??null,checkpointNs:ie??L??null}),{latest:K,checkpoints:fe,snapshots:le}=ls(W.payload),ht=Ve(A);let bt=fe.length>0;if(bt&&ht&&ht.size>0&&(bt=fe.some(Be=>{if(!(Be!=null&&Be.checkpointId))return!1;const kt=Wr(Be.checkpointId,Be.checkpointNs??null);return!ht.has(kt)})),!bt){ue(null),ce(void 0),Q(!1),R(null);return}if(qe(K,"prepend",A??void 0),A&&(Gt(A,fe,"prepend"),Yt(A,le,"prepend"),!W.usedHistoryApi))try{const Be=await ae(A);Xt(A,Be)}catch(Be){console.warn("[ChatSessionProvider] Failed to refresh checkpoint summaries during prepend:",Be)}R(null)}catch(A){throw R(String(A)),A}finally{_e(!1)}}},[qe,Te,Ve,ne,ke,L,ie,J,ae,Xt,ye,Gt,Yt]),Vm=b.useCallback(I=>{if(I!=null&&I.threadId){if(I.checkpointId){const A=Wr(I.checkpointId,I.checkpointNs??null),W=un({...I,interrupt:I.interrupt??null},{cloneMessages:!0});Yt(I.threadId,{[A]:W},"prepend")}qe(I,"replace",I.threadId)}},[qe,Yt]),qo=b.useCallback(async(I,A)=>{var zr;const W=Se.current,K=(I==null?void 0:I.text)??"",fe=(I==null?void 0:I.attachments)??[],le=fe.length?fe:(A==null?void 0:A.attachments)??[],ht=I==null?void 0:I.messageAdditionalKwargs,bt={...(A==null?void 0:A.payloadExtras)??{},...(I==null?void 0:I.payload)??{}};if(!W&&!Object.keys(bt).length&&le.length===0&&!K.trim()){console.warn("[ChatSessionProvider] Nothing to submit - skipping");return}!W&&!bt.messages&&console.warn("[ChatSessionProvider] No thread ID - message will create new thread");const{contentParts:Be,filesInfo:kt}=await Ty(c,le),Ht=[...Be];K&&K.trim()&&Ht.push({type:"text",text:K.trim()});const pn=!!W,Jn=pn?(A==null?void 0:A.checkpointId)??U.lastCheckpointId??void 0:void 0,Wt=pn?(A==null?void 0:A.checkpointNs)??U.lastCheckpointNs??void 0:void 0,jt={id:((zr=crypto.randomUUID)==null?void 0:zr.call(crypto))||`user-${Date.now()}`,role:"user",content:Ht,createdAt:new Date().toISOString(),...Jn!=null?{checkpointId:Jn}:{},...Wt!=null?{checkpointNs:Wt}:{}};ht&&Object.keys(ht).length&&(jt.additionalKwargs={...jt.additionalKwargs??{},...ht}),Ht.length>0&&Pe(jt);const or={...jt,content:Ht},$r=le.length>0,lo={messages:Ht.length>0?[or]:[],files_info:kt,...o&&$r&&s?{active_agent:s}:{},...bt},An={threadId:W??null,payload:lo,checkpointId:Jn??null,checkpointNs:Wt??null,nodeFilter:(A==null?void 0:A.nodeFilter)??null,config:A==null?void 0:A.config,command:(A==null?void 0:A.command)??null};An.threadId||delete An.threadId,An.command||delete An.command,de(An,{onError:xr=>{console.warn("[ChatSessionProvider] Stream error:",xr)},onOpen:({threadId:xr})=>{!Se.current&&xr&&(U.messages.length<=1&&(Xe.current=xr),j(xr))},onGap:gt})},[c,o,s,gt,U.lastCheckpointId,U.lastCheckpointNs,U.messages.length,Pe,de]),Km=b.useCallback(async(I,A,W)=>{if(!Se.current)throw new Error("No active thread to handle interrupt");const fe=A?W??!0:!1;try{try{We({type:"interrupt_response",payload:{interruptId:I}})}catch(le){console.warn("[ChatSessionProvider] optimistic interrupt_response dispatch failed:",le)}await qo({payload:{}},{checkpointId:U.lastCheckpointId??void 0,checkpointNs:U.lastCheckpointNs??void 0,command:{kind:"resume",value:fe}}),$(null)}catch(le){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${I}:`,le),le}},[We,U.lastCheckpointId,U.lastCheckpointNs,qo]);b.useEffect(()=>{if(l==null||l(E),E)try{localStorage.setItem("lastThreadId",E)}catch(I){console.warn("[ChatSessionProvider] Failed to persist lastThreadId:",I)}},[E,l]),b.useEffect(()=>((async()=>{try{if(!r&&!t)try{const A=localStorage.getItem("lastThreadId");A&&(j(A),n&&await Nn(A))}catch(A){console.warn("[ChatSessionProvider] Failed to restore last thread:",A)}else if(t&&n)await Nn(t);else try{await ct()}catch(A){console.error("[ChatSessionProvider] Failed to refresh threads (background):",A)}}catch(A){console.error("[ChatSessionProvider] Initialization failed:",A),i==null||i(String(A))}})(),()=>{}),[]),b.useEffect(()=>{const I=Se.current;if(!I||tt.current!==I)return;U.messages.length&&U.messages[U.messages.length-1];const A=un({checkpointId:U.lastCheckpointId??null,checkpointNs:U.lastCheckpointNs??null,messages:U.messages.slice(),nextCursor:J??null,nextCursorNs:ie??null,interrupt:U.pendingInterrupt??V??null}),W=Ke.current.get(I),K=W==null?void 0:W.snapshot,fe=!K||K.messages.length!==A.messages.length||K.messages.some((Be,kt)=>{var Ht;return(Be==null?void 0:Be.id)!==((Ht=A.messages[kt])==null?void 0:Ht.id)}),le=((K==null?void 0:K.checkpointId)??null)!==A.checkpointId||((K==null?void 0:K.checkpointNs)??null)!==A.checkpointNs,ht=((K==null?void 0:K.nextCursor)??null)!==A.nextCursor||((K==null?void 0:K.nextCursorNs)??null)!==A.nextCursorNs,bt=!ru((K==null?void 0:K.interrupt)??null,A.interrupt??null);if(fe||le||ht||bt){const Be={threadId:I,snapshot:A};Ke.current.set(I,Be),Ut.current&&window.clearTimeout(Ut.current),Ut.current=window.setTimeout(()=>{try{g(Be,100)}catch(kt){console.warn("[ChatSessionProvider] Failed to persist thread payload:",kt)}},fs)}},[J,ie,U.lastCheckpointId,U.lastCheckpointNs,U.messages,U.pendingInterrupt,V,g]);const dT=b.useMemo(()=>({threads:S,currentThreadId:E,setCurrentThreadId:j,isLoading:_,error:B,actions:{createThread:Xn,deleteThread:Ko,renameThread:ji,refreshThreads:()=>ct()},persistThreadsCache:Ge,hydrateFromCache:F}),[S,E,_,B,Xn,Ko,ji,ct,Ge,F,j]),fT=b.useMemo(()=>{const I=U.lastBranch??null,A=U.assemblingId??null,W=I||A?{branchLabel:(I==null?void 0:I.branchLabel)??null,lastBranch:I,assemblingMessageId:A}:null;return{threadId:E,messages:U.messages,interrupt:V,checkpoint:{id:U.lastCheckpointId??null,namespace:U.lastCheckpointNs??null},checkpoints:Nt,metadata:W,isLoading:D,isHistoryLoading:ye,error:H,hasMore:ne,loadOlder:Wm,seedFromSnapshot:Vm,clearState:At,navigateToCheckpoint:Hm,returnToLatest:Um,loadThread:Nn,clearThread:Pi,respondToInterrupt:Km}},[Pi,At,E,V,ne,ye,D,Wm,Nn,U.assemblingId,U.lastBranch,U.lastCheckpointId,U.lastCheckpointNs,U.messages,Hm,Km,Um,Vm,H,Nt]),hT=b.useMemo(()=>({isStreaming:hn,error:zt,connectionState:Ln,submit:qo,send:qo,stop:sn,setAuthToken:$n}),[Ln,hn,zt,sn,qo,$n]);return u.jsx(xx.Provider,{value:!0,children:u.jsx(cu.Provider,{value:hT,children:u.jsx(au.Provider,{value:dT,children:u.jsx(lu.Provider,{value:fT,children:e})})})})}function ms(){const e=b.useContext(au);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function gs(){const e=b.useContext(lu);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function uu(){const e=b.useContext(cu);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function ys({children:e,apiConfig:t,initialThreadId:n=null,autoLoadInitial:r=!0,disableAutoRestore:o=!1,enableFileAgentRouting:s=!1,fileAgentId:i="invoice_reader",onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Cy,{apiConfig:t,children:u.jsx(vx,{initialThreadId:n,autoLoadInitial:r,disableAutoRestore:o,enableFileAgentRouting:s,fileAgentId:i,onError:a,onAuthError:l,onThreadChange:c,children:e})})}function oe(...e){return Xm.twMerge(Ym.clsx(e))}const wx=Go.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"}}),ut=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?vr.Slot:"button";return u.jsx(i,{className:oe(wx({variant:t,size:n,className:e})),ref:s,...o})});ut.displayName="Button";const du=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:oe("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}));du.displayName="Textarea";function fu({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const m=i!==void 0,[g,y]=b.useState(e),x=(m?i:g)??"",[w,C]=b.useTransition(),T=b.useRef(null),k=b.useRef(0),S=b.useRef(null);b.useEffect(()=>{m||(y(e??""),S.current=null,T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`))},[e,t,m]);const E=b.useCallback(()=>{const H=T.current;H&&(H.style.height="auto",H.style.height=`${H.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const j=b.useCallback((H,{fromUser:R})=>{m||y(H),R&&(a==null||a(H))},[m,a]),_=b.useCallback(async H=>{H&&H.preventDefault();const R=(x??"").trim();if(!R&&!p)return;const V=++k.current;S.current={id:V,shouldClear:!0},C(()=>{var $,F,ne;try{const Q=l(R);Q&&typeof Q.then=="function"?Q.then(()=>{var ye,_e;((ye=S.current)==null?void 0:ye.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((_e=S.current)==null?void 0:_e.id)===V&&(S.current=null)}).catch(()=>{var ye;((ye=S.current)==null?void 0:ye.id)===V&&(S.current=null)}):((($=S.current)==null?void 0:$.id)===V&&S.current.shouldClear&&(m||(y(""),T.current&&(T.current.style.height="auto"),a==null||a(""))),((F=S.current)==null?void 0:F.id)===V&&(S.current=null))}catch{((ne=S.current)==null?void 0:ne.id)===V&&(S.current=null)}})},[x,l,p,m,a]),P=b.useCallback(H=>{const R=H.target.value;j(R,{fromUser:!0}),S.current&&(S.current.shouldClear=!1),T.current&&(T.current.style.height="auto",T.current.style.height=`${T.current.scrollHeight}px`)},[j]),D=b.useCallback(H=>{H.key==="Enter"&&!H.shiftKey?(H.preventDefault(),_()):H.key==="Escape"&&t&&(H.preventDefault(),c==null||c())},[_,t,c]),O=`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 u.jsx("form",{onSubmit:H=>void _(H),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(du,{ref:T,value:x,onChange:P,onKeyDown:D,placeholder:t?"Edit your message...":n,className:O,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(ut,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(he.Square,{size:16})}):u.jsx(ut,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!p||w,children:u.jsx(he.Send,{size:16})})})]})})}const bx=b.memo(fu);function ge(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 hu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function da(...e){return t=>{let n=!1;const r=e.map(o=>{const s=hu(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():hu(e[o],null)}}}}function Ze(...e){return v.useCallback(da(...e),e)}function Sx(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Qn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:h,children:p,...m}=f,g=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,y=v.useMemo(()=>m,Object.values(m));return u.jsx(g.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var g;const p=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,m=v.useContext(p);if(m)return m;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Cx(o,...t)]}function Cx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},kx=v[" useInsertionEffect ".trim().toString()]||Kt;function Vr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=Tx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const h=Ex(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function Tx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return kx(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Ex(e){return typeof e=="function"}var Ix=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],De=Ix.reduce((e,t)=>{const n=vr.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function pu(e,t){e&&Yo.flushSync(()=>e.dispatchEvent(t))}function fa(e){const t=e+"CollectionProvider",[n,r]=Qn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=g=>{const{scope:y,children:x}=g,w=b.useRef(null),C=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:C,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=vr.createSlot(a),c=b.forwardRef((g,y)=>{const{scope:x,children:w}=g,C=s(a,x),T=Ze(y,C.collectionRef);return u.jsx(l,{ref:T,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=vr.createSlot(d),p=b.forwardRef((g,y)=>{const{scope:x,children:w,...C}=g,T=b.useRef(null),k=Ze(y,T),S=s(d,x);return b.useEffect(()=>(S.itemMap.set(T,{ref:T,...C}),()=>void S.itemMap.delete(T))),u.jsx(h,{[f]:"",ref:k,children:w})});p.displayName=d;function m(g){const y=s(e+"CollectionConsumer",g);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const C=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((S,E)=>C.indexOf(S.ref.current)-C.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},m,r]}var Nx=v.createContext(void 0);function xs(e){const t=v.useContext(Nx);return e||t||"ltr"}function qt(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ax(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var _x="DismissableLayer",ha="dismissableLayer.update",jx="dismissableLayer.pointerDownOutside",Px="dismissableLayer.focusOutside",mu,gu=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),vs=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(gu),[d,f]=v.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=v.useState({}),m=Ze(t,E=>f(E)),g=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=g.indexOf(y),w=d?g.indexOf(d):-1,C=c.layersWithOutsidePointerEventsDisabled.size>0,T=w>=x,k=Mx(E=>{const j=E.target,_=[...c.branches].some(P=>P.contains(j));!T||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),S=Dx(E=>{const j=E.target;[...c.branches].some(P=>P.contains(j))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return Ax(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(mu=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),yu(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=mu)}},[d,h,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),yu())},[d,c]),v.useEffect(()=>{const E=()=>p({});return document.addEventListener(ha,E),()=>document.removeEventListener(ha,E)},[]),u.jsx(De.div,{...l,ref:m,style:{pointerEvents:C?T?"auto":"none":void 0,...e.style},onFocusCapture:ge(e.onFocusCapture,S.onFocusCapture),onBlurCapture:ge(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:ge(e.onPointerDownCapture,k.onPointerDownCapture)})});vs.displayName=_x;var Rx="DismissableLayerBranch",Ox=v.forwardRef((e,t)=>{const n=v.useContext(gu),r=v.useRef(null),o=Ze(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(De.div,{...e,ref:o})});Ox.displayName=Rx;function Mx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){xu(jx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Dx(e,t=globalThis==null?void 0:globalThis.document){const n=qt(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&xu(Px,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 yu(){const e=new CustomEvent(ha);document.dispatchEvent(e)}function xu(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?pu(o,s):o.dispatchEvent(s)}var pa=0;function ma(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??vu()),document.body.insertAdjacentElement("beforeend",e[1]??vu()),pa++,()=>{pa===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),pa--}},[])}function vu(){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 ga="focusScope.autoFocusOnMount",ya="focusScope.autoFocusOnUnmount",wu={bubbles:!1,cancelable:!0},Lx="FocusScope",ws=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=qt(o),d=qt(s),f=v.useRef(null),h=Ze(t,g=>l(g)),p=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let g=function(C){if(p.paused||!a)return;const T=C.target;a.contains(T)?f.current=T:ir(f.current,{select:!0})},y=function(C){if(p.paused||!a)return;const T=C.relatedTarget;T!==null&&(a.contains(T)||ir(f.current,{select:!0}))},x=function(C){if(document.activeElement===document.body)for(const k of C)k.removedNodes.length>0&&ir(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,p.paused]),v.useEffect(()=>{if(a){Cu.add(p);const g=document.activeElement;if(!a.contains(g)){const x=new CustomEvent(ga,wu);a.addEventListener(ga,c),a.dispatchEvent(x),x.defaultPrevented||(Fx(Ux(bu(a)),{select:!0}),document.activeElement===g&&ir(a))}return()=>{a.removeEventListener(ga,c),setTimeout(()=>{const x=new CustomEvent(ya,wu);a.addEventListener(ya,d),a.dispatchEvent(x),x.defaultPrevented||ir(g??document.body,{select:!0}),a.removeEventListener(ya,d),Cu.remove(p)},0)}}},[a,c,d,p]);const m=v.useCallback(g=>{if(!n&&!r||p.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,x=document.activeElement;if(y&&x){const w=g.currentTarget,[C,T]=$x(w);C&&T?!g.shiftKey&&x===T?(g.preventDefault(),n&&ir(C,{select:!0})):g.shiftKey&&x===C&&(g.preventDefault(),n&&ir(T,{select:!0})):x===w&&g.preventDefault()}},[n,r,p.paused]);return u.jsx(De.div,{tabIndex:-1,...i,ref:h,onKeyDown:m})});ws.displayName=Lx;function Fx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(ir(r,{select:t}),document.activeElement!==n)return}function $x(e){const t=bu(e),n=Su(t,e),r=Su(t.reverse(),e);return[n,r]}function bu(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 Su(e,t){for(const n of e)if(!zx(n,{upTo:t}))return n}function zx(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 Bx(e){return e instanceof HTMLInputElement&&"select"in e}function ir(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Bx(e)&&t&&e.select()}}var Cu=Hx();function Hx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ku(e,t),e.unshift(t)},remove(t){var n;e=ku(e,t),(n=e[0])==null||n.resume()}}}function ku(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Ux(e){return e.filter(t=>t.tagName!=="A")}var Wx=v[" useId ".trim().toString()]||(()=>{}),Vx=0;function er(e){const[t,n]=v.useState(Wx());return Kt(()=>{n(r=>r??String(Vx++))},[e]),t?`radix-${t}`:""}const Kx=["top","right","bottom","left"],ar=Math.min,mn=Math.max,bs=Math.round,Ss=Math.floor,Bn=e=>({x:e,y:e}),qx={left:"right",right:"left",bottom:"top",top:"bottom"},Gx={start:"end",end:"start"};function xa(e,t,n){return mn(e,ar(t,n))}function tr(e,t){return typeof e=="function"?e(t):e}function nr(e){return e.split("-")[0]}function Kr(e){return e.split("-")[1]}function va(e){return e==="x"?"y":"x"}function wa(e){return e==="y"?"height":"width"}const Yx=new Set(["top","bottom"]);function Hn(e){return Yx.has(nr(e))?"y":"x"}function ba(e){return va(Hn(e))}function Xx(e,t,n){n===void 0&&(n=!1);const r=Kr(e),o=ba(e),s=wa(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Cs(i)),[i,Cs(i)]}function Jx(e){const t=Cs(e);return[Sa(e),t,Sa(t)]}function Sa(e){return e.replace(/start|end/g,t=>Gx[t])}const Tu=["left","right"],Eu=["right","left"],Zx=["top","bottom"],Qx=["bottom","top"];function ev(e,t,n){switch(e){case"top":case"bottom":return n?t?Eu:Tu:t?Tu:Eu;case"left":case"right":return t?Zx:Qx;default:return[]}}function tv(e,t,n,r){const o=Kr(e);let s=ev(nr(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Sa)))),s}function Cs(e){return e.replace(/left|right|bottom|top/g,t=>qx[t])}function nv(e){return{top:0,right:0,bottom:0,left:0,...e}}function Iu(e){return typeof e!="number"?nv(e):{top:e,right:e,bottom:e,left:e}}function ks(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 Nu(e,t,n){let{reference:r,floating:o}=e;const s=Hn(t),i=ba(t),a=wa(i),l=nr(t),c=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(l){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(Kr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const rv=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=Nu(c,r,l),h=r,p={},m=0;for(let g=0;g<a.length;g++){const{name:y,fn:x}=a[g],{x:w,y:C,data:T,reset:k}=await x({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=C??f,p={...p,[y]:{...p[y],...T}},k&&m<=50&&(m++,typeof k=="object"&&(k.placement&&(h=k.placement),k.rects&&(c=k.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=Nu(c,h,l)),g=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function xo(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=tr(t,e),m=Iu(p),y=a[h?f==="floating"?"reference":"floating":f],x=ks(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,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},k=ks(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:C,strategy:l}):w);return{top:(x.top-k.top+m.top)/T.y,bottom:(k.bottom-x.bottom+m.bottom)/T.y,left:(x.left-k.left+m.left)/T.x,right:(k.right-x.right+m.right)/T.x}}const ov=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=tr(e,t)||{};if(c==null)return{};const f=Iu(d),h={x:n,y:r},p=ba(o),m=wa(p),g=await i.getDimensions(c),y=p==="y",x=y?"top":"left",w=y?"bottom":"right",C=y?"clientHeight":"clientWidth",T=s.reference[m]+s.reference[p]-h[p]-s.floating[m],k=h[p]-s.reference[p],S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=S?S[C]:0;(!E||!await(i.isElement==null?void 0:i.isElement(S)))&&(E=a.floating[C]||s.floating[m]);const j=T/2-k/2,_=E/2-g[m]/2-1,P=ar(f[x],_),D=ar(f[w],_),z=P,B=E-g[m]-D,O=E/2-g[m]/2+j,H=xa(z,O,B),R=!l.arrow&&Kr(o)!=null&&O!==H&&s.reference[m]/2-(O<z?P:D)-g[m]/2<0,V=R?O<z?O-z:O-B:0;return{[p]:h[p]+V,data:{[p]:H,centerOffset:O-H-V,...R&&{alignmentOffset:V}},reset:R}}}),sv=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=tr(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=nr(o),w=Hn(a),C=nr(a)===a,T=await(l.isRTL==null?void 0:l.isRTL(c.floating)),k=h||(C||!g?[Cs(a)]:Jx(a)),S=m!=="none";!h&&S&&k.push(...tv(a,g,m,T));const E=[a,...k],j=await xo(t,y),_=[];let P=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(j[x]),f){const O=Xx(o,i,T);_.push(j[O[0]],j[O[1]])}if(P=[...P,{placement:o,overflows:_}],!_.every(O=>O<=0)){var D,z;const O=(((D=s.flip)==null?void 0:D.index)||0)+1,H=E[O];if(H&&(!(f==="alignment"?w!==Hn(H):!1)||P.every($=>Hn($.placement)===w?$.overflows[0]>0:!0)))return{data:{index:O,overflows:P},reset:{placement:H}};let R=(z=P.filter(V=>V.overflows[0]<=0).sort((V,$)=>V.overflows[1]-$.overflows[1])[0])==null?void 0:z.placement;if(!R)switch(p){case"bestFit":{var B;const V=(B=P.filter($=>{if(S){const F=Hn($.placement);return F===w||F==="y"}return!0}).map($=>[$.placement,$.overflows.filter(F=>F>0).reduce((F,ne)=>F+ne,0)]).sort(($,F)=>$[1]-F[1])[0])==null?void 0:B[0];V&&(R=V);break}case"initialPlacement":R=a;break}if(o!==R)return{reset:{placement:R}}}return{}}}};function Au(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function _u(e){return Kx.some(t=>e[t]>=0)}const iv=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=tr(e,t);switch(r){case"referenceHidden":{const s=await xo(t,{...o,elementContext:"reference"}),i=Au(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:_u(i)}}}case"escaped":{const s=await xo(t,{...o,altBoundary:!0}),i=Au(s,n.floating);return{data:{escapedOffsets:i,escaped:_u(i)}}}default:return{}}}}},ju=new Set(["left","top"]);async function av(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=nr(n),a=Kr(n),l=Hn(n)==="y",c=ju.has(i)?-1:1,d=s&&l?-1:1,f=tr(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:m}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const lv=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await av(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},cv=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:w}=y;return{x,y:w}}},...l}=tr(e,t),c={x:n,y:r},d=await xo(t,l),f=Hn(nr(o)),h=va(f);let p=c[h],m=c[f];if(s){const y=h==="y"?"top":"left",x=h==="y"?"bottom":"right",w=p+d[y],C=p-d[x];p=xa(w,p,C)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=m+d[y],C=m-d[x];m=xa(w,m,C)}const g=a.fn({...t,[h]:p,[f]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[h]:s,[f]:i}}}}}},uv=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=tr(e,t),d={x:n,y:r},f=Hn(o),h=va(f);let p=d[h],m=d[f];const g=tr(a,t),y=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const C=h==="y"?"height":"width",T=s.reference[h]-s.floating[C]+y.mainAxis,k=s.reference[h]+s.reference[C]-y.mainAxis;p<T?p=T:p>k&&(p=k)}if(c){var x,w;const C=h==="y"?"width":"height",T=ju.has(nr(o)),k=s.reference[f]-s.floating[C]+(T&&((x=i.offset)==null?void 0:x[f])||0)+(T?0:y.crossAxis),S=s.reference[f]+s.reference[C]+(T?0:((w=i.offset)==null?void 0:w[f])||0)-(T?y.crossAxis:0);m<k?m=k:m>S&&(m=S)}return{[h]:p,[f]:m}}}},dv=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=tr(e,t),d=await xo(t,c),f=nr(o),h=Kr(o),p=Hn(o)==="y",{width:m,height:g}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=h==="end"?"top":"bottom");const w=g-d.top-d.bottom,C=m-d.left-d.right,T=ar(g-d[y],w),k=ar(m-d[x],C),S=!t.middlewareData.shift;let E=T,j=k;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(j=C),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),S&&!h){const P=mn(d.left,0),D=mn(d.right,0),z=mn(d.top,0),B=mn(d.bottom,0);p?j=m-2*(P!==0||D!==0?P+D:mn(d.left,d.right)):E=g-2*(z!==0||B!==0?z+B:mn(d.top,d.bottom))}await l({...t,availableWidth:j,availableHeight:E});const _=await i.getDimensions(a.floating);return m!==_.width||g!==_.height?{reset:{rects:!0}}:{}}}};function Ts(){return typeof window<"u"}function qr(e){return Pu(e)?(e.nodeName||"").toLowerCase():"#document"}function gn(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Un(e){var t;return(t=(Pu(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Pu(e){return Ts()?e instanceof Node||e instanceof gn(e).Node:!1}function jn(e){return Ts()?e instanceof Element||e instanceof gn(e).Element:!1}function Wn(e){return Ts()?e instanceof HTMLElement||e instanceof gn(e).HTMLElement:!1}function Ru(e){return!Ts()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof gn(e).ShadowRoot}const fv=new Set(["inline","contents"]);function vo(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Pn(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!fv.has(o)}const hv=new Set(["table","td","th"]);function pv(e){return hv.has(qr(e))}const mv=[":popover-open",":modal"];function Es(e){return mv.some(t=>{try{return e.matches(t)}catch{return!1}})}const gv=["transform","translate","scale","rotate","perspective"],yv=["transform","translate","scale","rotate","perspective","filter"],xv=["paint","layout","strict","content"];function Ca(e){const t=ka(),n=jn(e)?Pn(e):e;return gv.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)||yv.some(r=>(n.willChange||"").includes(r))||xv.some(r=>(n.contain||"").includes(r))}function vv(e){let t=lr(e);for(;Wn(t)&&!Gr(t);){if(Ca(t))return t;if(Es(t))return null;t=lr(t)}return null}function ka(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const wv=new Set(["html","body","#document"]);function Gr(e){return wv.has(qr(e))}function Pn(e){return gn(e).getComputedStyle(e)}function Is(e){return jn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function lr(e){if(qr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Ru(e)&&e.host||Un(e);return Ru(t)?t.host:t}function Ou(e){const t=lr(e);return Gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Wn(t)&&vo(t)?t:Ou(t)}function wo(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Ou(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=gn(o);if(s){const a=Ta(i);return t.concat(i,i.visualViewport||[],vo(o)?o:[],a&&n?wo(a):[])}return t.concat(o,wo(o,[],n))}function Ta(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Mu(e){const t=Pn(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Wn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=bs(n)!==s||bs(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Ea(e){return jn(e)?e:e.contextElement}function Yr(e){const t=Ea(e);if(!Wn(t))return Bn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=Mu(t);let i=(s?bs(n.width):n.width)/r,a=(s?bs(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const bv=Bn(0);function Du(e){const t=gn(e);return!ka()||!t.visualViewport?bv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Sv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==gn(e)?!1:t}function kr(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Ea(e);let i=Bn(1);t&&(r?jn(r)&&(i=Yr(r)):i=Yr(e));const a=Sv(s,n,r)?Du(s):Bn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const h=gn(s),p=r&&jn(r)?gn(r):r;let m=h,g=Ta(m);for(;g&&r&&p!==m;){const y=Yr(g),x=g.getBoundingClientRect(),w=Pn(g),C=x.left+(g.clientLeft+parseFloat(w.paddingLeft))*y.x,T=x.top+(g.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=C,c+=T,m=gn(g),g=Ta(m)}}return ks({width:d,height:f,x:l,y:c})}function Ns(e,t){const n=Is(e).scrollLeft;return t?t.left+n:kr(Un(e)).left+n}function Lu(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Ns(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Cv(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=Un(r),a=t?Es(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=Bn(1);const d=Bn(0),f=Wn(r);if((f||!f&&!s)&&((qr(r)!=="body"||vo(i))&&(l=Is(r)),Wn(r))){const p=kr(r);c=Yr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?Lu(i,l):Bn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}}function kv(e){return Array.from(e.getClientRects())}function Tv(e){const t=Un(e),n=Is(e),r=e.ownerDocument.body,o=mn(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=mn(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Ns(e);const a=-n.scrollTop;return Pn(r).direction==="rtl"&&(i+=mn(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const Fu=25;function Ev(e,t){const n=gn(e),r=Un(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=ka();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Ns(r);if(c<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,m=Math.abs(r.clientWidth-f.clientWidth-p);m<=Fu&&(s-=m)}else c<=Fu&&(s+=c);return{width:s,height:i,x:a,y:l}}const Iv=new Set(["absolute","fixed"]);function Nv(e,t){const n=kr(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=Wn(e)?Yr(e):Bn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function $u(e,t,n){let r;if(t==="viewport")r=Ev(e,n);else if(t==="document")r=Tv(Un(e));else if(jn(t))r=Nv(t,n);else{const o=Du(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return ks(r)}function zu(e,t){const n=lr(e);return n===t||!jn(n)||Gr(n)?!1:Pn(n).position==="fixed"||zu(n,t)}function Av(e,t){const n=t.get(e);if(n)return n;let r=wo(e,[],!1).filter(a=>jn(a)&&qr(a)!=="body"),o=null;const s=Pn(e).position==="fixed";let i=s?lr(e):e;for(;jn(i)&&!Gr(i);){const a=Pn(i),l=Ca(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Iv.has(o.position)||vo(i)&&!l&&zu(e,i))?r=r.filter(d=>d!==i):o=a,i=lr(i)}return t.set(e,r),r}function _v(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Es(t)?[]:Av(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=$u(t,d,o);return c.top=mn(f.top,c.top),c.right=ar(f.right,c.right),c.bottom=ar(f.bottom,c.bottom),c.left=mn(f.left,c.left),c},$u(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function jv(e){const{width:t,height:n}=Mu(e);return{width:t,height:n}}function Pv(e,t,n){const r=Wn(t),o=Un(t),s=n==="fixed",i=kr(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=Bn(0);function c(){l.x=Ns(o)}if(r||!r&&!s)if((qr(t)!=="body"||vo(o))&&(a=Is(t)),r){const p=kr(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Lu(o,a):Bn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function Ia(e){return Pn(e).position==="static"}function Bu(e,t){if(!Wn(e)||Pn(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Un(e)===n&&(n=n.ownerDocument.body),n}function Hu(e,t){const n=gn(e);if(Es(e))return n;if(!Wn(e)){let o=lr(e);for(;o&&!Gr(o);){if(jn(o)&&!Ia(o))return o;o=lr(o)}return n}let r=Bu(e,t);for(;r&&pv(r)&&Ia(r);)r=Bu(r,t);return r&&Gr(r)&&Ia(r)&&!Ca(r)?n:r||vv(e)||n}const Rv=async function(e){const t=this.getOffsetParent||Hu,n=this.getDimensions,r=await n(e.floating);return{reference:Pv(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Ov(e){return Pn(e).direction==="rtl"}const Mv={convertOffsetParentRelativeRectToViewportRelativeRect:Cv,getDocumentElement:Un,getClippingRect:_v,getOffsetParent:Hu,getElementRects:Rv,getClientRects:kv,getDimensions:jv,getScale:Yr,isElement:jn,isRTL:Ov};function Uu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Dv(e,t){let n=null,r;const o=Un(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=c;if(a||t(),!h||!p)return;const m=Ss(f),g=Ss(o.clientWidth-(d+h)),y=Ss(o.clientHeight-(f+p)),x=Ss(d),C={rootMargin:-m+"px "+-g+"px "+-y+"px "+-x+"px",threshold:mn(0,ar(1,l))||1};let T=!0;function k(S){const E=S[0].intersectionRatio;if(E!==l){if(!T)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Uu(c,e.getBoundingClientRect())&&i(),T=!1}try{n=new IntersectionObserver(k,{...C,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,C)}n.observe(e)}return i(!0),s}function Lv(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Ea(e),d=o||s?[...c?wo(c):[],...wo(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Dv(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(x=>{let[w]=x;w&&w.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var C;(C=p)==null||C.observe(t)})),n()}),c&&!l&&p.observe(c),p.observe(t));let m,g=l?kr(e):null;l&&y();function y(){const x=kr(e);g&&!Uu(g,x)&&n(),g=x,m=requestAnimationFrame(y)}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,l&&cancelAnimationFrame(m)}}const Fv=lv,$v=cv,zv=sv,Bv=dv,Hv=iv,Wu=ov,Uv=uv,Wv=(e,t,n)=>{const r=new Map,o={platform:Mv,...n},s={...o.platform,_c:r};return rv(e,t,{...o,platform:s})};var Vv=typeof document<"u",Kv=function(){},As=Vv?b.useLayoutEffect:Kv;function _s(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(!_s(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)&&!_s(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Vu(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Ku(e,t){const n=Vu(e);return Math.round(t*n)/n}function Na(e){const t=v.useRef(e);return As(()=>{t.current=e}),t}function qv(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=v.useState(r);_s(h,r)||p(r);const[m,g]=v.useState(null),[y,x]=v.useState(null),w=v.useCallback($=>{$!==S.current&&(S.current=$,g($))},[]),C=v.useCallback($=>{$!==E.current&&(E.current=$,x($))},[]),T=s||m,k=i||y,S=v.useRef(null),E=v.useRef(null),j=v.useRef(d),_=l!=null,P=Na(l),D=Na(o),z=Na(c),B=v.useCallback(()=>{if(!S.current||!E.current)return;const $={placement:t,strategy:n,middleware:h};D.current&&($.platform=D.current),Wv(S.current,E.current,$).then(F=>{const ne={...F,isPositioned:z.current!==!1};O.current&&!_s(j.current,ne)&&(j.current=ne,Yo.flushSync(()=>{f(ne)}))})},[h,t,n,D,z]);As(()=>{c===!1&&j.current.isPositioned&&(j.current.isPositioned=!1,f($=>({...$,isPositioned:!1})))},[c]);const O=v.useRef(!1);As(()=>(O.current=!0,()=>{O.current=!1}),[]),As(()=>{if(T&&(S.current=T),k&&(E.current=k),T&&k){if(P.current)return P.current(T,k,B);B()}},[T,k,B,P,_]);const H=v.useMemo(()=>({reference:S,floating:E,setReference:w,setFloating:C}),[w,C]),R=v.useMemo(()=>({reference:T,floating:k}),[T,k]),V=v.useMemo(()=>{const $={position:n,left:0,top:0};if(!R.floating)return $;const F=Ku(R.floating,d.x),ne=Ku(R.floating,d.y);return a?{...$,transform:"translate("+F+"px, "+ne+"px)",...Vu(R.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:F,top:ne}},[n,a,R.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:B,refs:H,elements:R,floatingStyles:V}),[d,B,H,R,V])}const Gv=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?Wu({element:r.current,padding:o}).fn(n):{}:r?Wu({element:r,padding:o}).fn(n):{}}}},Yv=(e,t)=>({...Fv(e),options:[e,t]}),Xv=(e,t)=>({...$v(e),options:[e,t]}),Jv=(e,t)=>({...Uv(e),options:[e,t]}),Zv=(e,t)=>({...zv(e),options:[e,t]}),Qv=(e,t)=>({...Bv(e),options:[e,t]}),ew=(e,t)=>({...Hv(e),options:[e,t]}),tw=(e,t)=>({...Gv(e),options:[e,t]});var nw="Arrow",qu=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(De.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});qu.displayName=nw;var rw=qu;function Gu(e){const[t,n]=v.useState(void 0);return Kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Aa="Popper",[Yu,js]=Qn(Aa),[ow,Xu]=Yu(Aa),Ju=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(ow,{scope:t,anchor:r,onAnchorChange:o,children:n})};Ju.displayName=Aa;var Zu="PopperAnchor",Qu=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Xu(Zu,n),i=v.useRef(null),a=Ze(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(De.div,{...o,ref:a})});Qu.displayName=Zu;var _a="PopperContent",[sw,iw]=Yu(_a),ed=v.forwardRef((e,t)=>{var te,L,q,ie,ce,U;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:m,...g}=e,y=Xu(_a,n),[x,w]=v.useState(null),C=Ze(t,We=>w(We)),[T,k]=v.useState(null),S=Gu(T),E=(S==null?void 0:S.width)??0,j=(S==null?void 0:S.height)??0,_=r+(s!=="center"?"-"+s:""),P=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},D=Array.isArray(c)?c:[c],z=D.length>0,B={padding:P,boundary:D.filter(lw),altBoundary:z},{refs:O,floatingStyles:H,placement:R,isPositioned:V,middlewareData:$}=qv({strategy:"fixed",placement:_,whileElementsMounted:(...We)=>Lv(...We,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[Yv({mainAxis:o+j,alignmentAxis:i}),l&&Xv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Jv():void 0,...B}),l&&Zv({...B}),Qv({...B,apply:({elements:We,rects:re,availableWidth:xe,availableHeight:Pe})=>{const{width:$e,height:rt}=re.reference,Se=We.floating.style;Se.setProperty("--radix-popper-available-width",`${xe}px`),Se.setProperty("--radix-popper-available-height",`${Pe}px`),Se.setProperty("--radix-popper-anchor-width",`${$e}px`),Se.setProperty("--radix-popper-anchor-height",`${rt}px`)}}),T&&tw({element:T,padding:a}),cw({arrowWidth:E,arrowHeight:j}),h&&ew({strategy:"referenceHidden",...B})]}),[F,ne]=rd(R),Q=qt(m);Kt(()=>{V&&(Q==null||Q())},[V,Q]);const ye=(te=$.arrow)==null?void 0:te.x,_e=(L=$.arrow)==null?void 0:L.y,J=((q=$.arrow)==null?void 0:q.centerOffset)!==0,[ue,ke]=v.useState();return Kt(()=>{x&&ke(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...H,transform:V?H.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ue,"--radix-popper-transform-origin":[(ie=$.transformOrigin)==null?void 0:ie.x,(ce=$.transformOrigin)==null?void 0:ce.y].join(" "),...((U=$.hide)==null?void 0:U.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(sw,{scope:n,placedSide:F,onArrowChange:k,arrowX:ye,arrowY:_e,shouldHideArrow:J,children:u.jsx(De.div,{"data-side":F,"data-align":ne,...g,ref:C,style:{...g.style,animation:V?void 0:"none"}})})})});ed.displayName=_a;var td="PopperArrow",aw={top:"bottom",right:"left",bottom:"top",left:"right"},nd=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=iw(td,r),i=aw[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(rw,{...o,ref:n,style:{...o.style,display:"block"}})})});nd.displayName=td;function lw(e){return e!==null}var cw=e=>({name:"transformOrigin",options:e,fn(t){var y,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=rd(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)+l/2;let m="",g="";return c==="bottom"?(m=i?f:`${h}px`,g=`${-l}px`):c==="top"?(m=i?f:`${h}px`,g=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,g=i?f:`${p}px`):c==="left"&&(m=`${r.floating.width+l}px`,g=i?f:`${p}px`),{data:{x:m,y:g}}}});function rd(e){const[t,n="center"]=e.split("-");return[t,n]}var od=Ju,sd=Qu,id=ed,ad=nd,uw="Portal",Ps=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);Kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ri.createPortal(u.jsx(De.div,{...r,ref:t}),i):null});Ps.displayName=uw;function dw(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Sn=e=>{const{present:t,children:n}=e,r=fw(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=Ze(r.ref,hw(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Sn.displayName="Presence";function fw(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=dw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Rs(r.current);s.current=a==="mounted"?c:"none"},[a]),Kt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=Rs(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const g=Rs(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&g&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},h=p=>{p.target===t&&(s.current=Rs(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Rs(e){return(e==null?void 0:e.animationName)||"none"}function hw(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 ja="rovingFocusGroup.onEntryFocus",pw={bubbles:!1,cancelable:!0},bo="RovingFocusGroup",[Pa,ld,mw]=fa(bo),[gw,cd]=Qn(bo,[mw]),[yw,xw]=gw(bo),ud=v.forwardRef((e,t)=>u.jsx(Pa.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Pa.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(vw,{...e,ref:t})})}));ud.displayName=bo;var vw=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,h=v.useRef(null),p=Ze(t,h),m=xs(s),[g,y]=Vr({prop:i,defaultProp:a??null,onChange:l,caller:bo}),[x,w]=v.useState(!1),C=qt(c),T=ld(n),k=v.useRef(!1),[S,E]=v.useState(0);return v.useEffect(()=>{const j=h.current;if(j)return j.addEventListener(ja,C),()=>j.removeEventListener(ja,C)},[C]),u.jsx(yw,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:g,onItemFocus:v.useCallback(j=>y(j),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(j=>j+1),[]),onFocusableItemRemove:v.useCallback(()=>E(j=>j-1),[]),children:u.jsx(De.div,{tabIndex:x||S===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:ge(e.onMouseDown,()=>{k.current=!0}),onFocus:ge(e.onFocus,j=>{const _=!k.current;if(j.target===j.currentTarget&&_&&!x){const P=new CustomEvent(ja,pw);if(j.currentTarget.dispatchEvent(P),!P.defaultPrevented){const D=T().filter(R=>R.focusable),z=D.find(R=>R.active),B=D.find(R=>R.id===g),H=[z,B,...D].filter(Boolean).map(R=>R.ref.current);hd(H,d)}}k.current=!1}),onBlur:ge(e.onBlur,()=>w(!1))})})}),dd="RovingFocusGroupItem",fd=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=er(),c=s||l,d=xw(dd,n),f=d.currentTabStopId===c,h=ld(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:g}=d;return v.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),u.jsx(Pa.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(De.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:ge(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:ge(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:ge(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=Sw(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.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(y.currentTarget);C=d.loop?Cw(C,T+1):C.slice(T+1)}setTimeout(()=>hd(C))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:g!=null}):i})})});fd.displayName=dd;var ww={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bw(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Sw(e,t,n){const r=bw(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return ww[r]}function hd(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Cw(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var kw=ud,Tw=fd,Ew=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Xr=new WeakMap,Os=new WeakMap,Ms={},Ra=0,pd=function(e){return e&&(e.host||pd(e.parentNode))},Iw=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=pd(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})},Nw=function(e,t,n,r){var o=Iw(t,Array.isArray(e)?e:[e]);Ms[n]||(Ms[n]=new WeakMap);var s=Ms[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),m=p!==null&&p!=="false",g=(Xr.get(h)||0)+1,y=(s.get(h)||0)+1;Xr.set(h,g),s.set(h,y),i.push(h),g===1&&m&&Os.set(h,!0),y===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",h,x)}})};return d(t),a.clear(),Ra++,function(){i.forEach(function(f){var h=Xr.get(f)-1,p=s.get(f)-1;Xr.set(f,h),s.set(f,p),h||(Os.has(f)||f.removeAttribute(r),Os.delete(f)),p||f.removeAttribute(n)}),Ra--,Ra||(Xr=new WeakMap,Xr=new WeakMap,Os=new WeakMap,Ms={})}},Oa=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Ew(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Nw(r,o,n,"aria-hidden")):function(){return null}},Vn=function(){return Vn=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},Vn.apply(this,arguments)};function md(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 Aw(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 Ds="right-scroll-bar-position",Ls="width-before-scroll-bar",_w="with-scroll-bars-hidden",jw="--removed-body-scroll-bar-size";function Ma(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Pw(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Rw=typeof window<"u"?v.useLayoutEffect:v.useEffect,gd=new WeakMap;function Ow(e,t){var n=Pw(null,function(r){return e.forEach(function(o){return Ma(o,r)})});return Rw(function(){var r=gd.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Ma(a,null)}),s.forEach(function(a){o.has(a)||Ma(a,i)})}gd.set(n,e)},[e]),n}function Mw(e){return e}function Dw(e,t){t===void 0&&(t=Mw);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Lw(e){e===void 0&&(e={});var t=Dw(null);return t.options=Vn({async:!0,ssr:!1},e),t}var yd=function(e){var t=e.sideCar,n=md(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,Vn({},n))};yd.isSideCarExport=!0;function Fw(e,t){return e.useMedium(t),yd}var xd=Lw(),Da=function(){},Fs=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:Da,onWheelCapture:Da,onTouchMoveCapture:Da}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,m=e.noIsolation,g=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,C=e.gapMode,T=md(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),k=h,S=Ow([n,t]),E=Vn(Vn({},T),o);return v.createElement(v.Fragment,null,d&&v.createElement(k,{sideCar:xd,removeScrollBar:c,shards:f,noRelative:p,noIsolation:m,inert:g,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:C}),i?v.cloneElement(v.Children.only(a),Vn(Vn({},E),{ref:S})):v.createElement(w,Vn({},E,{className:l,ref:S}),a))});Fs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Fs.classNames={fullWidth:Ls,zeroRight:Ds};var $w=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function zw(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=$w();return t&&e.setAttribute("nonce",t),e}function Bw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Hw(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Uw=function(){var e=0,t=null;return{add:function(n){e==0&&(t=zw())&&(Bw(t,n),Hw(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ww=function(){var e=Uw();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},vd=function(){var e=Ww(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Vw={left:0,top:0,right:0,gap:0},La=function(e){return parseInt(e||"",10)||0},Kw=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[La(n),La(r),La(o)]},qw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Vw;var t=Kw(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])}},Gw=vd(),Jr="data-scroll-locked",Yw=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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teodor-new-chat-ui",
3
- "version": "4.3.158",
3
+ "version": "4.3.159",
4
4
  "description": "React chat UI components with streaming support, tool calls, and modern design",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.esm.js",