teodor-new-chat-ui 4.3.355 → 4.3.356

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.umd.js CHANGED
@@ -32,10 +32,10 @@ React keys must be passed directly to JSX without using spread:
32
32
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[hl]=this[hl]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Dr(i);r[a]||(eg(o,i),r[a]=!0)}return O.isArray(t)?t.forEach(s):s(t),this}};Ft.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),O.reduceDescriptors(Ft.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),O.freezeMethods(Ft);function si(e,t){const n=this||Or,r=t||n,o=Ft.from(r.headers);let s=r.data;return O.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function ml(e){return!!(e&&e.__CANCEL__)}function ur(e,t,n){je.call(this,e??"canceled",je.ERR_CANCELED,t,n),this.name="CanceledError"}O.inherits(ur,je,{__CANCEL__:!0});function gl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new je("Request failed with status code "+n.status,[je.ERR_BAD_REQUEST,je.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function tg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function ng(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,p=0;for(;f!==o;)p+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const h=d&&c-d;return h?Math.round(p*1e3/h):void 0}}function rg(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),f=d-n;f>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-f)))},()=>o&&i(o)]}const So=(e,t,n=3)=>{let r=0;const o=ng(50,250);return rg(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const f={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(f)},n)},xl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},yl=e=>(...t)=>O.asap(()=>e(...t)),og=At.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,At.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(At.origin),At.navigator&&/(msie|trident)/i.test(At.navigator.userAgent)):()=>!0,sg=At.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];O.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),O.isString(r)&&i.push("path="+r),O.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function ig(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ag(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function vl(e,t,n){let r=!ig(t);return e&&(r||n==!1)?ag(e,t):t}const wl=e=>e instanceof Ft?{...e}:e;function qn(e,t){t=t||{};const n={};function r(c,d,f,p){return O.isPlainObject(c)&&O.isPlainObject(d)?O.merge.call({caseless:p},c,d):O.isPlainObject(d)?O.merge({},d):O.isArray(d)?d.slice():d}function o(c,d,f,p){if(O.isUndefined(d)){if(!O.isUndefined(c))return r(void 0,c,f,p)}else return r(c,d,f,p)}function s(c,d){if(!O.isUndefined(d))return r(void 0,d)}function i(c,d){if(O.isUndefined(d)){if(!O.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,f){if(f in t)return r(c,d);if(f in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,f)=>o(wl(c),wl(d),f,!0)};return O.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,p=f(e[d],t[d],d);O.isUndefined(p)&&f!==a||(n[d]=p)}),n}const bl=e=>{const t=qn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Ft.from(i),t.url=ul(vl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),O.isFormData(n)){if(At.hasStandardBrowserEnv||At.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(O.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,f])=>{c.includes(d.toLowerCase())&&i.set(d,f)})}}if(At.hasStandardBrowserEnv&&(r&&O.isFunction(r)&&(r=r(t)),r||r!==!1&&og(t.url))){const l=o&&s&&sg.read(s);l&&i.set(o,l)}return t},lg=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=bl(e);let s=o.data;const i=Ft.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,p,h,g;function m(){h&&h(),g&&g(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function x(){if(!y)return;const S=Ft.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:S,config:e,request:y};gl(function(E){n(E),m()},function(E){r(E),m()},C),y=null}"onloadend"in y?y.onloadend=x:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(x)},y.onabort=function(){y&&(r(new je("Request aborted",je.ECONNABORTED,e,y)),y=null)},y.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new je(C,je.ERR_NETWORK,e,y);T.event=k||null,r(T),y=null},y.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||fl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new je(k,C.clarifyTimeoutError?je.ETIMEDOUT:je.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&O.forEach(i.toJSON(),function(k,C){y.setRequestHeader(C,k)}),O.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([p,g]=So(c,!0),y.addEventListener("progress",p)),l&&y.upload&&([f,h]=So(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",h)),(o.cancelToken||o.signal)&&(d=S=>{y&&(r(!S||S.type?new ur(null,e,y):S),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const w=tg(o.url);if(w&&At.protocols.indexOf(w)===-1){r(new je("Unsupported protocol "+w+":",je.ERR_BAD_REQUEST,e));return}y.send(s||null)})},cg=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof je?d:new ur(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new je(`timeout ${t} of ms exceeded`,je.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>O.asap(a),l}},ug=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},dg=async function*(e,t){for await(const n of fg(e))yield*ug(n,t)},fg=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Sl=(e,t,n,r)=>{const o=dg(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let p=s+=f;n(p)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},Cl=64*1024,{isFunction:Co}=O,pg=(({Request:e,Response:t})=>({Request:e,Response:t}))(O.global),{ReadableStream:Tl,TextEncoder:kl}=O.global,El=(e,...t)=>{try{return!!e(...t)}catch{return!1}},hg=e=>{e=O.merge.call({skipUndefined:!0},pg,e);const{fetch:t,Request:n,Response:r}=e,o=t?Co(t):typeof fetch=="function",s=Co(n),i=Co(r);if(!o)return!1;const a=o&&Co(Tl),l=o&&(typeof kl=="function"?(g=>m=>g.encode(m))(new kl):async g=>new Uint8Array(await new n(g).arrayBuffer())),c=s&&a&&El(()=>{let g=!1;const m=new n(At.origin,{body:new Tl,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return g&&!m}),d=i&&a&&El(()=>O.isReadableStream(new r("").body)),f={stream:d&&(g=>g.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!f[g]&&(f[g]=(m,y)=>{let x=m&&m[g];if(x)return x.call(m);throw new je(`Response type '${g}' is not supported`,je.ERR_NOT_SUPPORT,y)})});const p=async g=>{if(g==null)return 0;if(O.isBlob(g))return g.size;if(O.isSpecCompliantForm(g))return(await new n(At.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(O.isArrayBufferView(g)||O.isArrayBuffer(g))return g.byteLength;if(O.isURLSearchParams(g)&&(g=g+""),O.isString(g))return(await l(g)).byteLength},h=async(g,m)=>{const y=O.toFiniteNumber(g.getContentLength());return y??p(m)};return async g=>{let{url:m,method:y,data:x,signal:w,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:E,headers:N,withCredentials:_="same-origin",fetchOptions:D}=bl(g),B=t||fetch;E=E?(E+"").toLowerCase():"text";let G=cg([w,S&&S.toAbortSignal()],k),V=null;const P=G&&G.unsubscribe&&(()=>{G.unsubscribe()});let M;try{if(T&&c&&y!=="get"&&y!=="head"&&(M=await h(N,x))!==0){let X=new n(m,{method:"POST",body:x,duplex:"half"}),ne;if(O.isFormData(x)&&(ne=X.headers.get("content-type"))&&N.setContentType(ne),X.body){const[ye,Te]=xl(M,So(yl(T)));x=Sl(X.body,Cl,ye,Te)}}O.isString(_)||(_=_?"include":"omit");const A=s&&"credentials"in n.prototype,F={...D,signal:G,method:y.toUpperCase(),headers:N.normalize().toJSON(),body:x,duplex:"half",credentials:A?_:void 0};V=s&&new n(m,F);let L=await(s?B(V,D):B(m,F));const R=d&&(E==="stream"||E==="response");if(d&&(C||R&&P)){const X={};["status","statusText","headers"].forEach(q=>{X[q]=L[q]});const ne=O.toFiniteNumber(L.headers.get("content-length")),[ye,Te]=C&&xl(ne,So(yl(C),!0))||[];L=new r(Sl(L.body,Cl,ye,()=>{Te&&Te(),P&&P()}),X)}E=E||"text";let z=await f[O.findKey(f,E)||"text"](L,g);return!R&&P&&P(),await new Promise((X,ne)=>{gl(X,ne,{data:z,headers:Ft.from(L.headers),status:L.status,statusText:L.statusText,config:g,request:V})})}catch(A){throw P&&P(),A&&A.name==="TypeError"&&/Load failed|fetch/i.test(A.message)?Object.assign(new je("Network Error",je.ERR_NETWORK,g,V),{cause:A.cause||A}):je.from(A,A&&A.code,g,V)}}},mg=new Map,Il=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=mg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:hg(t)),d=c;return c};Il();const ii={http:Lm,xhr:lg,fetch:{get:Il}};O.forEach(ii,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Al=e=>`- ${e}`,gg=e=>O.isFunction(e)||e===null||e===!1,Nl={getAdapter:(e,t)=>{e=O.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!gg(r)&&(o=ii[(a=String(r)).toLowerCase()],o===void 0))throw new je(`Unknown adapter '${a}'`);if(o&&(O.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
33
33
  `+i.map(Al).join(`
34
34
  `):" "+Al(i[0]):"as no adapter specified";throw new je("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:ii};function ai(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ur(null,e)}function _l(e){return ai(e),e.headers=Ft.from(e.headers),e.data=si.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Nl.getAdapter(e.adapter||Or.adapter,e)(e).then(function(r){return ai(e),r.data=si.call(e,e.transformResponse,r),r.headers=Ft.from(r.headers),r},function(r){return ml(r)||(ai(e),r&&r.response&&(r.response.data=si.call(e,e.transformResponse,r.response),r.response.headers=Ft.from(r.response.headers))),Promise.reject(r)})}const jl="1.12.2",To={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{To[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ml={};To.transitional=function(t,n,r){function o(s,i){return"[Axios v"+jl+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new je(o(i," has been removed"+(n?" in "+n:"")),je.ERR_DEPRECATED);return n&&!Ml[i]&&(Ml[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},To.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function xg(e,t,n){if(typeof e!="object")throw new je("options must be an object",je.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new je("option "+s+" must be "+l,je.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new je("Unknown option "+s,je.ERR_BAD_OPTION)}}const ko={assertOptions:xg,validators:To},fn=ko.validators;let Gn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new dl,response:new dl}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
35
- `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=qn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ko.assertOptions(r,{silentJSONParsing:fn.transitional(fn.boolean),forcedJSONParsing:fn.transitional(fn.boolean),clarifyTimeoutError:fn.transitional(fn.boolean)},!1),o!=null&&(O.isFunction(o)?n.paramsSerializer={serialize:o}:ko.assertOptions(o,{encode:fn.function,serialize:fn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ko.assertOptions(n,{baseUrl:fn.spelling("baseURL"),withXsrfToken:fn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&O.merge(s.common,s[n.method]);s&&O.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=Ft.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(l=l&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let d,f=0,p;if(!l){const g=[_l.bind(this),void 0];for(g.unshift(...a),g.push(...c),p=g.length,d=Promise.resolve(n);f<p;)d=d.then(g[f++],g[f++]);return d}p=a.length;let h=n;for(;f<p;){const g=a[f++],m=a[f++];try{h=g(h)}catch(y){m.call(this,y);break}}try{d=_l.call(this,h)}catch(g){return Promise.reject(g)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=qn(this.defaults,t);const n=vl(t.baseURL,t.url,t.allowAbsoluteUrls);return ul(n,t.params,t.paramsSerializer)}};O.forEach(["delete","get","head","options"],function(t){Gn.prototype[t]=function(n,r){return this.request(qn(r||{},{method:t,url:n,data:(r||{}).data}))}}),O.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(qn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Gn.prototype[t]=n(),Gn.prototype[t+"Form"]=n(!0)});let yg=class Gh{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Gh(function(o){t=o}),cancel:t}}};function vg(e){return function(n){return e.apply(null,n)}}function wg(e){return O.isObject(e)&&e.isAxiosError===!0}const li={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(li).forEach(([e,t])=>{li[t]=e});function Pl(e){const t=new Gn(e),n=Ya(Gn.prototype.request,t);return O.extend(n,Gn.prototype,t,{allOwnKeys:!0}),O.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pl(qn(e,o))},n}const yt=Pl(Or);yt.Axios=Gn,yt.CanceledError=ur,yt.CancelToken=yg,yt.isCancel=ml,yt.VERSION=jl,yt.toFormData=wo,yt.AxiosError=je,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=vg,yt.isAxiosError=wg,yt.mergeConfig=qn,yt.AxiosHeaders=Ft,yt.formToJSON=e=>pl(O.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Nl.getAdapter,yt.HttpStatusCode=li,yt.default=yt;const{Axios:VT,AxiosError:KT,CanceledError:qT,isCancel:GT,CancelToken:YT,VERSION:XT,all:JT,Cancel:ZT,isAxiosError:QT,spread:ek,toFormData:tk,AxiosHeaders:nk,HttpStatusCode:rk,formToJSON:ok,getAdapter:sk,mergeConfig:ik}=yt,Rl=typeof window<"u"?window.__API_BASE_URL__:void 0,Ol=Rl?Cn(Rl):void 0;function Cn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Eo=null;const ci=new Set;function Dl(){return Eo}function Io(e){Eo=e,ci.forEach(t=>t(e))}function Ll(e){return ci.add(e),()=>ci.delete(e)}const bg=3e4,Sg=9e4,qt=yt.create({...Ol?{baseURL:Ol}:{},timeout:bg,withCredentials:!0});qt.interceptors.request.use(e=>(Eo&&(e.headers.Authorization=`Bearer ${Eo}`),e)),qt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),Io(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Gt(e,t){return qt.defaults.baseURL?(await qt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ui(e,t,n){return qt.defaults.baseURL?(await qt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function $l(e,t,n){return qt.defaults.baseURL?(await qt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fl(e,t){return qt.defaults.baseURL?(await qt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Yt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){const t=qt.defaults.baseURL;return t?Cn(String(t)):""}updateConfig(t){t.baseUrl&&(qt.defaults.baseURL=Cn(String(t.baseUrl))),t.authToken!==void 0&&Io(t.authToken)}getAuthToken(){return Dl()}setAuthToken(t){Io(t)}onTokenChange(t){return Ll(t)}async listThreads(){const t=await Gt("/threads"),n=Yt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ui("/threads",t?{title:t}:void 0);return Yt(r)}async updateThread(t,n){const r=await $l(`/threads/${t}`,{title:n});return Yt(r)}async deleteThread(t){const n=await Fl(`/threads/${t}`);return Yt(n)}async threadInfo(t){const n=await Gt(`/threads/${t}/info`);return Yt(n)}async listAgents(){const t=await Gt("/agents"),n=Yt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Gt(`/agents/${t}`);return Yt(n)}async getAgentSchema(t){const n=await Gt(`/agents/${t}/schema`);return Yt(n)}async getState(t){const n=await Gt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Yt(n)}async getStateHistory(t){const n=await Gt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sg});return Yt(n)}async cancelRun(t){const n=await ui("/runs/cancel",{threadId:t});return Yt(n)}async listCheckpointSummaries(t){const n=await Gt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Yt(n);return(r==null?void 0:r.items)??[]}}const _n=new Bl,zl=b.createContext(null);function Cg({children:e,apiConfig:t}){const n=_n;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(zl.Provider,{value:r,children:e})}function di(){const e=b.useContext(zl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Tg(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function kg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Tg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Eg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function fi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Ig(e,t){return`${e??""}::${t??""}`}function dr(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!fi(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ng(t),i=Ul(r,0),a=_g(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Ul(e,t){if(!fi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,D)=>Fg(_,D)).filter(_=>!!_),d=Ot(e.config),f=Ot(d==null?void 0:d.configurable),p=dt(f,["checkpoint_id","checkpointId"]),h=dt(f,["checkpoint_ns","checkpointNs"]),g=Ot(e==null?void 0:e.parentConfig),m=Ot(g==null?void 0:g.configurable),y=dt(m,["checkpoint_id","checkpointId"])??null,x=dt(m,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,S=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(_=>_.role==="user")??null,C=Ot(e==null?void 0:e.metadata),T=dt(C,["branch_label","branchLabel"]),E=dt(m,["checkpoint_id","checkpointId"]),N=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:p??null,checkpointNs:h??null,nextCursor:y,nextCursorNs:x,interrupt:Ag(a,c,t),createdAt:S,parentId:E??null,branchLabel:T??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:C??null,config:d??null,parentConfig:g??null,next:N??null,tasks:l??null,values:i??null}}function Ag(e,t,n){const r=Lg(e,n);return r||Dg(t,n)}function Ng(e){const t=new Map;e.forEach((o,s)=>{if(!fi(o))return;const i=Ul(o,s);if(!(i!=null&&i.checkpointId))return;const a=Ig(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Pg(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Wl(s.createdAt??"")-Wl(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function _g(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=dt(i,["label"])??dt(i,["branch_label","branchLabel"])??dt(i,["description"])??"User input",l=Mg(i,["step"]),c=dt(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,p=o.lastUserMessageId??f,h=jg(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0,parentConfig:o.parentConfig??null})}return t}function jg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Mg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Pg(e,t){return{...e,metadata:Ao(e.metadata,t.metadata)??null,config:Ao(e.config,t.config)??null,parentConfig:Ao(e.parentConfig,t.parentConfig)??null,next:Rg(e.next,t.next)??null,tasks:Og(e.tasks,t.tasks)??null,values:Ao(e.values,t.values)??null}}function Ao(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Rg(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Og(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Dg(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Lg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=$g(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=Lr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Lr(r.state,`${o}-state`);if(s)return s}}return null}function $g(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...p]=e,h=typeof a=="string"&&a.trim()?a:t,g=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",m=Array.isArray(d)?d:void 0,y=p.length?p[p.length-1]:void 0;return{id:h,name:g,interrupts:m,state:y!==void 0?y:f}}const n=Ot(e);if(!n)return null;const r=dt(n,["id","thread_id","taskId"])??t,o=dt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function Lr(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Hl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Lr(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=Lr(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=Lr(l,t,n+1,r);if(c)return c}}return null}function Hl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=dt(n,["type","event","kind"]),o=dt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Hl(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Wl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Ot(e)??{},o=Ot(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Eg[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=Ot(o.additional_kwargs)??Ot(o.additionalKwargs),d=Ot(o.response_metadata)??Ot(o.responseMetadata),f=dt(c,["createdAt","created_at"])??dt(o,["created_at","createdAt"]),p=dt(c,["checkpointId","checkpoint_id"]),h=dt(c,["checkpointNs","checkpoint_ns"]),g=Bg(o.content),m={id:l,role:i,content:g};f&&(m.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(m.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(m.model=String(d.model_name)),!m.model&&typeof o.model=="string"&&(m.model=o.model),p&&(m.checkpointId=p),h&&(m.checkpointNs=h);const y=Hg(Ot(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(m.artifact=y);const x=qg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),w=d?{...d}:void 0;x&&Object.keys(x).length&&(m.additionalKwargs=x),w&&Object.keys(w).length&&(m.responseMetadata=w);const S=zg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Ug(o,m.content);k&&(m.content=k)}return m}function Bg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Vl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Vl(e);return t?[t]:[]}return[]}function Vl(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=dt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=dt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Kl(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=dt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Kl(e,t){var s;const n=dt(e,["id","call_id"])??t,r=dt(e,["name"])??dt(Ot(e.function),["name"]);if(!n||!r)return null;const o=Kg(e.args??e.arguments??((s=Ot(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function zg(e){return Array.isArray(e)?e.map((t,n)=>Kl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ug(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Hg(e){return e?{plots:Wg(e.plots)}:void 0}function Wg(e){return Array.isArray(e)?e.map(t=>Vg(t)).filter(t=>!!t):[]}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Kg(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function Ot(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function dt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function qg(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}const ql=120;function Gg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>ql?`${n.slice(0,ql-3)}…`:n:""}function Gl(e){return Gg(e.content)||""}function Yg(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=Gl(n);r&&t.set(n.id,r)}return t}function Xg(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=Gl(o);s&&t.set(r.checkpointId,s)}}return t}const Yl="aiNav:tool-progress";function pi(){return typeof window<"u"&&typeof window.localStorage<"u"}function Xl(e){return`${Yl}:${e}`}function Jg(e,t,n){if(!pi()||!e)return;const r=Xl(e);if(!t.length){window.localStorage.removeItem(r);return}const o={messageId:e,entries:t,updatedAt:Date.now(),...n??{}};try{window.localStorage.setItem(r,JSON.stringify(o))}catch{}}function Zg(e){if(!pi()||!e)return;const t=Xl(e),n=window.localStorage.getItem(t);if(n)try{const r=JSON.parse(n);return!(r!=null&&r.entries)||!Array.isArray(r.entries)?void 0:r.entries}catch{window.localStorage.removeItem(t);return}}function Jl(){if(!pi())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(Yl)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const Tt=[];for(let e=0;e<256;++e)Tt.push((e+256).toString(16).slice(1));function Qg(e,t=0){return(Tt[e[t+0]]+Tt[e[t+1]]+Tt[e[t+2]]+Tt[e[t+3]]+"-"+Tt[e[t+4]]+Tt[e[t+5]]+"-"+Tt[e[t+6]]+Tt[e[t+7]]+"-"+Tt[e[t+8]]+Tt[e[t+9]]+"-"+Tt[e[t+10]]+Tt[e[t+11]]+Tt[e[t+12]]+Tt[e[t+13]]+Tt[e[t+14]]+Tt[e[t+15]]).toLowerCase()}let hi;const ex=new Uint8Array(16);function tx(){if(!hi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");hi=crypto.getRandomValues.bind(crypto)}return hi(ex)}const Zl={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function nx(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??tx();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Qg(r)}function rx(e,t,n){return Zl.randomUUID&&!e?Zl.randomUUID():nx(e)}const ox={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function sx(e,t){var n;switch(t.type){case"reset":return{messages:mi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],pendingInterrupt:null,toolTimelines:{}};case"seed":{const r=mi(t.payload.messages),{messages:o,toolTimelines:s}=fr(r,e.toolTimelines),i={...e,messages:o,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,toolStreamingMessageId:null,toolStreamingStack:[],toolTimelines:s};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(i.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(i.lastCheckpointNs=t.payload.checkpointNs??null),i}case"prepend":{const r=mi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(c=>c.id)),s=r.filter(c=>!o.has(c.id));if(!s.length)return e;const i=[...s,...e.messages],{messages:a,toolTimelines:l}=fr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"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 ec(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>ec(o,s),e):e}case"interrupt_response":return{...e,messages:tc(e.messages),pendingInterrupt:null};default:return e}}function Ql(e=[]){const[t,n]=b.useReducer(sx,{...ox,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 ec(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=hx(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const c={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,c]}}if(t.type==="message.delta"){const i=e.assemblingId??nc(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:ic(c.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof f.lastSeq=="number"&&p<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:f.lastSeq}),e;const{newParts:h,newMeta:g,changed:m}=dx(c.content,t.delta,f,p);if(!m)return e;const y={...c,content:h},x=No(a,l,y),w={...d,[i]:g};return{...e,messages:x,messagesStreamMeta:w}}if(t.type==="message.end"){const i=e.assemblingId??nc(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(c=>c.id===i&&c.role==="assistant");if(l>=0){const c=a[l];if(!((n=c.content)==null?void 0:n.some(f=>{var p;return(f==null?void 0:f.type)==="text"&&((p=f.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=c.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool.start"){const i=rc(t),a=i[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),l=t.name??t.tool??"tool";!a&&i.length===0&&i.push(`${l}-${Date.now()}`);const c=i.length?i:a?[a]:[],d=c[0]??`${l}-${Date.now()}`,f={type:"tool_call",id:d,name:l,args:t.args},p={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},h=e.toolStreamingMessageId;if(!h){const w={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...ax(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},S=lx(w,c.length?c:[d]),k=[...e.messages,w],C=_o(k,w.id,p),{messages:T,toolTimelines:E}=fr(C,e.toolTimelines);return{...e,messages:T,toolIndex:oc(e.toolIndex,w.id,S),toolStreamingMessageId:w.id,toolStreamingStack:sc(e.toolStreamingStack??[],a??d),toolTimelines:E}}const g=_o(e.messages,h,p),{messages:m,toolTimelines:y}=fr(g,e.toolTimelines);return{...e,messages:m,toolIndex:oc(e.toolIndex,h,c),toolStreamingStack:sc(e.toolStreamingStack??[],a??d),toolTimelines:y}}if(t.type==="tool.end"){const i=rc(t);if(!i.length&&!(typeof t.id=="string"&&t.id))return e;const a=i[0]??(typeof t.id=="string"?t.id:null);if(!a)return e;const l=e.toolStreamingStack??[],c=l[0]??null,d=cx(l,a),f=d[0]?e.toolIndex[d[0]]:null,p=e.toolStreamingMessageId,h=c===a,g=t.name??((s=e.messages.find(C=>C.id===p))==null?void 0:s.name)??"tool",m=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),y={type:"tool.end",toolId:a,toolName:g,content:m==null?void 0:m.slice(0,200)};let x=e.messages;if(p&&(x=_o(x,p,y)),h&&p){const C=x.findIndex(T=>T.id===p);if(C>=0){const T=x[C],N={type:"text",text:(()=>{if(typeof t.output=="string"){const D=t.output.trim();try{return D}catch{return D}}return JSON.stringify(t.output??"")})()},_={...T,content:[N],artifact:t.artifact??T.artifact,additionalKwargs:{...T.additionalKwargs??{}}};x=No(x,C,_)}}const w=d,{messages:S,toolTimelines:k}=fr(x,e.toolTimelines);return{...e,messages:S,toolTimelines:k,toolStreamingMessageId:h?f:p,toolStreamingStack:w}}if(t.type==="progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"progress",content:t.content??null},l=_o(e.messages,i,a),c=l.findIndex(y=>y.id===i);if(c===-1)return e;const d=l[c],f={...d.additionalKwargs??{},toolStreaming:!0},p={...d,additionalKwargs:f},h=No(l,c,p),{messages:g,toolTimelines:m}=fr(h,e.toolTimelines);return{...e,messages:g,toolTimelines:m}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=px(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="state_history"){const i=dr(t),a=i.interrupt,l=i.latest,c=a===null?tc(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:a,lastCheckpointId:(l==null?void 0:l.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(l==null?void 0:l.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function mi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function No(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function tc(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 nc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function rc(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 ix(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 ax(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};for(const l of t)s(l);const i=Array.from(o),a={};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function lx(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=ix(e);for(const o of r)n.add(o);return Array.from(n)}function oc(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 _o(e,t,n){const r=e.findIndex(c=>c.id===t);if(r===-1)return e;const o=e[r],s=[...e],i={...o.additionalKwargs??{}},a=Array.isArray(i.toolProgress)?[...i.toolProgress]:[],l={id:rx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),Jg(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function sc(e,t){return e.includes(t)?e:[...e,t]}function cx(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function ux(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}function fr(e,t){let n=!1;const r={},o=e.map(s=>{const i=ux(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??Zg(s.id);if(a!=null&&a.length){const l=[...a];r[s.id]=l,n=!0;const c={...s.additionalKwargs??{},toolProgress:l};return{...s,additionalKwargs:c}}return s});return{messages:n?o:e,toolTimelines:r}}function ic(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function dx(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??ic(e);let l="",c=e.slice();if(s){const f=fx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const p=c[c.length-1];if((p==null?void 0:p.type)==="text"){const h=p.text??"",g={...p,text:h+l};c=[...c.slice(0,c.length-1),g]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function ac(e){return e.replace(/\s+/g," ").trim()}function fx(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=ac(e),o=ac(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 px(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return No(e,r,s)}return e}function hx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function lc(e={}){const t=b.useMemo(()=>Cn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,p]=b.useState(""),[h,g]=b.useState(null),[m,y]=b.useState(0),[x,w]=b.useState(!1),S=b.useRef(null),k=b.useRef(!0),C=b.useRef(0),T=b.useRef(null),E=b.useRef(null),N=b.useRef(null),_=b.useRef(null),D=b.useCallback(P=>{o(P)},[]),B=b.useCallback(()=>{p(""),g(null),d(null),E.current=null,N.current=null,_.current=null},[]),G=b.useCallback(()=>{var P;console.debug("[use-chat] stop() invoked - aborting stream"),(P=S.current)==null||P.abort(),S.current=null,T.current=null,l(!1),w(!1),C.current=0,y(0)},[]),V=b.useCallback((P,M,A)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),g(null),E.current=null,N.current=null,_.current=null;const F=new AbortController;S.current=F;let L=null,R=null,z=!1;return T.current={threadId:P.threadId??null,headers:{}},(async()=>{var ne,ye,Te,q,U,Z,$,Y,Q,de,oe,_e,ze,se,me,Pe,Ve,ut;const X=Ke=>{var qe;try{const Qe=JSON.parse(JSON.stringify(Ke));return(qe=Qe==null?void 0:Qe.payload)!=null&&qe.files_info&&Array.isArray(Qe.payload.files_info)&&(Qe.payload.files_info=Qe.payload.files_info.map(Ge=>({...Ge,data:Ge!=null&&Ge.data?`<base64 ${String(Ge.data).length} chars>`:Ge==null?void 0:Ge.data}))),Qe}catch{return Ke}};try{let Ke={};try{if(r)Ke={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const We=window.__AUTH_TOKEN__,pt=((ne=window.localStorage)==null?void 0:ne.getItem("authToken"))||null;let Rt=null;try{const H=(ye=window.localStorage)==null?void 0:ye.getItem("chat-settings");H&&(Rt=((Te=JSON.parse(H))==null?void 0:Te.apiKey)||null)}catch{}const Ye=We||pt||Rt||null;Ye&&(Ke={Authorization:`Bearer ${Ye}`})}}catch{}console.debug("[use-chat] POST",t+n,X(P));let qe={};if(typeof window<"u")try{const tt=(q=window.localStorage)==null?void 0:q.getItem("authSessionId");tt&&(qe={"X-Session-Id":tt})}catch{}const Qe={...Ke,...qe,...s.current},Ge={"Content-Type":"application/json",Accept:"text/event-stream",...Qe},et=await fetch(t+n,{method:"POST",headers:Ge,body:JSON.stringify(P),signal:F.signal,credentials:i});if(T.current&&(T.current.headers=Qe),!et.ok||!et.body){const tt=await et.text().catch(()=>"");console.debug("[use-chat] non-OK response",et.status,tt==null?void 0:tt.slice(0,500));const We=`stream ${et.status}${tt?": "+tt:""}`;throw(U=A==null?void 0:A.onConnectionError)==null||U.call(A,We),z=!0,L="error",R=We,new Error(We)}w(!0);const st=et.body.getReader(),Mt=new TextDecoder;let gt="",Ct=[];C.current=0,y(0);let it=0,St=null;const Pt=()=>{if(Ct.length){const tt=Ct.join("");Ct=[],k.current&&p(We=>We+tt)}St=null},zt=()=>{typeof window<"u"&&St==null&&(St=requestAnimationFrame(Pt))};let nn=Date.now();const Le=setInterval(()=>{var tt;if(Date.now()-nn>18e5){const We="Stream idle timeout";d(We),L="error",R=We,F.abort(),(tt=A==null?void 0:A.onError)==null||tt.call(A,We)}},5e3),Sn=1024*1024;try{const tt=et.headers.get("X-Thread-Id")||et.headers.get("x-thread-id"),We=et.headers.get("X-Thread-Created")||et.headers.get("x-thread-created"),pt=tt??null,Rt=String(We??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:pt}),(Z=A==null?void 0:A.onOpen)==null||Z.call(A,{threadId:pt,created:Rt});;){const{value:Ye,done:H}=await st.read();if(H)break;gt+=Mt.decode(Ye,{stream:!0}),gt.length>Sn&&(gt="",console.warn("Stream buffer reset: exceeded 1MB"));let j;for(;(j=gt.indexOf(`
35
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=qn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&ko.assertOptions(r,{silentJSONParsing:fn.transitional(fn.boolean),forcedJSONParsing:fn.transitional(fn.boolean),clarifyTimeoutError:fn.transitional(fn.boolean)},!1),o!=null&&(O.isFunction(o)?n.paramsSerializer={serialize:o}:ko.assertOptions(o,{encode:fn.function,serialize:fn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ko.assertOptions(n,{baseUrl:fn.spelling("baseURL"),withXsrfToken:fn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&O.merge(s.common,s[n.method]);s&&O.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=Ft.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(l=l&&m.synchronous,a.unshift(m.fulfilled,m.rejected))});const c=[];this.interceptors.response.forEach(function(m){c.push(m.fulfilled,m.rejected)});let d,f=0,p;if(!l){const g=[_l.bind(this),void 0];for(g.unshift(...a),g.push(...c),p=g.length,d=Promise.resolve(n);f<p;)d=d.then(g[f++],g[f++]);return d}p=a.length;let h=n;for(;f<p;){const g=a[f++],m=a[f++];try{h=g(h)}catch(y){m.call(this,y);break}}try{d=_l.call(this,h)}catch(g){return Promise.reject(g)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=qn(this.defaults,t);const n=vl(t.baseURL,t.url,t.allowAbsoluteUrls);return ul(n,t.params,t.paramsSerializer)}};O.forEach(["delete","get","head","options"],function(t){Gn.prototype[t]=function(n,r){return this.request(qn(r||{},{method:t,url:n,data:(r||{}).data}))}}),O.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(qn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Gn.prototype[t]=n(),Gn.prototype[t+"Form"]=n(!0)});let yg=class Gh{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new ur(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Gh(function(o){t=o}),cancel:t}}};function vg(e){return function(n){return e.apply(null,n)}}function wg(e){return O.isObject(e)&&e.isAxiosError===!0}const li={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(li).forEach(([e,t])=>{li[t]=e});function Pl(e){const t=new Gn(e),n=Ya(Gn.prototype.request,t);return O.extend(n,Gn.prototype,t,{allOwnKeys:!0}),O.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pl(qn(e,o))},n}const yt=Pl(Or);yt.Axios=Gn,yt.CanceledError=ur,yt.CancelToken=yg,yt.isCancel=ml,yt.VERSION=jl,yt.toFormData=wo,yt.AxiosError=je,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=vg,yt.isAxiosError=wg,yt.mergeConfig=qn,yt.AxiosHeaders=Ft,yt.formToJSON=e=>pl(O.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Nl.getAdapter,yt.HttpStatusCode=li,yt.default=yt;const{Axios:VT,AxiosError:KT,CanceledError:qT,isCancel:GT,CancelToken:YT,VERSION:XT,all:JT,Cancel:ZT,isAxiosError:QT,spread:ek,toFormData:tk,AxiosHeaders:nk,HttpStatusCode:rk,formToJSON:ok,getAdapter:sk,mergeConfig:ik}=yt,Rl=typeof window<"u"?window.__API_BASE_URL__:void 0,Ol=Rl?Cn(Rl):void 0;function Cn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Eo=null;const ci=new Set;function Dl(){return Eo}function Io(e){Eo=e,ci.forEach(t=>t(e))}function Ll(e){return ci.add(e),()=>ci.delete(e)}const bg=3e4,Sg=9e4,qt=yt.create({...Ol?{baseURL:Ol}:{},timeout:bg,withCredentials:!0});qt.interceptors.request.use(e=>(Eo&&(e.headers.Authorization=`Bearer ${Eo}`),e)),qt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),Io(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function Gt(e,t){return qt.defaults.baseURL?(await qt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function ui(e,t,n){return qt.defaults.baseURL?(await qt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function $l(e,t,n){return qt.defaults.baseURL?(await qt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Fl(e,t){return qt.defaults.baseURL?(await qt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Yt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class Bl{get baseUrl(){const t=qt.defaults.baseURL;return t?Cn(String(t)):""}updateConfig(t){t.baseUrl&&(qt.defaults.baseURL=Cn(String(t.baseUrl))),t.authToken!==void 0&&Io(t.authToken)}getAuthToken(){return Dl()}setAuthToken(t){Io(t)}onTokenChange(t){return Ll(t)}async listThreads(){const t=await Gt("/threads"),n=Yt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await ui("/threads",t?{title:t}:void 0);return Yt(r)}async updateThread(t,n){const r=await $l(`/threads/${t}`,{title:n});return Yt(r)}async deleteThread(t){const n=await Fl(`/threads/${t}`);return Yt(n)}async threadInfo(t){const n=await Gt(`/threads/${t}/info`);return Yt(n)}async listAgents(){const t=await Gt("/agents"),n=Yt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Gt(`/agents/${t}`);return Yt(n)}async getAgentSchema(t){const n=await Gt(`/agents/${t}/schema`);return Yt(n)}async getState(t){const n=await Gt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Yt(n)}async getStateHistory(t){const n=await Gt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:Sg});return Yt(n)}async cancelRun(t){const n=await ui("/runs/cancel",{threadId:t});return Yt(n)}async listCheckpointSummaries(t){const n=await Gt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Yt(n);return(r==null?void 0:r.items)??[]}}const _n=new Bl,zl=b.createContext(null);function Cg({children:e,apiConfig:t}){const n=_n;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(zl.Provider,{value:r,children:e})}function di(){const e=b.useContext(zl);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Tg(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function kg(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await Tg(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const Eg={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function fi(e){if(!e||typeof e!="object")return!1;const t=e;return"values"in t&&"config"in t&&typeof t.values=="object"&&t.values!==null&&typeof t.config=="object"&&t.config!==null}function Ig(e,t){return`${e??""}::${t??""}`}function dr(e){const t=Array.isArray(e==null?void 0:e.checkpoints)?(e==null?void 0:e.checkpoints)??[]:e!=null&&e.checkpoints?Object.values(e.checkpoints):[],n=(e==null?void 0:e.threadId)??"",r=t[0];if(!fi(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=Ng(t),i=Ul(r,0),a=_g(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function Ul(e,t){if(!fi(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(_=>!!_&&typeof _=="object").map(_=>({..._})):a===null?null:void 0,c=r.map((_,D)=>Fg(_,D)).filter(_=>!!_),d=Ot(e.config),f=Ot(d==null?void 0:d.configurable),p=dt(f,["checkpoint_id","checkpointId"]),h=dt(f,["checkpoint_ns","checkpointNs"]),g=Ot(e==null?void 0:e.parentConfig),m=Ot(g==null?void 0:g.configurable),y=dt(m,["checkpoint_id","checkpointId"])??null,x=dt(m,["checkpoint_ns","checkpointNs"])??null,w=e==null?void 0:e.createdAt,S=typeof w=="string"&&w.trim()?w:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(_=>_.role==="user")??null,C=Ot(e==null?void 0:e.metadata),T=dt(C,["branch_label","branchLabel"]),E=dt(m,["checkpoint_id","checkpointId"]),N=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:p??null,checkpointNs:h??null,nextCursor:y,nextCursorNs:x,interrupt:Ag(a,c,t),createdAt:S,parentId:E??null,branchLabel:T??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:C??null,config:d??null,parentConfig:g??null,next:N??null,tasks:l??null,values:i??null}}function Ag(e,t,n){const r=Lg(e,n);return r||Dg(t,n)}function Ng(e){const t=new Map;e.forEach((o,s)=>{if(!fi(o))return;const i=Ul(o,s);if(!(i!=null&&i.checkpointId))return;const a=Ig(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,Pg(l,i))});const n=Array.from(t.values());n.sort((o,s)=>Wl(s.createdAt??"")-Wl(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function _g(e){var n,r;const t=[];for(const o of e){const s=o.checkpointId??null;if(!s)continue;const i=o.metadata??{},a=dt(i,["label"])??dt(i,["branch_label","branchLabel"])??dt(i,["description"])??"User input",l=Mg(i,["step"]),c=dt(i,["source"]),d=o.createdAt??null,f=((r=(n=o.messages)==null?void 0:n[o.messages.length-1])==null?void 0:r.id)??null,p=o.lastUserMessageId??f,h=jg(o.next);t.push({id:s,label:a,messageId:p,step:l,source:c??null,createdAt:d,next:h??void 0,parentConfig:o.parentConfig??null})}return t}function jg(e){if(!Array.isArray(e)||e.length===0)return null;const t=e.map(n=>{if(typeof n=="string")return n.trim();if(n&&typeof n=="object"&&"type"in n){const r=n;if(typeof r.type=="string")return r.type}return null}).filter(n=>!!(n&&n.length));return t.length?t.join(", "):null}function Mg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r=="number"&&Number.isFinite(r))return r}return null}function Pg(e,t){return{...e,metadata:Ao(e.metadata,t.metadata)??null,config:Ao(e.config,t.config)??null,parentConfig:Ao(e.parentConfig,t.parentConfig)??null,next:Rg(e.next,t.next)??null,tasks:Og(e.tasks,t.tasks)??null,values:Ao(e.values,t.values)??null}}function Ao(e,t){return t&&typeof t=="object"?{...e&&typeof e=="object"?e:{},...t}:t===null?e&&typeof e=="object"?{...e}:e??null:e&&typeof e=="object"?{...e}:e??void 0}function Rg(e,t){return Array.isArray(t)?t.slice():t===null?Array.isArray(e)?e.slice():e??null:Array.isArray(e)?e.slice():e??void 0}function Og(e,t){return Array.isArray(t)?t.map(n=>({...n})):t===null?Array.isArray(e)?e.map(n=>({...n})):e??null:Array.isArray(e)?e.map(n=>({...n})):e??void 0}function Dg(e,t){var n;for(let r=e.length-1;r>=0;r--){const o=((n=e[r])==null?void 0:n.content)??[];for(let s=o.length-1;s>=0;s--){const i=o[s];if((i==null?void 0:i.type)==="interrupt"){const a=i;return{id:typeof a.id=="string"&&a.id.trim()?a.id:`interrupt-${t}-${r}-${s}`,value:a.value}}}}return null}function Lg(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=$g(e[n],`task-${t}-${n}`);if(!r)continue;const o=r.id||`task-${t}-${n}`;if(Array.isArray(r.interrupts)&&r.interrupts.length)for(let s=r.interrupts.length-1;s>=0;s--){const i=Lr(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=Lr(r.state,`${o}-state`);if(s)return s}}return null}function $g(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...p]=e,h=typeof a=="string"&&a.trim()?a:t,g=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",m=Array.isArray(d)?d:void 0,y=p.length?p[p.length-1]:void 0;return{id:h,name:g,interrupts:m,state:y!==void 0?y:f}}const n=Ot(e);if(!n)return null;const r=dt(n,["id","thread_id","taskId"])??t,o=dt(n,["name"])??"task",s=Array.isArray(n.interrupts)?n.interrupts:void 0,i=Object.prototype.hasOwnProperty.call(n,"state")?n.state:void 0;return{id:r,name:o,interrupts:s,state:i}}function Lr(e,t,n=0,r=new Set){if(n>6||e==null)return null;if(typeof e=="object"){if(r.has(e))return null;r.add(e)}const o=Hl(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=Lr(e[s],t,n+1,r);if(i)return i}return null}if(typeof e=="object"){const s=e,i=["interrupt","pending_interrupt","pendingInterrupt","value","data","payload","result","response"];for(const a of i)if(a in s){const l=Lr(s[a],t,n+1,r);if(l)return l}for(const[a,l]of Object.entries(s)){if(i.includes(a)||a==="messages"||a==="results")continue;const c=Lr(l,t,n+1,r);if(c)return c}}return null}function Hl(e,t){if(!e)return null;if(typeof e=="object"&&!Array.isArray(e)){const n=e,r=dt(n,["type","event","kind"]),o=dt(n,["id","interrupt_id","interruptId","value_id"])??(r&&r.toLowerCase().includes("interrupt")?t:void 0);if(!(Object.prototype.hasOwnProperty.call(n,"value")||Object.prototype.hasOwnProperty.call(n,"data")||Object.prototype.hasOwnProperty.call(n,"payload"))&&!(r&&r.toLowerCase().includes("interrupt")))return null;const i=Object.prototype.hasOwnProperty.call(n,"value")?n.value:Object.prototype.hasOwnProperty.call(n,"data")?n.data:Object.prototype.hasOwnProperty.call(n,"payload")?n.payload:n,a=o&&o.trim()?o:t;return a?{id:a,value:i}:null}if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){const r=Hl(e[n],t);if(r)return r}return e.length>=2&&typeof e[0]=="string"&&e[0].trim()?{id:e[0],value:e[1]}:null}if(typeof e=="string"){const n=e.trim();return n?{id:t||n,value:n}:null}return null}function Wl(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Fg(e,t){if(!e||typeof e!="object")return null;const n=e,r=Ot(e)??{},o=Ot(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=Eg[s];if(!i)return null;const a=o.id??o.message_id??o.run_id??null,l=typeof a=="string"&&a.trim()?a:`history-${i}-${t}`,c=Ot(o.additional_kwargs)??Ot(o.additionalKwargs),d=Ot(o.response_metadata)??Ot(o.responseMetadata),f=dt(c,["createdAt","created_at"])??dt(o,["created_at","createdAt"]),p=dt(c,["checkpointId","checkpoint_id"]),h=dt(c,["checkpointNs","checkpoint_ns"]),g=Bg(o.content),m={id:l,role:i,content:g};f&&(m.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(m.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(m.model=String(d.model_name)),!m.model&&typeof o.model=="string"&&(m.model=o.model),p&&(m.checkpointId=p),h&&(m.checkpointNs=h);const y=Hg(Ot(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(m.artifact=y);const x=qg(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),w=d?{...d}:void 0;x&&Object.keys(x).length&&(m.additionalKwargs=x),w&&Object.keys(w).length&&(m.responseMetadata=w);const S=zg((c==null?void 0:c.tool_calls)??o.tool_calls);if(S.length&&(m.content=[...m.content,...S]),i==="tool"){const k=Ug(o,m.content);k&&(m.content=k)}return m}function Bg(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>Vl(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=Vl(e);return t?[t]:[]}return[]}function Vl(e){if(!e||typeof e!="object")return typeof e=="string"&&e.trim()?{type:"text",text:e}:null;const t=e,n=String(t.type??"").toLowerCase();if(!n||n==="text"){const o=typeof t.text=="string"?t.text:typeof t.value=="string"?t.value:"";return o.trim()?{type:"text",text:o}:null}if(n==="image"||n==="image_url"){const o=dt(t,["url","src"]);if(!o)return null;const s={type:"image_url",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.alt=="string"&&(s.alt=t.alt),s}if(n==="file"){const o=dt(t,["url"]);if(!o)return null;const s={type:"file",url:o};return typeof t.mimeType=="string"&&(s.mimeType=t.mimeType),typeof t.name=="string"&&(s.name=t.name),typeof t.size=="number"&&(s.size=t.size),typeof t.sourceType=="string"&&(s.sourceType=t.sourceType),s}if(n==="tool_call")return Kl(t)??null;if(n==="tool_end"){const o="output"in t?t.output:t.content;return o?{type:"text",text:typeof o=="string"?o:JSON.stringify(o)}:null}if(n==="interrupt")return{type:"interrupt",value:t.value,...t};if(n==="tool"){const o=dt(t,["text","content"]);if(o)return{type:"text",text:o}}const r=typeof t.content=="string"?t.content:typeof t.value=="string"?t.value:JSON.stringify(t);return r?{type:"text",text:r}:null}function Kl(e,t){var s;const n=dt(e,["id","call_id"])??t,r=dt(e,["name"])??dt(Ot(e.function),["name"]);if(!n||!r)return null;const o=Kg(e.args??e.arguments??((s=Ot(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function zg(e){return Array.isArray(e)?e.map((t,n)=>Kl(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ug(e,t){const n=e.content??e.output;if(!n)return t;const o={type:"text",text:typeof n=="string"?n:JSON.stringify(n)};return[...t,o]}function Hg(e){return e?{plots:Wg(e.plots)}:void 0}function Wg(e){return Array.isArray(e)?e.map(t=>Vg(t)).filter(t=>!!t):[]}function Vg(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.content_base64=="string"&&t.content_base64.trim()||void 0,r=typeof t.url=="string"&&t.url.trim()||void 0,o=(typeof t.format=="string"?t.format.trim():void 0)||(typeof t.mimeType=="string"?t.mimeType.trim():void 0)||(typeof t.mime_type=="string"?t.mime_type.trim():void 0),s=typeof t.plotId=="string"&&t.plotId.trim()||void 0,i=typeof t.artifactId=="string"&&t.artifactId.trim()||void 0,a={};return n&&(a.content_base64=n),r&&(a.url=r),o&&(a.format=o),s&&(a.plotId=s),i&&(a.artifactId=i),a}function Kg(e){if(!e)return{};if(typeof e=="string")try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{raw:e}}catch{return{raw:e}}return typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function Ot(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return{...e}}function dt(e,t){if(e)for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r}}function qg(e,t){if(!e)return;const n={};let r=!1;for(const[o,s]of Object.entries(e)){if(t.includes(o)){r=!0;continue}s!==void 0&&(n[o]=s)}return r?Object.keys(n).length?n:void 0:e}const ql=120;function Gg(e){if(!Array.isArray(e))return"";const t=e.filter(r=>!!(r&&r.type==="text")).map(r=>(r.text??"").trim()).filter(Boolean);if(!t.length)return"";const n=t.join(" ").replace(/\s+/g," ").trim();return n?n.length>ql?`${n.slice(0,ql-3)}…`:n:""}function Gl(e){return Gg(e.content)||""}function Yg(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=Gl(n);r&&t.set(n.id,r)}return t}function Xg(e){var n;const t=new Map;for(const r of e){if(!r.checkpointId)continue;const o=(n=r.messages)==null?void 0:n.find(s=>s.role==="user");if(o){const s=Gl(o);s&&t.set(r.checkpointId,s)}}return t}const Yl="aiNav:tool-progress";function pi(){return typeof window<"u"&&typeof window.localStorage<"u"}function Xl(e){return`${Yl}:${e}`}function Jg(e,t,n){if(!pi()||!e)return;const r=Xl(e);if(!t.length){window.localStorage.removeItem(r);return}const o={messageId:e,entries:t,updatedAt:Date.now(),...n??{}};try{window.localStorage.setItem(r,JSON.stringify(o))}catch{}}function Zg(e){if(!pi()||!e)return;const t=Xl(e),n=window.localStorage.getItem(t);if(n)try{const r=JSON.parse(n);return!(r!=null&&r.entries)||!Array.isArray(r.entries)?void 0:r.entries}catch{window.localStorage.removeItem(t);return}}function Jl(){if(!pi())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(Yl)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const Tt=[];for(let e=0;e<256;++e)Tt.push((e+256).toString(16).slice(1));function Qg(e,t=0){return(Tt[e[t+0]]+Tt[e[t+1]]+Tt[e[t+2]]+Tt[e[t+3]]+"-"+Tt[e[t+4]]+Tt[e[t+5]]+"-"+Tt[e[t+6]]+Tt[e[t+7]]+"-"+Tt[e[t+8]]+Tt[e[t+9]]+"-"+Tt[e[t+10]]+Tt[e[t+11]]+Tt[e[t+12]]+Tt[e[t+13]]+Tt[e[t+14]]+Tt[e[t+15]]).toLowerCase()}let hi;const ex=new Uint8Array(16);function tx(){if(!hi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");hi=crypto.getRandomValues.bind(crypto)}return hi(ex)}const Zl={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function nx(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??tx();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Qg(r)}function rx(e,t,n){return Zl.randomUUID&&!e?Zl.randomUUID():nx(e)}function mi(e){return e.filter(t=>{var s;if(t.role!=="assistant")return!0;const n=(t.content||[]).some(i=>{var a;return i&&i.type==="text"&&((a=i.text)==null?void 0:a.trim())}),r=(t.content||[]).some(i=>i&&i.type==="image_url"),o=!!((s=t.artifact)!=null&&s.plots&&t.artifact.plots.length>0);return!!(n||r||o)})}function No(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Ql(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function ec(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function tc(e){const t=new Set,n=r=>{typeof r=="string"&&r.trim()&&t.add(r.trim())};return n(e.id),n(e==null?void 0:e.call_id),n(e==null?void 0:e.callId),Array.from(t)}function ox(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=dx(e);for(const o of r)n.add(o);return Array.from(n)}function nc(e,t,n){if(!n.length)return e;let r=!1;const o={...e};for(const s of n)s&&o[s]!==t&&(o[s]=t,r=!0);return r?o:e}function sx(e,t,n,r){const o=new Set,s=l=>{typeof l=="string"&&l.trim()&&o.add(l.trim())};for(const l of t)s(l);const i=Array.from(o),a={};if(i.length){a.toolCallIds=i;const l=typeof a.toolCallId=="string"?a.toolCallId.trim():null;a.toolCallId=l&&o.has(l)?l:i[0]}return n&&(a.toolName=n),r!==void 0&&(a.toolArgs=r),a}function _o(e,t,n){const r=e.findIndex(c=>c.id===t);if(r===-1)return e;const o=e[r],s=[...e],i={...o.additionalKwargs??{}},a=Array.isArray(i.toolProgress)?[...i.toolProgress]:[],l={id:rx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),Jg(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function rc(e,t){return e.includes(t)?e:[...e,t]}function ix(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function fr(e,t){let n=!1;const r={},o=e.map(s=>{const i=fx(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??Zg(s.id);if(a!=null&&a.length){const l=[...a];r[s.id]=l,n=!0;const c={...s.additionalKwargs??{},toolProgress:l};return{...s,additionalKwargs:c}}return s});return{messages:n?o:e,toolTimelines:r}}function oc(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function ax(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(f=>f.type==="text").map(f=>f.text??"").join(""),i=t.filter(f=>f.type!=="text"),a=o.lastText??oc(e);let l="",c=e.slice();if(s){const f=lx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const p=c[c.length-1];if((p==null?void 0:p.type)==="text"){const h=p.text??"",g={...p,text:h+l};c=[...c.slice(0,c.length-1),g]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function sc(e){return e.replace(/\s+/g," ").trim()}function lx(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=sc(e),o=sc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function cx(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return No(e,r,s)}return e}function ux(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function dx(e){if(!e)return[];const t=new Set,n=o=>{typeof o=="string"&&o.trim()&&t.add(o.trim())},r=e.additionalKwargs;if(r){n(r.toolCallId);const o=r.toolCallIds;if(Array.isArray(o))for(const s of o)n(s)}for(const o of e.content??[])(o==null?void 0:o.type)==="tool_call"&&n(o.id);return Array.from(t)}function fx(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}const px={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function hx(e,t){var n;switch(t.type){case"reset":return{messages:mi(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],pendingInterrupt:null,toolTimelines:{}};case"seed":{const r=mi(t.payload.messages),{messages:o,toolTimelines:s}=fr(r,e.toolTimelines),i={...e,messages:o,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null,toolStreamingMessageId:null,toolStreamingStack:[],toolTimelines:s};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(i.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(i.lastCheckpointNs=t.payload.checkpointNs??null),i}case"prepend":{const r=mi(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(c=>c.id)),s=r.filter(c=>!o.has(c.id));if(!s.length)return e;const i=[...s,...e.messages],{messages:a,toolTimelines:l}=fr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"event":return ac(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>ac(o,s),e):e}case"interrupt_response":return{...e,messages:Ql(e.messages),pendingInterrupt:null};default:return e}}function ic(e=[]){const[t,n]=b.useReducer(hx,{...px,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function ac(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=ux(t.model);if(e.messages.some(d=>d.id===i)){const d=e.messagesStreamMeta??{},f={...d,[i]:d[i]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:i,messagesStreamMeta:f}}const c={id:i,role:"assistant",name:a||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:i,messages:[...e.messages,c]}}if(t.type==="message.delta"){const i=e.assemblingId??ec(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(S=>S.id===i&&S.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:oc(c.content)},p=t.seq??null;if(p!==null&&typeof p=="number"&&typeof f.lastSeq=="number"&&p<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:p,lastSeq:f.lastSeq}),e;const{newParts:h,newMeta:g,changed:m}=ax(c.content,t.delta,f,p);if(!m)return e;const y={...c,content:h},x=No(a,l,y),w={...d,[i]:g};return{...e,messages:x,messagesStreamMeta:w}}if(t.type==="message.end"){const i=e.assemblingId??ec(e.messages);if(!i)return{...e,assemblingId:null};const a=e.messages,l=a.findIndex(c=>c.id===i&&c.role==="assistant");if(l>=0){const c=a[l];if(!((n=c.content)==null?void 0:n.some(f=>{var p;return(f==null?void 0:f.type)==="text"&&((p=f.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=c.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const f=[...a.slice(0,l),...a.slice(l+1)];return{...e,assemblingId:null,messages:f}}}return e}if(t.type==="tool.start"){const i=tc(t),a=i[0]??(typeof t.id=="string"?t.id:null)??(typeof t.call_id=="string"?t.call_id:null),l=t.name??t.tool??"tool";!a&&i.length===0&&i.push(`${l}-${Date.now()}`);const c=i.length?i:a?[a]:[],d=c[0]??`${l}-${Date.now()}`,f={type:"tool_call",id:d,name:l,args:t.args},p={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},h=e.toolStreamingMessageId;if(!h){const w={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...sx(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},S=ox(w,c.length?c:[d]),k=[...e.messages,w],C=_o(k,w.id,p),{messages:T,toolTimelines:E}=fr(C,e.toolTimelines);return{...e,messages:T,toolIndex:nc(e.toolIndex,w.id,S),toolStreamingMessageId:w.id,toolStreamingStack:rc(e.toolStreamingStack??[],a??d),toolTimelines:E}}const g=_o(e.messages,h,p),{messages:m,toolTimelines:y}=fr(g,e.toolTimelines);return{...e,messages:m,toolIndex:nc(e.toolIndex,h,c),toolStreamingStack:rc(e.toolStreamingStack??[],a??d),toolTimelines:y}}if(t.type==="tool.end"){const i=tc(t);if(!i.length&&!(typeof t.id=="string"&&t.id))return e;const a=i[0]??(typeof t.id=="string"?t.id:null);if(!a)return e;const l=e.toolStreamingStack??[],c=l[0]??null,d=ix(l,a),f=d[0]?e.toolIndex[d[0]]:null,p=e.toolStreamingMessageId,h=c===a,g=t.name??((s=e.messages.find(C=>C.id===p))==null?void 0:s.name)??"tool",m=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),y={type:"tool.end",toolId:a,toolName:g,content:m==null?void 0:m.slice(0,200)};let x=e.messages;if(p&&(x=_o(x,p,y)),h&&p){const C=x.findIndex(T=>T.id===p);if(C>=0){const T=x[C],N={type:"text",text:(()=>{if(typeof t.output=="string"){const D=t.output.trim();try{return D}catch{return D}}return JSON.stringify(t.output??"")})()},_={...T,content:[N],artifact:t.artifact??T.artifact,additionalKwargs:{...T.additionalKwargs??{}}};x=No(x,C,_)}}const w=d,{messages:S,toolTimelines:k}=fr(x,e.toolTimelines);return{...e,messages:S,toolTimelines:k,toolStreamingMessageId:h?f:p,toolStreamingStack:w}}if(t.type==="progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"progress",content:t.content??null},l=_o(e.messages,i,a),c=l.findIndex(y=>y.id===i);if(c===-1)return e;const d=l[c],f={...d.additionalKwargs??{},toolStreaming:!0},p={...d,additionalKwargs:f},h=No(l,c,p),{messages:g,toolTimelines:m}=fr(h,e.toolTimelines);return{...e,messages:g,toolTimelines:m}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=cx(e.messages,t.checkpointId,i);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:i,messages:a}}if(t.type==="error"){const i={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,i]}}if(t.type==="state_history"){const i=dr(t),a=i.interrupt,l=i.latest,c=a===null?Ql(e.messages):e.messages;return{...e,messages:c,pendingInterrupt:a,lastCheckpointId:(l==null?void 0:l.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(l==null?void 0:l.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function lc(e={}){const t=b.useMemo(()=>Cn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[f,p]=b.useState(""),[h,g]=b.useState(null),[m,y]=b.useState(0),[x,w]=b.useState(!1),S=b.useRef(null),k=b.useRef(!0),C=b.useRef(0),T=b.useRef(null),E=b.useRef(null),N=b.useRef(null),_=b.useRef(null),D=b.useCallback(P=>{o(P)},[]),B=b.useCallback(()=>{p(""),g(null),d(null),E.current=null,N.current=null,_.current=null},[]),G=b.useCallback(()=>{var P;console.debug("[use-chat] stop() invoked - aborting stream"),(P=S.current)==null||P.abort(),S.current=null,T.current=null,l(!1),w(!1),C.current=0,y(0)},[]),V=b.useCallback((P,M,A)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&p(""),g(null),E.current=null,N.current=null,_.current=null;const F=new AbortController;S.current=F;let L=null,R=null,z=!1;return T.current={threadId:P.threadId??null,headers:{}},(async()=>{var ne,ye,Te,q,U,Z,$,Y,Q,de,oe,_e,ze,se,me,Pe,Ve,ut;const X=Ke=>{var qe;try{const Qe=JSON.parse(JSON.stringify(Ke));return(qe=Qe==null?void 0:Qe.payload)!=null&&qe.files_info&&Array.isArray(Qe.payload.files_info)&&(Qe.payload.files_info=Qe.payload.files_info.map(Ge=>({...Ge,data:Ge!=null&&Ge.data?`<base64 ${String(Ge.data).length} chars>`:Ge==null?void 0:Ge.data}))),Qe}catch{return Ke}};try{let Ke={};try{if(r)Ke={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const We=window.__AUTH_TOKEN__,pt=((ne=window.localStorage)==null?void 0:ne.getItem("authToken"))||null;let Rt=null;try{const H=(ye=window.localStorage)==null?void 0:ye.getItem("chat-settings");H&&(Rt=((Te=JSON.parse(H))==null?void 0:Te.apiKey)||null)}catch{}const Ye=We||pt||Rt||null;Ye&&(Ke={Authorization:`Bearer ${Ye}`})}}catch{}console.debug("[use-chat] POST",t+n,X(P));let qe={};if(typeof window<"u")try{const tt=(q=window.localStorage)==null?void 0:q.getItem("authSessionId");tt&&(qe={"X-Session-Id":tt})}catch{}const Qe={...Ke,...qe,...s.current},Ge={"Content-Type":"application/json",Accept:"text/event-stream",...Qe},et=await fetch(t+n,{method:"POST",headers:Ge,body:JSON.stringify(P),signal:F.signal,credentials:i});if(T.current&&(T.current.headers=Qe),!et.ok||!et.body){const tt=await et.text().catch(()=>"");console.debug("[use-chat] non-OK response",et.status,tt==null?void 0:tt.slice(0,500));const We=`stream ${et.status}${tt?": "+tt:""}`;throw(U=A==null?void 0:A.onConnectionError)==null||U.call(A,We),z=!0,L="error",R=We,new Error(We)}w(!0);const st=et.body.getReader(),Mt=new TextDecoder;let gt="",Ct=[];C.current=0,y(0);let it=0,St=null;const Pt=()=>{if(Ct.length){const tt=Ct.join("");Ct=[],k.current&&p(We=>We+tt)}St=null},zt=()=>{typeof window<"u"&&St==null&&(St=requestAnimationFrame(Pt))};let nn=Date.now();const Le=setInterval(()=>{var tt;if(Date.now()-nn>18e5){const We="Stream idle timeout";d(We),L="error",R=We,F.abort(),(tt=A==null?void 0:A.onError)==null||tt.call(A,We)}},5e3),Sn=1024*1024;try{const tt=et.headers.get("X-Thread-Id")||et.headers.get("x-thread-id"),We=et.headers.get("X-Thread-Created")||et.headers.get("x-thread-created"),pt=tt??null,Rt=String(We??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:pt}),(Z=A==null?void 0:A.onOpen)==null||Z.call(A,{threadId:pt,created:Rt});;){const{value:Ye,done:H}=await st.read();if(H)break;gt+=Mt.decode(Ye,{stream:!0}),gt.length>Sn&&(gt="",console.warn("Stream buffer reset: exceeded 1MB"));let j;for(;(j=gt.indexOf(`
36
36
 
37
37
  `))>=0;){const J=gt.slice(0,j);gt=gt.slice(j+2);const re=gx(J);if(!re)continue;let ie;try{ie=JSON.parse(re)}catch{console.debug("[use-chat] malformed SSE:",re.slice(0,200));continue}const ce=mx(ie)?ie.data:ie;nn=Date.now();const Xe=ce.seq;if(Xe!==void 0){if(Xe<=it){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:Xe,lastProcessedSeq:it,type:ce.type});continue}it>0&&Xe>it+1&&(($=A==null?void 0:A.onGap)==null||$.call(A,{from:it,to:Xe})),it=Xe,C.current=Xe,y(Xe)}if(ce.type==="checkpoint")E.current=ce.checkpointId??null,N.current=ce.checkpointNs??null,g(ce.checkpointId??null);else if(ce.type==="state_history"){_.current=ce;try{const at=dr(ce).latest;at&&(E.current=at.checkpointId??null,N.current=at.checkpointNs??null,g(at.checkpointId??null))}catch(Ie){console.warn("[use-chat] Failed to hydrate state_history payload",Ie)}}try{M==null||M(ce)}catch(Ie){console.error("[use-chat] Error in onEvent callback:",Ie,"for event:",ce.type)}if(ce.type==="message.delta"){const Ie=ce.delta.filter(at=>at.type==="text").map(at=>at.text).join("");Ie&&e.autoAppendAssistant!==!1&&(Ct.push(Ie),zt())}else if(ce.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(Y=A==null?void 0:A.onHeartbeat)==null||Y.call(A,ce)}catch(Ie){console.warn("[use-chat] heartbeat callback failed",Ie)}}else if(St!==null&&cancelAnimationFrame(St),Pt(),ce.type==="checkpoint")g(ce.checkpointId);else if(ce.type==="error"){const Ie=ce;if(d(Ie.message),L="error",R=Ie.message,Ie.error_type==="auth_error"||Ie.code==="TOKEN_EXPIRED"||((Q=Ie.message)==null?void 0:Q.includes("token"))||((de=Ie.message)==null?void 0:de.includes("401"))||((oe=Ie.message)==null?void 0:oe.includes("unauthorized"))||((_e=Ie.message)==null?void 0:_e.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Ie.message);try{(ze=A==null?void 0:A.onAuthError)==null||ze.call(A,Ie.message)}catch(ht){console.warn("[use-chat] onAuthError handler failed",ht)}F.abort()}}}}Pt(),L===null&&!F.signal.aborted&&(L="complete")}catch(tt){if(tt.name==="AbortError")L=L??"aborted";else{const We=tt.message||String(tt);L="error",R=We,d(We),(se=A==null?void 0:A.onError)==null||se.call(A,We)}}finally{try{await st.cancel()}catch{}finally{(me=st.releaseLock)==null||me.call(st)}St!==null&&typeof window<"u"&&window.cancelAnimationFrame(St),clearInterval(Le)}}catch(Ke){if(Ke.name==="AbortError")L=L??"aborted";else{const qe=Ke.message||String(Ke);L="error",R=qe,d(qe),(Pe=A==null?void 0:A.onError)==null||Pe.call(A,qe),z||((Ve=A==null?void 0:A.onConnectionError)==null||Ve.call(A,qe),z=!0)}}finally{const Ke=C.current,qe=E.current,Qe=N.current,Ge=_.current,et=L??(F.signal.aborted?"aborted":R?"error":"complete");try{(ut=A==null?void 0:A.onClosed)==null||ut.call(A,{reason:et,lastSeq:Ke,lastCheckpointId:qe,lastCheckpointNs:Qe,lastStateHistory:Ge,error:R})}catch(st){console.warn("[use-chat] onClosed callback failed",st)}l(!1),w(!1),S.current=null,C.current=0,y(0),T.current=null}})(),{close:()=>F.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var P;k.current=!1,(P=S.current)==null||P.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:h,lastSeq:m,connected:x,stream:V,stop:G,clear:B,setToken:D}}function mx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function gx(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
38
- `)}const xx=["message.start","message.delta","message.end","progress"],yx=["tool.start","tool.end"],vx=["thread_info","checkpoint"],wx=["error","interrupt","heartbeat","state_history","cancelled"],bx=[...xx,...yx,...vx,...wx],Sx=new Set(bx);function Cx(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return Sx.has(t)}const cc=200;function Tx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=b.useRef(null),f=b.useRef(null),p=b.useRef(new Map),h=b.useRef(null),g=b.useRef(null),m=b.useCallback(M=>{try{const A=globalThis.structuredClone;if(typeof A=="function")return A(M)}catch{}try{return JSON.parse(JSON.stringify(M))}catch{return M}},[]),y=b.useCallback((M,A)=>{if(!M)return;const F=p.current.get(M)??[],L=m(A),R=F.length>=cc?[...F.slice(F.length-cc+1),L]:[...F,L];p.current.set(M,R)},[m]),x=b.useCallback(M=>{M&&p.current.set(M,[])},[]),w=b.useCallback(M=>{const A=M??f.current;if(!A)return;const F=p.current.get(A);F!=null&&F.length&&F.forEach(L=>{try{n(L)}catch(R){console.error("[useChatStreamingService] Failed to replay buffered event",R)}})},[n]),S=b.useCallback(M=>{f.current=M.threadId,h.current&&(h.current.threadIdGuess=M.threadId),g.current=M,x(M.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",M);try{t(M)}catch(A){console.error("[useChatStreamingService] Error in onThreadInfo handler:",A)}},[x,t]),k=b.useCallback(M=>{try{c==null||c(M)}catch(A){console.error("[useChatStreamingService] Error in onHeartbeat handler:",A)}},[c]),C=b.useCallback(M=>{var L,R,z,X;const A=M;if(A.error_type==="auth_error"||A.code==="TOKEN_EXPIRED"||((L=A.message)==null?void 0:L.includes("token"))||((R=A.message)==null?void 0:R.includes("401"))||((z=A.message)==null?void 0:z.includes("unauthorized"))||((X=A.message)==null?void 0:X.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",A.message);try{l==null||l(A.message)}catch(ne){console.warn("[useChatStreamingService] onAuthError handler failed",ne)}}},[l]),T=b.useMemo(()=>({thread_info:M=>(S(M),!0),heartbeat:M=>(k(M),!0),error:M=>(C(M),!1)}),[S,k,C]),E=b.useCallback(M=>{var R;const A=M.seq??null;if(A!==null){const z=d.current;if(z!==null){if(A<=z)return;A>z+1&&(s==null||s({from:z,to:A}))}d.current=A}const F=T[M.type];if(F&&F(M))return;const L=M.threadId??(M.type==="state_history"?M.threadId:void 0)??f.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(M.type==="state_history"){f.current=L??f.current;try{r==null||r(M)}catch(z){console.error("[useChatStreamingService] onStateHistory handler failed",z)}}if(Cx(M)){M.type==="checkpoint"||M.type==="state_history"?x(L??null):y(L??null,M);try{n(M)}catch(z){console.error("[useChatStreamingService] Error in onMessageEvent handler:",z)}return}try{o==null||o(M)}catch(z){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",z)}},[y,x,n,s,r,o,T]),{stream:N,stop:_,isStreaming:D,error:B,setToken:G}=lc({baseUrl:e,token:void 0}),V=b.useCallback((M,A)=>{d.current=null,g.current=null,f.current=M.threadId??null,h.current={request:M,callbacks:A,manualStop:!1,threadIdGuess:M.threadId??null},N(M,E,{onOpen:A==null?void 0:A.onOpen,onError:F=>{var L;(L=A==null?void 0:A.onError)==null||L.call(A,F)},onGap:(A==null?void 0:A.onGap)??s,onConnectionError:F=>{var L;a==null||a(F),(L=A==null?void 0:A.onConnectionError)==null||L.call(A,F)},onAuthError:F=>{var L;l==null||l(F),(L=A==null?void 0:A.onAuthError)==null||L.call(A,F)},onHeartbeat:F=>{var L;try{c==null||c(F)}catch(R){console.warn("[useChatStreamingService] onHeartbeat handler failed",R)}try{(L=A==null?void 0:A.onHeartbeat)==null||L.call(A,F)}catch(R){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",R)}},onClosed:F=>{var X,ne,ye,Te;const L=((X=h.current)==null?void 0:X.manualStop)??!1,R=f.current??((ne=h.current)==null?void 0:ne.threadIdGuess)??((ye=F.lastStateHistory)==null?void 0:ye.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&L)&&x(R);const z={...F,threadId:R,threadInfo:g.current,manualStop:L};try{i==null||i(z)}catch(q){console.warn("[useChatStreamingService] onStreamClosed handler failed",q)}try{(Te=A==null?void 0:A.onClosed)==null||Te.call(A,z)}catch(q){console.warn("[useChatStreamingService] downstream onClosed handler failed",q)}h.current&&(h.current=null)}})},[x,E,l,a,c,s,i,N]),P=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),_()},[_]);return b.useMemo(()=>({startStream:V,stop:P,isStreaming:D,error:B,setAuthToken:G,replayBufferedEvents:w}),[V,P,D,B,G,w])}const uc=b.createContext(null),dc=b.createContext(null),fc=b.createContext(null);b.createContext(!1);function kx({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l}){const{api:c,baseUrl:d}=di(),f=b.useMemo(()=>Cn(d),[d]),[p,h]=b.useState([]),[g,m]=b.useState(t),[y,x]=b.useState(!1),[w,S]=b.useState(null),[k,C]=b.useState(!1),[T,E]=b.useState(null),{state:N,seed:_,prepend:D,pushUser:B,onEvent:G}=Ql(),[V,P]=b.useState(!1),[M,A]=b.useState(!1),[F,L]=b.useState(null),[R,z]=b.useState([]),[X,ne]=b.useState([]),[ye,Te]=b.useState(!1),q=b.useMemo(()=>Xg(R),[R]),U=b.useRef(g),Z=b.useRef(null),$=b.useRef(null),Y=b.useRef(null),Q=b.useRef(null),de=b.useRef(!1),oe=b.useRef(null),_e=b.useRef(new Map),ze=b.useRef(new Map);b.useEffect(()=>{U.current=g},[g]);const se=b.useCallback(async H=>{var J,re;if(!H.threadId)return;const j=H.threadId;(J=H.onStart)==null||J.call(H),H.setLoading(!0);try{await H.action(j)}catch(ie){if(U.current===j){const ce=String(ie);(re=H.handleError)==null||re.call(H,ce),s==null||s(ce)}throw ie}finally{H.setLoading(!1)}},[s]),me=b.useCallback(async()=>{x(!0),S(null);try{const H=await c.listThreads();h(H??[])}catch(H){const j=String(H);S(j),s==null||s(j)}finally{x(!1)}},[c,s]),Pe=b.useCallback(H=>{if(!(H!=null&&H.threadId))return;const j={threadId:H.threadId,title:H.title||`Thread ${H.threadId.slice(0,8)}`,createdAt:H.createdAt||new Date().toISOString(),updatedAt:H.updatedAt||new Date().toISOString(),messageCount:H.messageCount??1};h(J=>{let re=!1;const ie=J.map(ce=>ce.threadId===j.threadId?(re=!0,console.debug("[ChatSessionProvider] thread_info: updating existing thread",j.threadId),{...ce,title:j.title??ce.title,updatedAt:j.updatedAt??ce.updatedAt,messageCount:j.messageCount??ce.messageCount}):ce);return re?ie:(console.debug("[ChatSessionProvider] thread_info: adding thread to list",j.threadId),[j,...J])})},[]),Ve=b.useCallback(H=>{const j=H.threadId??U.current;if(!j||U.current&&U.current!==j)return;const{checkpoints:J,timeline:re}=dr(H);if(!J.length)return;const ie=J.find(ce=>ce.messages&&ce.messages.length>0)??J.find(ce=>!!ce.checkpointId)??J[0];_((ie==null?void 0:ie.messages)??[],{checkpointId:(ie==null?void 0:ie.checkpointId)??null,checkpointNs:(ie==null?void 0:ie.checkpointNs)??null}),ne(re),z(J),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null),oe.current=`${j}:latest`,$.current=null,Y.current=null},[_]),ut=b.useCallback(H=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",H.threadId),Pe(H),U.current!==H.threadId&&((H.created??!U.current)&&($.current=H.threadId),Y.current=H.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),m(H.threadId))},[Pe]),{startStream:Ke,stop:qe,isStreaming:Qe,error:Ge,setAuthToken:et}=Tx({baseUrl:f,onThreadInfo:ut,onMessageEvent:G,onStateHistory:Ve,onUnhandledEvent:H=>{console.warn("[ChatSessionProvider] Unhandled event:",H.type)},onAuthError:i,onConnectionError:l}),st=b.useCallback(async H=>{try{const j=await c.createThread(H);return m(j.threadId),await me(),j.threadId}catch(j){return s==null||s(String(j)),null}},[c,me,s]),Mt=b.useCallback(async H=>{const j=p;h(re=>re.filter(ie=>ie.threadId!==H));const J=new AbortController;ze.current.set(H,J);try{await c.deleteThread(H),U.current===H&&(m(null),_([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",H)}catch(re){console.error("[ChatSessionProvider] Delete failed, restoring thread:",H,re),h(j),s==null||s(`Failed to delete thread: ${String(re)}`)}finally{ze.current.delete(H)}},[p,c,_,s]),gt=b.useCallback(async(H,j)=>{try{await c.updateThread(H,j),await me()}catch(J){s==null||s(String(J))}},[c,me,s]),Ct=b.useCallback(async(H,j)=>{if(!H)return;const J=`${H}:${j??"latest"}`,re=_e.current.get(J);if(re)return re;const ie=se({threadId:H,setLoading:C,onStart:()=>E(null),handleError:ce=>E(ce),action:async ce=>{const Xe=await c.getStateHistory({threadId:ce,checkpointId:j||void 0});if(U.current!==ce){console.log(`[ChatSessionProvider] Thread changed during load (was ${ce}, now ${U.current}), discarding stale data`);return}const{checkpoints:Ie,timeline:at}=dr(Xe),ht=Ie.find(Kt=>Kt.messages&&Kt.messages.length>0)??(j?Ie.find(Kt=>Kt.checkpointId===j):null)??Ie[0];_((ht==null?void 0:ht.messages)??[],{checkpointId:(ht==null?void 0:ht.checkpointId)??null,checkpointNs:(ht==null?void 0:ht.checkpointNs)??null}),ne(at),z(Ie),P(!!(ht!=null&&ht.nextCursor)),L((ht==null?void 0:ht.nextCursor)??null)}});_e.current.set(J,ie);try{await ie}finally{_e.current.delete(J)}return U.current===H&&(oe.current=J),ie},[c,_,s,se]),it=b.useCallback(async(H,j,J)=>{J!=null&&J.clearProgress&&Jl(),Q.current=H;try{await Ct(H,j)}finally{Q.current===H&&(Q.current=null)}},[Ct]);b.useEffect(()=>{if(!o||!g||k||Qe)return;if($.current===g){$.current=null,Z.current=g;return}if(Y.current===g){Z.current=g;return}if(Q.current===g){Q.current=null,Z.current=g;return}if(Z.current===g)return;Z.current=g;const H=!de.current&&!!n&&g===t;let j;H&&n?(j=n,de.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",j,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const J=`${g}:${j??"latest"}`;oe.current!==J&&it(g,j)},[o,g,n,r,t,k,Qe,it]);const St=b.useCallback(async(H,j)=>{Jl();const J=U.current;await se({threadId:J,setLoading:Te,action:async re=>{const ie=await c.getStateHistory({threadId:re,checkpointId:H,checkpointNs:j??void 0});if(U.current!==re){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${re}, now ${U.current}), discarding stale data`);return}const{checkpoints:ce,timeline:Xe}=dr(ie),Ie=ce.find(at=>at.checkpointId===H&&(j?at.checkpointNs===j:!0));if(!Ie){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:H,checkpointNs:j});return}ne(Xe),z(ce),_(Ie.messages??[],{checkpointId:Ie.checkpointId??null,checkpointNs:Ie.checkpointNs??null})}}).catch(()=>{})},[c,_,s,se]),Pt=b.useCallback((H,j)=>{_(N.messages,{checkpointId:H??null,checkpointNs:j??null})},[_,N.messages]),zt=b.useCallback(async()=>{U.current&&await it(U.current)},[it]),nn=b.useCallback(async()=>{const H=U.current;!H||!F||await se({threadId:H,setLoading:A,action:async j=>{const J=await c.getStateHistory({threadId:j,checkpointId:F});if(U.current!==j)return;const{checkpoints:re}=dr(J);if(re.length>0){const ie=re[re.length-1];D((ie==null?void 0:ie.messages)??[]),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null)}}}).catch(()=>{})},[c,F,D,s,se]),Le=b.useCallback(async()=>{_([],{}),m(null),qe(),z([]),ne([]),P(!1),L(null),C(!1),Te(!1),A(!1),E(null);try{await c.getAgent("default")}catch(H){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",H)}},[_,qe,c]),Sn=b.useCallback(async(H,j,J)=>{const re=U.current;if(!re)throw new Error("No active thread to handle interrupt");const ie=j?J??!0:!1;try{const ce={threadId:re,checkpointId:N.lastCheckpointId??void 0,checkpointNs:N.lastCheckpointNs??void 0,command:{kind:"resume",value:ie}};Ke(ce)}catch(ce){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${H}:`,ce),ce}},[N.lastCheckpointId,N.lastCheckpointNs,Ke]);b.useEffect(()=>{me()},[me]),b.useEffect(()=>{a==null||a(g)},[g,a]);const tt=b.useCallback(async(H,j)=>{let J=U.current;const re=(H==null?void 0:H.text)??"",ie=(H==null?void 0:H.attachments)??[],ce=(re==null?void 0:re.trim())??"",Xe={...(H==null?void 0:H.payload)??{}},Ie=Array.isArray(Xe.messages)?Xe.messages:void 0;Ie&&delete Xe.messages;const at=!!(Ie&&Ie.length);if(!J&&!ce&&ie.length===0&&!at)return;if(!J){const we=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Be=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);J=`${we}${Be}`,$.current=J,m(J)}const{contentParts:ht,filesInfo:Kt}=await kg(c,ie),Hn=[...ht];ce&&Hn.push({type:"text",text:re});const Ar=j==null?void 0:j.originalMessageId,Nr=!!(j!=null&&j.edit&&Ar),po=!at&&Hn.length>0;let Nn=null;po&&(Nn={id:Nr?Ar:`msg-${Date.now()}`,role:"user",content:Hn,createdAt:new Date().toISOString()},Nr||B(Nn));const I=at?Ie:Nn?[Nn]:[],W={...Xe,...Kt.length?{files_info:Kt}:{}};I.length?W.messages=I:"messages"in W||(W.messages=[]);const ae={threadId:J,payload:W,checkpointId:(j==null?void 0:j.checkpointId)??N.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??N.lastCheckpointNs??void 0,edit:!!(j!=null&&j.edit),timelineCheckpoints:X};Ke(ae)},[c,B,N,Ke,X]),We=b.useMemo(()=>({threads:p,currentThreadId:g,setCurrentThreadId:m,isLoading:y,error:w,actions:{createThread:st,deleteThread:Mt,renameThread:gt,refreshThreads:me}}),[p,g,y,w,st,Mt,gt,me]),pt=b.useMemo(()=>{const H=N.assemblingId??null;return H?{assemblingMessageId:H}:null},[N.assemblingId]),Rt=b.useMemo(()=>({threadId:g,messages:N.messages,interrupt:null,checkpoint:{id:N.lastCheckpointId??null,namespace:N.lastCheckpointNs??null},checkpoints:R,timelineCheckpoints:X,metadata:pt,isLoading:k,isHistoryLoading:M,isLoadingCheckpoint:ye,error:T,hasMore:V,loadOlder:nn,clearState:Le,navigateToCheckpoint:St,setCurrentCheckpointId:Pt,returnToLatest:zt,loadThread:it,clearThread:Le,respondToInterrupt:Sn,messagePreviews:q}),[g,N,R,X,k,M,ye,T,V,nn,Le,St,Pt,zt,it,Sn,q,pt]),Ye=b.useMemo(()=>({isStreaming:Qe,error:Ge,connectionState:Qe?"connected":"idle",submit:tt,send:tt,stop:qe,setAuthToken:et}),[Qe,Ge,tt,qe,et]);return u.jsx(uc.Provider,{value:We,children:u.jsx(dc.Provider,{value:Rt,children:u.jsx(fc.Provider,{value:Ye,children:e})})})}function jo(){const e=b.useContext(uc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Mo(){const e=b.useContext(dc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function pc(){const e=b.useContext(fc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Po({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Cg,{apiConfig:t,children:u.jsx(kx,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,children:e})})}function te(...e){return Xh.twMerge(Yh.clsx(e))}const Ex=ho.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Je=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Vn.Slot:"button";return u.jsx(i,{className:te(Ex({variant:t,size:n,className:e})),ref:s,...o})});Je.displayName="Button";const hc=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));hc.displayName="Textarea";function mc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:p="",allowEmptySend:h=!1}){const g=i!==void 0,[m,y]=b.useState(e),x=(g?i:m)??"",[w,S]=b.useTransition(),k=b.useRef(null),C=b.useRef(0),T=b.useRef(null);b.useEffect(()=>{g||(y(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,g]);const E=b.useCallback(()=>{const M=k.current;M&&(M.style.height="auto",M.style.height=`${M.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const N=b.useCallback((M,{fromUser:A})=>{g||y(M),A&&(a==null||a(M))},[g,a]),_=b.useCallback(async M=>{M&&M.preventDefault();const A=(x??"").trim();if(!A&&!h)return;const F=++C.current;T.current={id:F,shouldClear:!0},S(()=>{var L,R,z;try{const X=l(A);X&&typeof X.then=="function"?X.then(()=>{var ne,ye;((ne=T.current)==null?void 0:ne.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((ye=T.current)==null?void 0:ye.id)===F&&(T.current=null)}).catch(()=>{var ne;((ne=T.current)==null?void 0:ne.id)===F&&(T.current=null)}):(((L=T.current)==null?void 0:L.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((R=T.current)==null?void 0:R.id)===F&&(T.current=null))}catch{((z=T.current)==null?void 0:z.id)===F&&(T.current=null)}})},[x,l,h,g,a]),D=b.useCallback(M=>{const A=M.target.value;N(A,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),B=b.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),_()):M.key==="Escape"&&t&&(M.preventDefault(),c==null||c())},[_,t,c]),P=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${p}`;return u.jsx("form",{onSubmit:M=>void _(M),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(hc,{ref:k,value:x,onChange:D,onKeyDown:B,placeholder:t?"Edit your message...":n,className:P,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(Je,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(le.Square,{size:16})}):u.jsx(Je,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!h||w,children:u.jsx(le.Send,{size:16})})})]})})}const Ix=b.memo(mc);function pe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function gc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function gi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=gc(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():gc(e[o],null)}}}}function $e(...e){return v.useCallback(gi(...e),e)}function Ax(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Tn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:p,children:h,...g}=f,m=((x=p==null?void 0:p[e])==null?void 0:x[l])||a,y=v.useMemo(()=>g,Object.values(g));return u.jsx(m.Provider,{value:y,children:h})};c.displayName=s+"Provider";function d(f,p){var m;const h=((m=p==null?void 0:p[e])==null?void 0:m[l])||a,g=v.useContext(h);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Nx(o,...t)]}function Nx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},_x=v[" useInsertionEffect ".trim().toString()]||kt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=jx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const p=Mx(d)?d(e):d;p!==e&&((f=i.current)==null||f.call(i,p))}else s(d)},[a,e,s,i]);return[l,c]}function jx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return _x(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Mx(e){return typeof e=="function"}var Px=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ne=Px.reduce((e,t)=>{const n=Vn.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function xc(e,t){e&&mo.flushSync(()=>e.dispatchEvent(t))}function xi(e){const t=e+"CollectionProvider",[n,r]=Tn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:y,children:x}=m,w=b.useRef(null),S=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=Vn.createSlot(a),c=b.forwardRef((m,y)=>{const{scope:x,children:w}=m,S=s(a,x),k=$e(y,S.collectionRef);return u.jsx(l,{ref:k,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=Vn.createSlot(d),h=b.forwardRef((m,y)=>{const{scope:x,children:w,...S}=m,k=b.useRef(null),C=$e(y,k),T=s(d,x);return b.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:C,children:w})});h.displayName=d;function g(m){const y=s(e+"CollectionConsumer",m);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},g,r]}var Rx=v.createContext(void 0);function Ro(e){const t=v.useContext(Rx);return e||t||"ltr"}function Et(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ox(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Dx="DismissableLayer",yi="dismissableLayer.update",Lx="dismissableLayer.pointerDownOutside",$x="dismissableLayer.focusOutside",yc,vc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Oo=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(vc),[d,f]=v.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),g=$e(t,E=>f(E)),m=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=m.indexOf(y),w=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=x,C=zx(E=>{const N=E.target,_=[...c.branches].some(D=>D.contains(N));!k||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),T=Ux(E=>{const N=E.target;[...c.branches].some(D=>D.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return Ox(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(yc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),wc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=yc)}},[d,p,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),wc())},[d,c]),v.useEffect(()=>{const E=()=>h({});return document.addEventListener(yi,E),()=>document.removeEventListener(yi,E)},[]),u.jsx(Ne.div,{...l,ref:g,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:pe(e.onFocusCapture,T.onFocusCapture),onBlurCapture:pe(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:pe(e.onPointerDownCapture,C.onPointerDownCapture)})});Oo.displayName=Dx;var Fx="DismissableLayerBranch",Bx=v.forwardRef((e,t)=>{const n=v.useContext(vc),r=v.useRef(null),o=$e(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ne.div,{...e,ref:o})});Bx.displayName=Fx;function zx(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){bc(Lx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Ux(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&bc($x,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function wc(){const e=new CustomEvent(yi);document.dispatchEvent(e)}function bc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?xc(o,s):o.dispatchEvent(s)}var vi=0;function wi(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Sc()),document.body.insertAdjacentElement("beforeend",e[1]??Sc()),vi++,()=>{vi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),vi--}},[])}function Sc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var bi="focusScope.autoFocusOnMount",Si="focusScope.autoFocusOnUnmount",Cc={bubbles:!1,cancelable:!0},Hx="FocusScope",Do=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=Et(o),d=Et(s),f=v.useRef(null),p=$e(t,m=>l(m)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(S){if(h.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:jn(f.current,{select:!0})},y=function(S){if(h.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||jn(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&jn(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,h.paused]),v.useEffect(()=>{if(a){Ec.add(h);const m=document.activeElement;if(!a.contains(m)){const x=new CustomEvent(bi,Cc);a.addEventListener(bi,c),a.dispatchEvent(x),x.defaultPrevented||(Wx(Yx(Tc(a)),{select:!0}),document.activeElement===m&&jn(a))}return()=>{a.removeEventListener(bi,c),setTimeout(()=>{const x=new CustomEvent(Si,Cc);a.addEventListener(Si,d),a.dispatchEvent(x),x.defaultPrevented||jn(m??document.body,{select:!0}),a.removeEventListener(Si,d),Ec.remove(h)},0)}}},[a,c,d,h]);const g=v.useCallback(m=>{if(!n&&!r||h.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,x=document.activeElement;if(y&&x){const w=m.currentTarget,[S,k]=Vx(w);S&&k?!m.shiftKey&&x===k?(m.preventDefault(),n&&jn(S,{select:!0})):m.shiftKey&&x===S&&(m.preventDefault(),n&&jn(k,{select:!0})):x===w&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Ne.div,{tabIndex:-1,...i,ref:p,onKeyDown:g})});Do.displayName=Hx;function Wx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(jn(r,{select:t}),document.activeElement!==n)return}function Vx(e){const t=Tc(e),n=kc(t,e),r=kc(t.reverse(),e);return[n,r]}function Tc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function kc(e,t){for(const n of e)if(!Kx(n,{upTo:t}))return n}function Kx(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function qx(e){return e instanceof HTMLInputElement&&"select"in e}function jn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&qx(e)&&t&&e.select()}}var Ec=Gx();function Gx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ic(e,t),e.unshift(t)},remove(t){var n;e=Ic(e,t),(n=e[0])==null||n.resume()}}}function Ic(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Yx(e){return e.filter(t=>t.tagName!=="A")}var Xx=v[" useId ".trim().toString()]||(()=>{}),Jx=0;function kn(e){const[t,n]=v.useState(Xx());return kt(()=>{n(r=>r??String(Jx++))},[e]),t?`radix-${t}`:""}const Zx=["top","right","bottom","left"],Mn=Math.min,Ut=Math.max,Lo=Math.round,$o=Math.floor,pn=e=>({x:e,y:e}),Qx={left:"right",right:"left",bottom:"top",top:"bottom"},ey={start:"end",end:"start"};function Ci(e,t,n){return Ut(e,Mn(t,n))}function En(e,t){return typeof e=="function"?e(t):e}function In(e){return e.split("-")[0]}function hr(e){return e.split("-")[1]}function Ti(e){return e==="x"?"y":"x"}function ki(e){return e==="y"?"height":"width"}const ty=new Set(["top","bottom"]);function hn(e){return ty.has(In(e))?"y":"x"}function Ei(e){return Ti(hn(e))}function ny(e,t,n){n===void 0&&(n=!1);const r=hr(e),o=Ei(e),s=ki(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Fo(i)),[i,Fo(i)]}function ry(e){const t=Fo(e);return[Ii(e),t,Ii(t)]}function Ii(e){return e.replace(/start|end/g,t=>ey[t])}const Ac=["left","right"],Nc=["right","left"],oy=["top","bottom"],sy=["bottom","top"];function iy(e,t,n){switch(e){case"top":case"bottom":return n?t?Nc:Ac:t?Ac:Nc;case"left":case"right":return t?oy:sy;default:return[]}}function ay(e,t,n,r){const o=hr(e);let s=iy(In(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ii)))),s}function Fo(e){return e.replace(/left|right|bottom|top/g,t=>Qx[t])}function ly(e){return{top:0,right:0,bottom:0,left:0,...e}}function _c(e){return typeof e!="number"?ly(e):{top:e,right:e,bottom:e,left:e}}function Bo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function jc(e,t,n){let{reference:r,floating:o}=e;const s=hn(t),i=Ei(t),a=ki(i),l=In(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:d,y:r.y-o.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:f};break;case"left":h={x:r.x-o.width,y:f};break;default:h={x:r.x,y:r.y}}switch(hr(t)){case"start":h[i]-=p*(n&&c?-1:1);break;case"end":h[i]+=p*(n&&c?-1:1);break}return h}const cy=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=jc(c,r,l),p=r,h={},g=0;for(let m=0;m<a.length;m++){const{name:y,fn:x}=a[m],{x:w,y:S,data:k,reset:C}=await x({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,h={...h,[y]:{...h[y],...k}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:f}=jc(c,p,l)),m=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function $r(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:h=0}=En(t,e),g=_c(h),y=a[p?f==="floating"?"reference":"floating":f],x=Bo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},C=Bo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(x.top-C.top+g.top)/k.y,bottom:(C.bottom-x.bottom+g.bottom)/k.y,left:(x.left-C.left+g.left)/k.x,right:(C.right-x.right+g.right)/k.x}}const uy=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=En(e,t)||{};if(c==null)return{};const f=_c(d),p={x:n,y:r},h=Ei(o),g=ki(h),m=await i.getDimensions(c),y=h==="y",x=y?"top":"left",w=y?"bottom":"right",S=y?"clientHeight":"clientWidth",k=s.reference[g]+s.reference[h]-p[h]-s.floating[g],C=p[h]-s.reference[h],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[g]);const N=k/2-C/2,_=E/2-m[g]/2-1,D=Mn(f[x],_),B=Mn(f[w],_),G=D,V=E-m[g]-B,P=E/2-m[g]/2+N,M=Ci(G,P,V),A=!l.arrow&&hr(o)!=null&&P!==M&&s.reference[g]/2-(P<G?D:B)-m[g]/2<0,F=A?P<G?P-G:P-V:0;return{[h]:p[h]+F,data:{[h]:M,centerOffset:P-M-F,...A&&{alignmentOffset:F}},reset:A}}}),dy=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...y}=En(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=In(o),w=hn(a),S=In(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(S||!m?[Fo(a)]:ry(a)),T=g!=="none";!p&&T&&C.push(...ay(a,m,g,k));const E=[a,...C],N=await $r(t,y),_=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(N[x]),f){const P=ny(o,i,k);_.push(N[P[0]],N[P[1]])}if(D=[...D,{placement:o,overflows:_}],!_.every(P=>P<=0)){var B,G;const P=(((B=s.flip)==null?void 0:B.index)||0)+1,M=E[P];if(M&&(!(f==="alignment"?w!==hn(M):!1)||D.every(L=>hn(L.placement)===w?L.overflows[0]>0:!0)))return{data:{index:P,overflows:D},reset:{placement:M}};let A=(G=D.filter(F=>F.overflows[0]<=0).sort((F,L)=>F.overflows[1]-L.overflows[1])[0])==null?void 0:G.placement;if(!A)switch(h){case"bestFit":{var V;const F=(V=D.filter(L=>{if(T){const R=hn(L.placement);return R===w||R==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(R=>R>0).reduce((R,z)=>R+z,0)]).sort((L,R)=>L[1]-R[1])[0])==null?void 0:V[0];F&&(A=F);break}case"initialPlacement":A=a;break}if(o!==A)return{reset:{placement:A}}}return{}}}};function Mc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Pc(e){return Zx.some(t=>e[t]>=0)}const fy=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=En(e,t);switch(r){case"referenceHidden":{const s=await $r(t,{...o,elementContext:"reference"}),i=Mc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Pc(i)}}}case"escaped":{const s=await $r(t,{...o,altBoundary:!0}),i=Mc(s,n.floating);return{data:{escapedOffsets:i,escaped:Pc(i)}}}default:return{}}}}},Rc=new Set(["left","top"]);async function py(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=In(n),a=hr(n),l=hn(n)==="y",c=Rc.has(i)?-1:1,d=s&&l?-1:1,f=En(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:g}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof g=="number"&&(h=a==="end"?g*-1:g),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const hy=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await py(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},my=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:w}=y;return{x,y:w}}},...l}=En(e,t),c={x:n,y:r},d=await $r(t,l),f=hn(In(o)),p=Ti(f);let h=c[p],g=c[f];if(s){const y=p==="y"?"top":"left",x=p==="y"?"bottom":"right",w=h+d[y],S=h-d[x];h=Ci(w,h,S)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=g+d[y],S=g-d[x];g=Ci(w,g,S)}const m=a.fn({...t,[p]:h,[f]:g});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[f]:i}}}}}},gy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=En(e,t),d={x:n,y:r},f=hn(o),p=Ti(f);let h=d[p],g=d[f];const m=En(a,t),y=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=p==="y"?"height":"width",k=s.reference[p]-s.floating[S]+y.mainAxis,C=s.reference[p]+s.reference[S]-y.mainAxis;h<k?h=k:h>C&&(h=C)}if(c){var x,w;const S=p==="y"?"width":"height",k=Rc.has(In(o)),C=s.reference[f]-s.floating[S]+(k&&((x=i.offset)==null?void 0:x[f])||0)+(k?0:y.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((w=i.offset)==null?void 0:w[f])||0)-(k?y.crossAxis:0);g<C?g=C:g>T&&(g=T)}return{[p]:h,[f]:g}}}},xy=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=En(e,t),d=await $r(t,c),f=In(o),p=hr(o),h=hn(o)==="y",{width:g,height:m}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=p==="end"?"top":"bottom");const w=m-d.top-d.bottom,S=g-d.left-d.right,k=Mn(m-d[y],w),C=Mn(g-d[x],S),T=!t.middlewareData.shift;let E=k,N=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),T&&!p){const D=Ut(d.left,0),B=Ut(d.right,0),G=Ut(d.top,0),V=Ut(d.bottom,0);h?N=g-2*(D!==0||B!==0?D+B:Ut(d.left,d.right)):E=m-2*(G!==0||V!==0?G+V:Ut(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const _=await i.getDimensions(a.floating);return g!==_.width||m!==_.height?{reset:{rects:!0}}:{}}}};function zo(){return typeof window<"u"}function mr(e){return Oc(e)?(e.nodeName||"").toLowerCase():"#document"}function Ht(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function mn(e){var t;return(t=(Oc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Oc(e){return zo()?e instanceof Node||e instanceof Ht(e).Node:!1}function sn(e){return zo()?e instanceof Element||e instanceof Ht(e).Element:!1}function gn(e){return zo()?e instanceof HTMLElement||e instanceof Ht(e).HTMLElement:!1}function Dc(e){return!zo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ht(e).ShadowRoot}const yy=new Set(["inline","contents"]);function Fr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!yy.has(o)}const vy=new Set(["table","td","th"]);function wy(e){return vy.has(mr(e))}const by=[":popover-open",":modal"];function Uo(e){return by.some(t=>{try{return e.matches(t)}catch{return!1}})}const Sy=["transform","translate","scale","rotate","perspective"],Cy=["transform","translate","scale","rotate","perspective","filter"],Ty=["paint","layout","strict","content"];function Ai(e){const t=Ni(),n=sn(e)?an(e):e;return Sy.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Cy.some(r=>(n.willChange||"").includes(r))||Ty.some(r=>(n.contain||"").includes(r))}function ky(e){let t=Pn(e);for(;gn(t)&&!gr(t);){if(Ai(t))return t;if(Uo(t))return null;t=Pn(t)}return null}function Ni(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Ey=new Set(["html","body","#document"]);function gr(e){return Ey.has(mr(e))}function an(e){return Ht(e).getComputedStyle(e)}function Ho(e){return sn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Pn(e){if(mr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Dc(e)&&e.host||mn(e);return Dc(t)?t.host:t}function Lc(e){const t=Pn(e);return gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:gn(t)&&Fr(t)?t:Lc(t)}function Br(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Lc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Ht(o);if(s){const a=_i(i);return t.concat(i,i.visualViewport||[],Fr(o)?o:[],a&&n?Br(a):[])}return t.concat(o,Br(o,[],n))}function _i(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function $c(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=gn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Lo(n)!==s||Lo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ji(e){return sn(e)?e:e.contextElement}function xr(e){const t=ji(e);if(!gn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=$c(t);let i=(s?Lo(n.width):n.width)/r,a=(s?Lo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Iy=pn(0);function Fc(e){const t=Ht(e);return!Ni()||!t.visualViewport?Iy:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Ay(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Ht(e)?!1:t}function Yn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ji(e);let i=pn(1);t&&(r?sn(r)&&(i=xr(r)):i=xr(e));const a=Ay(s,n,r)?Fc(s):pn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const p=Ht(s),h=r&&sn(r)?Ht(r):r;let g=p,m=_i(g);for(;m&&r&&h!==g;){const y=xr(m),x=m.getBoundingClientRect(),w=an(m),S=x.left+(m.clientLeft+parseFloat(w.paddingLeft))*y.x,k=x.top+(m.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=k,g=Ht(m),m=_i(g)}}return Bo({width:d,height:f,x:l,y:c})}function Wo(e,t){const n=Ho(e).scrollLeft;return t?t.left+n:Yn(mn(e)).left+n}function Bc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Wo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Ny(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=mn(r),a=t?Uo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=gn(r);if((f||!f&&!s)&&((mr(r)!=="body"||Fr(i))&&(l=Ho(r)),gn(r))){const h=Yn(r);c=xr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?Bc(i,l):pn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+p.x,y:n.y*c.y-l.scrollTop*c.y+d.y+p.y}}function _y(e){return Array.from(e.getClientRects())}function jy(e){const t=mn(e),n=Ho(e),r=e.ownerDocument.body,o=Ut(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ut(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Wo(e);const a=-n.scrollTop;return an(r).direction==="rtl"&&(i+=Ut(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const zc=25;function My(e,t){const n=Ht(e),r=mn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ni();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Wo(r);if(c<=0){const d=r.ownerDocument,f=d.body,p=getComputedStyle(f),h=d.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,g=Math.abs(r.clientWidth-f.clientWidth-h);g<=zc&&(s-=g)}else c<=zc&&(s+=c);return{width:s,height:i,x:a,y:l}}const Py=new Set(["absolute","fixed"]);function Ry(e,t){const n=Yn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=gn(e)?xr(e):pn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Uc(e,t,n){let r;if(t==="viewport")r=My(e,n);else if(t==="document")r=jy(mn(e));else if(sn(t))r=Ry(t,n);else{const o=Fc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Bo(r)}function Hc(e,t){const n=Pn(e);return n===t||!sn(n)||gr(n)?!1:an(n).position==="fixed"||Hc(n,t)}function Oy(e,t){const n=t.get(e);if(n)return n;let r=Br(e,[],!1).filter(a=>sn(a)&&mr(a)!=="body"),o=null;const s=an(e).position==="fixed";let i=s?Pn(e):e;for(;sn(i)&&!gr(i);){const a=an(i),l=Ai(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Py.has(o.position)||Fr(i)&&!l&&Hc(e,i))?r=r.filter(d=>d!==i):o=a,i=Pn(i)}return t.set(e,r),r}function Dy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Uo(t)?[]:Oy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Uc(t,d,o);return c.top=Ut(f.top,c.top),c.right=Mn(f.right,c.right),c.bottom=Mn(f.bottom,c.bottom),c.left=Ut(f.left,c.left),c},Uc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Ly(e){const{width:t,height:n}=$c(e);return{width:t,height:n}}function $y(e,t,n){const r=gn(t),o=mn(t),s=n==="fixed",i=Yn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=Wo(o)}if(r||!r&&!s)if((mr(t)!=="body"||Fr(o))&&(a=Ho(t)),r){const h=Yn(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Bc(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,p=i.top+a.scrollTop-l.y-d.y;return{x:f,y:p,width:i.width,height:i.height}}function Mi(e){return an(e).position==="static"}function Wc(e,t){if(!gn(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return mn(e)===n&&(n=n.ownerDocument.body),n}function Vc(e,t){const n=Ht(e);if(Uo(e))return n;if(!gn(e)){let o=Pn(e);for(;o&&!gr(o);){if(sn(o)&&!Mi(o))return o;o=Pn(o)}return n}let r=Wc(e,t);for(;r&&wy(r)&&Mi(r);)r=Wc(r,t);return r&&gr(r)&&Mi(r)&&!Ai(r)?n:r||ky(e)||n}const Fy=async function(e){const t=this.getOffsetParent||Vc,n=this.getDimensions,r=await n(e.floating);return{reference:$y(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function By(e){return an(e).direction==="rtl"}const zy={convertOffsetParentRelativeRectToViewportRelativeRect:Ny,getDocumentElement:mn,getClippingRect:Dy,getOffsetParent:Vc,getElementRects:Fy,getClientRects:_y,getDimensions:Ly,getScale:xr,isElement:sn,isRTL:By};function Kc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Uy(e,t){let n=null,r;const o=mn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:p,height:h}=c;if(a||t(),!p||!h)return;const g=$o(f),m=$o(o.clientWidth-(d+p)),y=$o(o.clientHeight-(f+h)),x=$o(d),S={rootMargin:-g+"px "+-m+"px "+-y+"px "+-x+"px",threshold:Ut(0,Mn(1,l))||1};let k=!0;function C(T){const E=T[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Kc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(C,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return i(!0),s}function Hy(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=ji(e),d=o||s?[...c?Br(c):[],...Br(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Uy(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(x=>{let[w]=x;w&&w.target===c&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=h)==null||S.observe(t)})),n()}),c&&!l&&h.observe(c),h.observe(t));let g,m=l?Yn(e):null;l&&y();function y(){const x=Yn(e);m&&!Kc(m,x)&&n(),m=x,g=requestAnimationFrame(y)}return n(),()=>{var x;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(x=h)==null||x.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const Wy=hy,Vy=my,Ky=dy,qy=xy,Gy=fy,qc=uy,Yy=gy,Xy=(e,t,n)=>{const r=new Map,o={platform:zy,...n},s={...o.platform,_c:r};return cy(e,t,{...o,platform:s})};var Jy=typeof document<"u",Zy=function(){},Vo=Jy?b.useLayoutEffect:Zy;function Ko(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ko(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Ko(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Gc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Yc(e,t){const n=Gc(e);return Math.round(t*n)/n}function Pi(e){const t=v.useRef(e);return Vo(()=>{t.current=e}),t}function Qy(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=v.useState(r);Ko(p,r)||h(r);const[g,m]=v.useState(null),[y,x]=v.useState(null),w=v.useCallback(L=>{L!==T.current&&(T.current=L,m(L))},[]),S=v.useCallback(L=>{L!==E.current&&(E.current=L,x(L))},[]),k=s||g,C=i||y,T=v.useRef(null),E=v.useRef(null),N=v.useRef(d),_=l!=null,D=Pi(l),B=Pi(o),G=Pi(c),V=v.useCallback(()=>{if(!T.current||!E.current)return;const L={placement:t,strategy:n,middleware:p};B.current&&(L.platform=B.current),Xy(T.current,E.current,L).then(R=>{const z={...R,isPositioned:G.current!==!1};P.current&&!Ko(N.current,z)&&(N.current=z,mo.flushSync(()=>{f(z)}))})},[p,t,n,B,G]);Vo(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f(L=>({...L,isPositioned:!1})))},[c]);const P=v.useRef(!1);Vo(()=>(P.current=!0,()=>{P.current=!1}),[]),Vo(()=>{if(k&&(T.current=k),C&&(E.current=C),k&&C){if(D.current)return D.current(k,C,V);V()}},[k,C,V,D,_]);const M=v.useMemo(()=>({reference:T,floating:E,setReference:w,setFloating:S}),[w,S]),A=v.useMemo(()=>({reference:k,floating:C}),[k,C]),F=v.useMemo(()=>{const L={position:n,left:0,top:0};if(!A.floating)return L;const R=Yc(A.floating,d.x),z=Yc(A.floating,d.y);return a?{...L,transform:"translate("+R+"px, "+z+"px)",...Gc(A.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:R,top:z}},[n,a,A.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:V,refs:M,elements:A,floatingStyles:F}),[d,V,M,A,F])}const ev=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?qc({element:r.current,padding:o}).fn(n):{}:r?qc({element:r,padding:o}).fn(n):{}}}},tv=(e,t)=>({...Wy(e),options:[e,t]}),nv=(e,t)=>({...Vy(e),options:[e,t]}),rv=(e,t)=>({...Yy(e),options:[e,t]}),ov=(e,t)=>({...Ky(e),options:[e,t]}),sv=(e,t)=>({...qy(e),options:[e,t]}),iv=(e,t)=>({...Gy(e),options:[e,t]}),av=(e,t)=>({...ev(e),options:[e,t]});var lv="Arrow",Xc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Ne.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Xc.displayName=lv;var cv=Xc;function Jc(e){const[t,n]=v.useState(void 0);return kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ri="Popper",[Zc,qo]=Tn(Ri),[uv,Qc]=Zc(Ri),eu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(uv,{scope:t,anchor:r,onAnchorChange:o,children:n})};eu.displayName=Ri;var tu="PopperAnchor",nu=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Qc(tu,n),i=v.useRef(null),a=$e(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Ne.div,{...o,ref:a})});nu.displayName=tu;var Oi="PopperContent",[dv,fv]=Zc(Oi),ru=v.forwardRef((e,t)=>{var Z,$,Y,Q,de,oe;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:g,...m}=e,y=Qc(Oi,n),[x,w]=v.useState(null),S=$e(t,_e=>w(_e)),[k,C]=v.useState(null),T=Jc(k),E=(T==null?void 0:T.width)??0,N=(T==null?void 0:T.height)??0,_=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},B=Array.isArray(c)?c:[c],G=B.length>0,V={padding:D,boundary:B.filter(hv),altBoundary:G},{refs:P,floatingStyles:M,placement:A,isPositioned:F,middlewareData:L}=Qy({strategy:"fixed",placement:_,whileElementsMounted:(..._e)=>Hy(..._e,{animationFrame:h==="always"}),elements:{reference:y.anchor},middleware:[tv({mainAxis:o+N,alignmentAxis:i}),l&&nv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?rv():void 0,...V}),l&&ov({...V}),sv({...V,apply:({elements:_e,rects:ze,availableWidth:se,availableHeight:me})=>{const{width:Pe,height:Ve}=ze.reference,ut=_e.floating.style;ut.setProperty("--radix-popper-available-width",`${se}px`),ut.setProperty("--radix-popper-available-height",`${me}px`),ut.setProperty("--radix-popper-anchor-width",`${Pe}px`),ut.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),k&&av({element:k,padding:a}),mv({arrowWidth:E,arrowHeight:N}),p&&iv({strategy:"referenceHidden",...V})]}),[R,z]=iu(A),X=Et(g);kt(()=>{F&&(X==null||X())},[F,X]);const ne=(Z=L.arrow)==null?void 0:Z.x,ye=($=L.arrow)==null?void 0:$.y,Te=((Y=L.arrow)==null?void 0:Y.centerOffset)!==0,[q,U]=v.useState();return kt(()=>{x&&U(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:P.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:F?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:q,"--radix-popper-transform-origin":[(Q=L.transformOrigin)==null?void 0:Q.x,(de=L.transformOrigin)==null?void 0:de.y].join(" "),...((oe=L.hide)==null?void 0:oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(dv,{scope:n,placedSide:R,onArrowChange:C,arrowX:ne,arrowY:ye,shouldHideArrow:Te,children:u.jsx(Ne.div,{"data-side":R,"data-align":z,...m,ref:S,style:{...m.style,animation:F?void 0:"none"}})})})});ru.displayName=Oi;var ou="PopperArrow",pv={top:"bottom",right:"left",bottom:"top",left:"right"},su=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=fv(ou,r),i=pv[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(cv,{...o,ref:n,style:{...o.style,display:"block"}})})});su.displayName=ou;function hv(e){return e!==null}var mv=e=>({name:"transformOrigin",options:e,fn(t){var y,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=iu(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,h=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let g="",m="";return c==="bottom"?(g=i?f:`${p}px`,m=`${-l}px`):c==="top"?(g=i?f:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,m=i?f:`${h}px`):c==="left"&&(g=`${r.floating.width+l}px`,m=i?f:`${h}px`),{data:{x:g,y:m}}}});function iu(e){const[t,n="center"]=e.split("-");return[t,n]}var au=eu,lu=nu,cu=ru,uu=su,gv="Portal",Go=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ys.createPortal(u.jsx(Ne.div,{...r,ref:t}),i):null});Go.displayName=gv;function xv(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Xt=e=>{const{present:t,children:n}=e,r=yv(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=$e(r.ref,vv(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Xt.displayName="Presence";function yv(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=xv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Yo(r.current);s.current=a==="mounted"?c:"none"},[a]),kt(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=Yo(c);e?l("MOUNT"):h==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const m=Yo(r.current).includes(CSS.escape(h.animationName));if(h.target===t&&m&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=h=>{h.target===t&&(s.current=Yo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Yo(e){return(e==null?void 0:e.animationName)||"none"}function vv(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Di="rovingFocusGroup.onEntryFocus",wv={bubbles:!1,cancelable:!0},zr="RovingFocusGroup",[Li,du,bv]=xi(zr),[Sv,fu]=Tn(zr,[bv]),[Cv,Tv]=Sv(zr),pu=v.forwardRef((e,t)=>u.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(kv,{...e,ref:t})})}));pu.displayName=zr;var kv=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,p=v.useRef(null),h=$e(t,p),g=Ro(s),[m,y]=pr({prop:i,defaultProp:a??null,onChange:l,caller:zr}),[x,w]=v.useState(!1),S=Et(c),k=du(n),C=v.useRef(!1),[T,E]=v.useState(0);return v.useEffect(()=>{const N=p.current;if(N)return N.addEventListener(Di,S),()=>N.removeEventListener(Di,S)},[S]),u.jsx(Cv,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:m,onItemFocus:v.useCallback(N=>y(N),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:v.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Ne.div,{tabIndex:x||T===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:pe(e.onMouseDown,()=>{C.current=!0}),onFocus:pe(e.onFocus,N=>{const _=!C.current;if(N.target===N.currentTarget&&_&&!x){const D=new CustomEvent(Di,wv);if(N.currentTarget.dispatchEvent(D),!D.defaultPrevented){const B=k().filter(A=>A.focusable),G=B.find(A=>A.active),V=B.find(A=>A.id===m),M=[G,V,...B].filter(Boolean).map(A=>A.ref.current);gu(M,d)}}C.current=!1}),onBlur:pe(e.onBlur,()=>w(!1))})})}),hu="RovingFocusGroupItem",mu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=kn(),c=s||l,d=Tv(hu,n),f=d.currentTabStopId===c,p=du(n),{onFocusableItemAdd:h,onFocusableItemRemove:g,currentTabStopId:m}=d;return v.useEffect(()=>{if(r)return h(),()=>g()},[r,h,g]),u.jsx(Li.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Ne.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:pe(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:pe(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:pe(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=Av(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=p().filter(k=>k.focusable).map(k=>k.ref.current);if(x==="last")S.reverse();else if(x==="prev"||x==="next"){x==="prev"&&S.reverse();const k=S.indexOf(y.currentTarget);S=d.loop?Nv(S,k+1):S.slice(k+1)}setTimeout(()=>gu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});mu.displayName=hu;var Ev={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Iv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Av(e,t,n){const r=Iv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Ev[r]}function gu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Nv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var _v=pu,jv=mu,Mv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},yr=new WeakMap,Xo=new WeakMap,Jo={},$i=0,xu=function(e){return e&&(e.host||xu(e.parentNode))},Pv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Rv=function(e,t,n,r){var o=Pv(t,Array.isArray(e)?e:[e]);Jo[n]||(Jo[n]=new WeakMap);var s=Jo[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(p){if(a.has(p))d(p);else try{var h=p.getAttribute(r),g=h!==null&&h!=="false",m=(yr.get(p)||0)+1,y=(s.get(p)||0)+1;yr.set(p,m),s.set(p,y),i.push(p),m===1&&g&&Xo.set(p,!0),y===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",p,x)}})};return d(t),a.clear(),$i++,function(){i.forEach(function(f){var p=yr.get(f)-1,h=s.get(f)-1;yr.set(f,p),s.set(f,h),p||(Xo.has(f)||f.removeAttribute(r),Xo.delete(f)),h||f.removeAttribute(n)}),$i--,$i||(yr=new WeakMap,yr=new WeakMap,Xo=new WeakMap,Jo={})}},Fi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Mv(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Rv(r,o,n,"aria-hidden")):function(){return null}},xn=function(){return xn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},xn.apply(this,arguments)};function yu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function Ov(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Zo="right-scroll-bar-position",Qo="width-before-scroll-bar",Dv="with-scroll-bars-hidden",Lv="--removed-body-scroll-bar-size";function Bi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function $v(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Fv=typeof window<"u"?v.useLayoutEffect:v.useEffect,vu=new WeakMap;function Bv(e,t){var n=$v(null,function(r){return e.forEach(function(o){return Bi(o,r)})});return Fv(function(){var r=vu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Bi(a,null)}),s.forEach(function(a){o.has(a)||Bi(a,i)})}vu.set(n,e)},[e]),n}function zv(e){return e}function Uv(e,t){t===void 0&&(t=zv);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Hv(e){e===void 0&&(e={});var t=Uv(null);return t.options=xn({async:!0,ssr:!1},e),t}var wu=function(e){var t=e.sideCar,n=yu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,xn({},n))};wu.isSideCarExport=!0;function Wv(e,t){return e.useMedium(t),wu}var bu=Hv(),zi=function(){},es=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:zi,onWheelCapture:zi,onTouchMoveCapture:zi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,g=e.noIsolation,m=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,S=e.gapMode,k=yu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,T=Bv([n,t]),E=xn(xn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(C,{sideCar:bu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:g,inert:m,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),xn(xn({},E),{ref:T})):v.createElement(w,xn({},E,{className:l,ref:T}),a))});es.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},es.classNames={fullWidth:Qo,zeroRight:Zo};var Vv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Kv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Vv();return t&&e.setAttribute("nonce",t),e}function qv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Gv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Yv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Kv())&&(qv(t,n),Gv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Xv=function(){var e=Yv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Su=function(){var e=Xv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Jv={left:0,top:0,right:0,gap:0},Ui=function(e){return parseInt(e||"",10)||0},Zv=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Ui(n),Ui(r),Ui(o)]},Qv=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Jv;var t=Zv(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},ew=Su(),vr="data-scroll-locked",tw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
38
+ `)}const xx=["message.start","message.delta","message.end","progress"],yx=["tool.start","tool.end"],vx=["thread_info","checkpoint"],wx=["error","interrupt","heartbeat","state_history","cancelled"],bx=[...xx,...yx,...vx,...wx],Sx=new Set(bx);function Cx(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return Sx.has(t)}const cc=200;function Tx({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=b.useRef(null),f=b.useRef(null),p=b.useRef(new Map),h=b.useRef(null),g=b.useRef(null),m=b.useCallback(M=>{try{const A=globalThis.structuredClone;if(typeof A=="function")return A(M)}catch{}try{return JSON.parse(JSON.stringify(M))}catch{return M}},[]),y=b.useCallback((M,A)=>{if(!M)return;const F=p.current.get(M)??[],L=m(A),R=F.length>=cc?[...F.slice(F.length-cc+1),L]:[...F,L];p.current.set(M,R)},[m]),x=b.useCallback(M=>{M&&p.current.set(M,[])},[]),w=b.useCallback(M=>{const A=M??f.current;if(!A)return;const F=p.current.get(A);F!=null&&F.length&&F.forEach(L=>{try{n(L)}catch(R){console.error("[useChatStreamingService] Failed to replay buffered event",R)}})},[n]),S=b.useCallback(M=>{f.current=M.threadId,h.current&&(h.current.threadIdGuess=M.threadId),g.current=M,x(M.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",M);try{t(M)}catch(A){console.error("[useChatStreamingService] Error in onThreadInfo handler:",A)}},[x,t]),k=b.useCallback(M=>{try{c==null||c(M)}catch(A){console.error("[useChatStreamingService] Error in onHeartbeat handler:",A)}},[c]),C=b.useCallback(M=>{var L,R,z,X;const A=M;if(A.error_type==="auth_error"||A.code==="TOKEN_EXPIRED"||((L=A.message)==null?void 0:L.includes("token"))||((R=A.message)==null?void 0:R.includes("401"))||((z=A.message)==null?void 0:z.includes("unauthorized"))||((X=A.message)==null?void 0:X.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",A.message);try{l==null||l(A.message)}catch(ne){console.warn("[useChatStreamingService] onAuthError handler failed",ne)}}},[l]),T=b.useMemo(()=>({thread_info:M=>(S(M),!0),heartbeat:M=>(k(M),!0),error:M=>(C(M),!1)}),[S,k,C]),E=b.useCallback(M=>{var R;const A=M.seq??null;if(A!==null){const z=d.current;if(z!==null){if(A<=z)return;A>z+1&&(s==null||s({from:z,to:A}))}d.current=A}const F=T[M.type];if(F&&F(M))return;const L=M.threadId??(M.type==="state_history"?M.threadId:void 0)??f.current??((R=h.current)==null?void 0:R.threadIdGuess)??null;if(M.type==="state_history"){f.current=L??f.current;try{r==null||r(M)}catch(z){console.error("[useChatStreamingService] onStateHistory handler failed",z)}}if(Cx(M)){M.type==="checkpoint"||M.type==="state_history"?x(L??null):y(L??null,M);try{n(M)}catch(z){console.error("[useChatStreamingService] Error in onMessageEvent handler:",z)}return}try{o==null||o(M)}catch(z){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",z)}},[y,x,n,s,r,o,T]),{stream:N,stop:_,isStreaming:D,error:B,setToken:G}=lc({baseUrl:e,token:void 0}),V=b.useCallback((M,A)=>{d.current=null,g.current=null,f.current=M.threadId??null,h.current={request:M,callbacks:A,manualStop:!1,threadIdGuess:M.threadId??null},N(M,E,{onOpen:A==null?void 0:A.onOpen,onError:F=>{var L;(L=A==null?void 0:A.onError)==null||L.call(A,F)},onGap:(A==null?void 0:A.onGap)??s,onConnectionError:F=>{var L;a==null||a(F),(L=A==null?void 0:A.onConnectionError)==null||L.call(A,F)},onAuthError:F=>{var L;l==null||l(F),(L=A==null?void 0:A.onAuthError)==null||L.call(A,F)},onHeartbeat:F=>{var L;try{c==null||c(F)}catch(R){console.warn("[useChatStreamingService] onHeartbeat handler failed",R)}try{(L=A==null?void 0:A.onHeartbeat)==null||L.call(A,F)}catch(R){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",R)}},onClosed:F=>{var X,ne,ye,Te;const L=((X=h.current)==null?void 0:X.manualStop)??!1,R=f.current??((ne=h.current)==null?void 0:ne.threadIdGuess)??((ye=F.lastStateHistory)==null?void 0:ye.threadId)??null;(F.reason==="complete"||F.reason==="aborted"&&L)&&x(R);const z={...F,threadId:R,threadInfo:g.current,manualStop:L};try{i==null||i(z)}catch(q){console.warn("[useChatStreamingService] onStreamClosed handler failed",q)}try{(Te=A==null?void 0:A.onClosed)==null||Te.call(A,z)}catch(q){console.warn("[useChatStreamingService] downstream onClosed handler failed",q)}h.current&&(h.current=null)}})},[x,E,l,a,c,s,i,N]),P=b.useCallback(()=>{h.current&&(h.current.manualStop=!0),_()},[_]);return b.useMemo(()=>({startStream:V,stop:P,isStreaming:D,error:B,setAuthToken:G,replayBufferedEvents:w}),[V,P,D,B,G,w])}const uc=b.createContext(null),dc=b.createContext(null),fc=b.createContext(null);b.createContext(!1);function kx({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l}){const{api:c,baseUrl:d}=di(),f=b.useMemo(()=>Cn(d),[d]),[p,h]=b.useState([]),[g,m]=b.useState(t),[y,x]=b.useState(!1),[w,S]=b.useState(null),[k,C]=b.useState(!1),[T,E]=b.useState(null),{state:N,seed:_,prepend:D,pushUser:B,onEvent:G}=ic(),[V,P]=b.useState(!1),[M,A]=b.useState(!1),[F,L]=b.useState(null),[R,z]=b.useState([]),[X,ne]=b.useState([]),[ye,Te]=b.useState(!1),q=b.useMemo(()=>Xg(R),[R]),U=b.useRef(g),Z=b.useRef(null),$=b.useRef(null),Y=b.useRef(null),Q=b.useRef(null),de=b.useRef(!1),oe=b.useRef(null),_e=b.useRef(new Map),ze=b.useRef(new Map);b.useEffect(()=>{U.current=g},[g]);const se=b.useCallback(async H=>{var J,re;if(!H.threadId)return;const j=H.threadId;(J=H.onStart)==null||J.call(H),H.setLoading(!0);try{await H.action(j)}catch(ie){if(U.current===j){const ce=String(ie);(re=H.handleError)==null||re.call(H,ce),s==null||s(ce)}throw ie}finally{H.setLoading(!1)}},[s]),me=b.useCallback(async()=>{x(!0),S(null);try{const H=await c.listThreads();h(H??[])}catch(H){const j=String(H);S(j),s==null||s(j)}finally{x(!1)}},[c,s]),Pe=b.useCallback(H=>{if(!(H!=null&&H.threadId))return;const j={threadId:H.threadId,title:H.title||`Thread ${H.threadId.slice(0,8)}`,createdAt:H.createdAt||new Date().toISOString(),updatedAt:H.updatedAt||new Date().toISOString(),messageCount:H.messageCount??1};h(J=>{let re=!1;const ie=J.map(ce=>ce.threadId===j.threadId?(re=!0,console.debug("[ChatSessionProvider] thread_info: updating existing thread",j.threadId),{...ce,title:j.title??ce.title,updatedAt:j.updatedAt??ce.updatedAt,messageCount:j.messageCount??ce.messageCount}):ce);return re?ie:(console.debug("[ChatSessionProvider] thread_info: adding thread to list",j.threadId),[j,...J])})},[]),Ve=b.useCallback(H=>{const j=H.threadId??U.current;if(!j||U.current&&U.current!==j)return;const{checkpoints:J,timeline:re}=dr(H);if(!J.length)return;const ie=J.find(ce=>ce.messages&&ce.messages.length>0)??J.find(ce=>!!ce.checkpointId)??J[0];_((ie==null?void 0:ie.messages)??[],{checkpointId:(ie==null?void 0:ie.checkpointId)??null,checkpointNs:(ie==null?void 0:ie.checkpointNs)??null}),ne(re),z(J),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null),oe.current=`${j}:latest`,$.current=null,Y.current=null},[_]),ut=b.useCallback(H=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",H.threadId),Pe(H),U.current!==H.threadId&&((H.created??!U.current)&&($.current=H.threadId),Y.current=H.threadId,console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),m(H.threadId))},[Pe]),{startStream:Ke,stop:qe,isStreaming:Qe,error:Ge,setAuthToken:et}=Tx({baseUrl:f,onThreadInfo:ut,onMessageEvent:G,onStateHistory:Ve,onUnhandledEvent:H=>{console.warn("[ChatSessionProvider] Unhandled event:",H.type)},onAuthError:i,onConnectionError:l}),st=b.useCallback(async H=>{try{const j=await c.createThread(H);return m(j.threadId),await me(),j.threadId}catch(j){return s==null||s(String(j)),null}},[c,me,s]),Mt=b.useCallback(async H=>{const j=p;h(re=>re.filter(ie=>ie.threadId!==H));const J=new AbortController;ze.current.set(H,J);try{await c.deleteThread(H),U.current===H&&(m(null),_([],{})),console.log("[ChatSessionProvider] Thread deleted successfully:",H)}catch(re){console.error("[ChatSessionProvider] Delete failed, restoring thread:",H,re),h(j),s==null||s(`Failed to delete thread: ${String(re)}`)}finally{ze.current.delete(H)}},[p,c,_,s]),gt=b.useCallback(async(H,j)=>{try{await c.updateThread(H,j),await me()}catch(J){s==null||s(String(J))}},[c,me,s]),Ct=b.useCallback(async(H,j)=>{if(!H)return;const J=`${H}:${j??"latest"}`,re=_e.current.get(J);if(re)return re;const ie=se({threadId:H,setLoading:C,onStart:()=>E(null),handleError:ce=>E(ce),action:async ce=>{const Xe=await c.getStateHistory({threadId:ce,checkpointId:j||void 0});if(U.current!==ce){console.log(`[ChatSessionProvider] Thread changed during load (was ${ce}, now ${U.current}), discarding stale data`);return}const{checkpoints:Ie,timeline:at}=dr(Xe),ht=Ie.find(Kt=>Kt.messages&&Kt.messages.length>0)??(j?Ie.find(Kt=>Kt.checkpointId===j):null)??Ie[0];_((ht==null?void 0:ht.messages)??[],{checkpointId:(ht==null?void 0:ht.checkpointId)??null,checkpointNs:(ht==null?void 0:ht.checkpointNs)??null}),ne(at),z(Ie),P(!!(ht!=null&&ht.nextCursor)),L((ht==null?void 0:ht.nextCursor)??null)}});_e.current.set(J,ie);try{await ie}finally{_e.current.delete(J)}return U.current===H&&(oe.current=J),ie},[c,_,s,se]),it=b.useCallback(async(H,j,J)=>{J!=null&&J.clearProgress&&Jl(),Q.current=H;try{await Ct(H,j)}finally{Q.current===H&&(Q.current=null)}},[Ct]);b.useEffect(()=>{if(!o||!g||k||Qe)return;if($.current===g){$.current=null,Z.current=g;return}if(Y.current===g){Z.current=g;return}if(Q.current===g){Q.current=null,Z.current=g;return}if(Z.current===g)return;Z.current=g;const H=!de.current&&!!n&&g===t;let j;H&&n?(j=n,de.current=!0,console.log("[ChatSessionProvider] Loading thread with checkpoint:",j,r?`(ns: ${r})`:"")):console.log("[ChatSessionProvider] Loading thread with latest checkpoint");const J=`${g}:${j??"latest"}`;oe.current!==J&&it(g,j)},[o,g,n,r,t,k,Qe,it]);const St=b.useCallback(async(H,j)=>{Jl();const J=U.current;await se({threadId:J,setLoading:Te,action:async re=>{const ie=await c.getStateHistory({threadId:re,checkpointId:H,checkpointNs:j??void 0});if(U.current!==re){console.log(`[ChatSessionProvider] Thread changed during checkpoint navigation (was ${re}, now ${U.current}), discarding stale data`);return}const{checkpoints:ce,timeline:Xe}=dr(ie),Ie=ce.find(at=>at.checkpointId===H&&(j?at.checkpointNs===j:!0));if(!Ie){console.warn("[ChatSessionProvider] Requested checkpoint not found:",{checkpointId:H,checkpointNs:j});return}ne(Xe),z(ce),_(Ie.messages??[],{checkpointId:Ie.checkpointId??null,checkpointNs:Ie.checkpointNs??null})}}).catch(()=>{})},[c,_,s,se]),Pt=b.useCallback((H,j)=>{_(N.messages,{checkpointId:H??null,checkpointNs:j??null})},[_,N.messages]),zt=b.useCallback(async()=>{U.current&&await it(U.current)},[it]),nn=b.useCallback(async()=>{const H=U.current;!H||!F||await se({threadId:H,setLoading:A,action:async j=>{const J=await c.getStateHistory({threadId:j,checkpointId:F});if(U.current!==j)return;const{checkpoints:re}=dr(J);if(re.length>0){const ie=re[re.length-1];D((ie==null?void 0:ie.messages)??[]),P(!!(ie!=null&&ie.nextCursor)),L((ie==null?void 0:ie.nextCursor)??null)}}}).catch(()=>{})},[c,F,D,s,se]),Le=b.useCallback(async()=>{_([],{}),m(null),qe(),z([]),ne([]),P(!1),L(null),C(!1),Te(!1),A(!1),E(null);try{await c.getAgent("default")}catch(H){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",H)}},[_,qe,c]),Sn=b.useCallback(async(H,j,J)=>{const re=U.current;if(!re)throw new Error("No active thread to handle interrupt");const ie=j?J??!0:!1;try{const ce={threadId:re,checkpointId:N.lastCheckpointId??void 0,checkpointNs:N.lastCheckpointNs??void 0,command:{kind:"resume",value:ie}};Ke(ce)}catch(ce){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${H}:`,ce),ce}},[N.lastCheckpointId,N.lastCheckpointNs,Ke]);b.useEffect(()=>{me()},[me]),b.useEffect(()=>{a==null||a(g)},[g,a]);const tt=b.useCallback(async(H,j)=>{let J=U.current;const re=(H==null?void 0:H.text)??"",ie=(H==null?void 0:H.attachments)??[],ce=(re==null?void 0:re.trim())??"",Xe={...(H==null?void 0:H.payload)??{}},Ie=Array.isArray(Xe.messages)?Xe.messages:void 0;Ie&&delete Xe.messages;const at=!!(Ie&&Ie.length);if(!J&&!ce&&ie.length===0&&!at)return;if(!J){const we=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Be=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);J=`${we}${Be}`,$.current=J,m(J)}const{contentParts:ht,filesInfo:Kt}=await kg(c,ie),Hn=[...ht];ce&&Hn.push({type:"text",text:re});const Ar=j==null?void 0:j.originalMessageId,Nr=!!(j!=null&&j.edit&&Ar),po=!at&&Hn.length>0;let Nn=null;po&&(Nn={id:Nr?Ar:`msg-${Date.now()}`,role:"user",content:Hn,createdAt:new Date().toISOString()},Nr||B(Nn));const I=at?Ie:Nn?[Nn]:[],W={...Xe,...Kt.length?{files_info:Kt}:{}};I.length?W.messages=I:"messages"in W||(W.messages=[]);const ae={threadId:J,payload:W,checkpointId:(j==null?void 0:j.checkpointId)??N.lastCheckpointId??void 0,checkpointNs:(j==null?void 0:j.checkpointNs)??N.lastCheckpointNs??void 0,edit:!!(j!=null&&j.edit),timelineCheckpoints:X};Ke(ae)},[c,B,N,Ke,X]),We=b.useMemo(()=>({threads:p,currentThreadId:g,setCurrentThreadId:m,isLoading:y,error:w,actions:{createThread:st,deleteThread:Mt,renameThread:gt,refreshThreads:me}}),[p,g,y,w,st,Mt,gt,me]),pt=b.useMemo(()=>{const H=N.assemblingId??null;return H?{assemblingMessageId:H}:null},[N.assemblingId]),Rt=b.useMemo(()=>({threadId:g,messages:N.messages,interrupt:null,checkpoint:{id:N.lastCheckpointId??null,namespace:N.lastCheckpointNs??null},checkpoints:R,timelineCheckpoints:X,metadata:pt,isLoading:k,isHistoryLoading:M,isLoadingCheckpoint:ye,error:T,hasMore:V,loadOlder:nn,clearState:Le,navigateToCheckpoint:St,setCurrentCheckpointId:Pt,returnToLatest:zt,loadThread:it,clearThread:Le,respondToInterrupt:Sn,messagePreviews:q}),[g,N,R,X,k,M,ye,T,V,nn,Le,St,Pt,zt,it,Sn,q,pt]),Ye=b.useMemo(()=>({isStreaming:Qe,error:Ge,connectionState:Qe?"connected":"idle",submit:tt,send:tt,stop:qe,setAuthToken:et}),[Qe,Ge,tt,qe,et]);return u.jsx(uc.Provider,{value:We,children:u.jsx(dc.Provider,{value:Rt,children:u.jsx(fc.Provider,{value:Ye,children:e})})})}function jo(){const e=b.useContext(uc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Mo(){const e=b.useContext(dc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function pc(){const e=b.useContext(fc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function Po({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c}){return u.jsx(Cg,{apiConfig:t,children:u.jsx(kx,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,children:e})})}function te(...e){return Xh.twMerge(Yh.clsx(e))}const Ex=ho.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Je=v.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Vn.Slot:"button";return u.jsx(i,{className:te(Ex({variant:t,size:n,className:e})),ref:s,...o})});Je.displayName="Button";const hc=v.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:te("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));hc.displayName="Textarea";function mc({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:p="",allowEmptySend:h=!1}){const g=i!==void 0,[m,y]=b.useState(e),x=(g?i:m)??"",[w,S]=b.useTransition(),k=b.useRef(null),C=b.useRef(0),T=b.useRef(null);b.useEffect(()=>{g||(y(e??""),T.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,g]);const E=b.useCallback(()=>{const M=k.current;M&&(M.style.height="auto",M.style.height=`${M.scrollHeight}px`)},[]);b.useEffect(()=>{E()},[E,x]);const N=b.useCallback((M,{fromUser:A})=>{g||y(M),A&&(a==null||a(M))},[g,a]),_=b.useCallback(async M=>{M&&M.preventDefault();const A=(x??"").trim();if(!A&&!h)return;const F=++C.current;T.current={id:F,shouldClear:!0},S(()=>{var L,R,z;try{const X=l(A);X&&typeof X.then=="function"?X.then(()=>{var ne,ye;((ne=T.current)==null?void 0:ne.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((ye=T.current)==null?void 0:ye.id)===F&&(T.current=null)}).catch(()=>{var ne;((ne=T.current)==null?void 0:ne.id)===F&&(T.current=null)}):(((L=T.current)==null?void 0:L.id)===F&&T.current.shouldClear&&(g||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((R=T.current)==null?void 0:R.id)===F&&(T.current=null))}catch{((z=T.current)==null?void 0:z.id)===F&&(T.current=null)}})},[x,l,h,g,a]),D=b.useCallback(M=>{const A=M.target.value;N(A,{fromUser:!0}),T.current&&(T.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[N]),B=b.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),_()):M.key==="Escape"&&t&&(M.preventDefault(),c==null||c())},[_,t,c]),P=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${p}`;return u.jsx("form",{onSubmit:M=>void _(M),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(hc,{ref:k,value:x,onChange:D,onKeyDown:B,placeholder:t?"Edit your message...":n,className:P,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(Je,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(le.Square,{size:16})}):u.jsx(Je,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!x.trim()&&!h||w,children:u.jsx(le.Send,{size:16})})})]})})}const Ix=b.memo(mc);function pe(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function gc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function gi(...e){return t=>{let n=!1;const r=e.map(o=>{const s=gc(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():gc(e[o],null)}}}}function $e(...e){return v.useCallback(gi(...e),e)}function Ax(e,t){const n=v.createContext(t),r=s=>{const{children:i,...a}=s,l=v.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=v.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Tn(e,t=[]){let n=[];function r(s,i){const a=v.createContext(i),l=n.length;n=[...n,i];const c=f=>{var x;const{scope:p,children:h,...g}=f,m=((x=p==null?void 0:p[e])==null?void 0:x[l])||a,y=v.useMemo(()=>g,Object.values(g));return u.jsx(m.Provider,{value:y,children:h})};c.displayName=s+"Provider";function d(f,p){var m;const h=((m=p==null?void 0:p[e])==null?void 0:m[l])||a,g=v.useContext(h);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>v.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return v.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,Nx(o,...t)]}function Nx(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const f=l(s)[`__scope${c}`];return{...a,...f}},{});return v.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var kt=globalThis!=null&&globalThis.document?v.useLayoutEffect:()=>{},_x=v[" useInsertionEffect ".trim().toString()]||kt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=jx({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=v.useRef(e!==void 0);v.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=v.useCallback(d=>{var f;if(a){const p=Mx(d)?d(e):d;p!==e&&((f=i.current)==null||f.call(i,p))}else s(d)},[a,e,s,i]);return[l,c]}function jx({defaultProp:e,onChange:t}){const[n,r]=v.useState(e),o=v.useRef(n),s=v.useRef(t);return _x(()=>{s.current=t},[t]),v.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function Mx(e){return typeof e=="function"}var Px=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ne=Px.reduce((e,t)=>{const n=Vn.createSlot(`Primitive.${t}`),r=v.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function xc(e,t){e&&mo.flushSync(()=>e.dispatchEvent(t))}function xi(e){const t=e+"CollectionProvider",[n,r]=Tn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:y,children:x}=m,w=b.useRef(null),S=b.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:S,collectionRef:w,children:x})};i.displayName=t;const a=e+"CollectionSlot",l=Vn.createSlot(a),c=b.forwardRef((m,y)=>{const{scope:x,children:w}=m,S=s(a,x),k=$e(y,S.collectionRef);return u.jsx(l,{ref:k,children:w})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",p=Vn.createSlot(d),h=b.forwardRef((m,y)=>{const{scope:x,children:w,...S}=m,k=b.useRef(null),C=$e(y,k),T=s(d,x);return b.useEffect(()=>(T.itemMap.set(k,{ref:k,...S}),()=>void T.itemMap.delete(k))),u.jsx(p,{[f]:"",ref:C,children:w})});h.displayName=d;function g(m){const y=s(e+"CollectionConsumer",m);return b.useCallback(()=>{const w=y.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((T,E)=>S.indexOf(T.ref.current)-S.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:h},g,r]}var Rx=v.createContext(void 0);function Ro(e){const t=v.useContext(Rx);return e||t||"ltr"}function Et(e){const t=v.useRef(e);return v.useEffect(()=>{t.current=e}),v.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ox(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e);v.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Dx="DismissableLayer",yi="dismissableLayer.update",Lx="dismissableLayer.pointerDownOutside",$x="dismissableLayer.focusOutside",yc,vc=v.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Oo=v.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=v.useContext(vc),[d,f]=v.useState(null),p=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,h]=v.useState({}),g=$e(t,E=>f(E)),m=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=m.indexOf(y),w=d?m.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=x,C=zx(E=>{const N=E.target,_=[...c.branches].some(D=>D.contains(N));!k||_||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),T=Ux(E=>{const N=E.target;[...c.branches].some(D=>D.contains(N))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return Ox(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),v.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(yc=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),wc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=yc)}},[d,p,n,c]),v.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),wc())},[d,c]),v.useEffect(()=>{const E=()=>h({});return document.addEventListener(yi,E),()=>document.removeEventListener(yi,E)},[]),u.jsx(Ne.div,{...l,ref:g,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:pe(e.onFocusCapture,T.onFocusCapture),onBlurCapture:pe(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:pe(e.onPointerDownCapture,C.onPointerDownCapture)})});Oo.displayName=Dx;var Fx="DismissableLayerBranch",Bx=v.forwardRef((e,t)=>{const n=v.useContext(vc),r=v.useRef(null),o=$e(t,r);return v.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Ne.div,{...e,ref:o})});Bx.displayName=Fx;function zx(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1),o=v.useRef(()=>{});return v.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){bc(Lx,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Ux(e,t=globalThis==null?void 0:globalThis.document){const n=Et(e),r=v.useRef(!1);return v.useEffect(()=>{const o=s=>{s.target&&!r.current&&bc($x,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function wc(){const e=new CustomEvent(yi);document.dispatchEvent(e)}function bc(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?xc(o,s):o.dispatchEvent(s)}var vi=0;function wi(){v.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Sc()),document.body.insertAdjacentElement("beforeend",e[1]??Sc()),vi++,()=>{vi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),vi--}},[])}function Sc(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var bi="focusScope.autoFocusOnMount",Si="focusScope.autoFocusOnUnmount",Cc={bubbles:!1,cancelable:!0},Hx="FocusScope",Do=v.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=v.useState(null),c=Et(o),d=Et(s),f=v.useRef(null),p=$e(t,m=>l(m)),h=v.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;v.useEffect(()=>{if(r){let m=function(S){if(h.paused||!a)return;const k=S.target;a.contains(k)?f.current=k:jn(f.current,{select:!0})},y=function(S){if(h.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||jn(f.current,{select:!0}))},x=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&jn(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const w=new MutationObserver(x);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),w.disconnect()}}},[r,a,h.paused]),v.useEffect(()=>{if(a){Ec.add(h);const m=document.activeElement;if(!a.contains(m)){const x=new CustomEvent(bi,Cc);a.addEventListener(bi,c),a.dispatchEvent(x),x.defaultPrevented||(Wx(Yx(Tc(a)),{select:!0}),document.activeElement===m&&jn(a))}return()=>{a.removeEventListener(bi,c),setTimeout(()=>{const x=new CustomEvent(Si,Cc);a.addEventListener(Si,d),a.dispatchEvent(x),x.defaultPrevented||jn(m??document.body,{select:!0}),a.removeEventListener(Si,d),Ec.remove(h)},0)}}},[a,c,d,h]);const g=v.useCallback(m=>{if(!n&&!r||h.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,x=document.activeElement;if(y&&x){const w=m.currentTarget,[S,k]=Vx(w);S&&k?!m.shiftKey&&x===k?(m.preventDefault(),n&&jn(S,{select:!0})):m.shiftKey&&x===S&&(m.preventDefault(),n&&jn(k,{select:!0})):x===w&&m.preventDefault()}},[n,r,h.paused]);return u.jsx(Ne.div,{tabIndex:-1,...i,ref:p,onKeyDown:g})});Do.displayName=Hx;function Wx(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(jn(r,{select:t}),document.activeElement!==n)return}function Vx(e){const t=Tc(e),n=kc(t,e),r=kc(t.reverse(),e);return[n,r]}function Tc(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function kc(e,t){for(const n of e)if(!Kx(n,{upTo:t}))return n}function Kx(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function qx(e){return e instanceof HTMLInputElement&&"select"in e}function jn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&qx(e)&&t&&e.select()}}var Ec=Gx();function Gx(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Ic(e,t),e.unshift(t)},remove(t){var n;e=Ic(e,t),(n=e[0])==null||n.resume()}}}function Ic(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Yx(e){return e.filter(t=>t.tagName!=="A")}var Xx=v[" useId ".trim().toString()]||(()=>{}),Jx=0;function kn(e){const[t,n]=v.useState(Xx());return kt(()=>{n(r=>r??String(Jx++))},[e]),t?`radix-${t}`:""}const Zx=["top","right","bottom","left"],Mn=Math.min,Ut=Math.max,Lo=Math.round,$o=Math.floor,pn=e=>({x:e,y:e}),Qx={left:"right",right:"left",bottom:"top",top:"bottom"},ey={start:"end",end:"start"};function Ci(e,t,n){return Ut(e,Mn(t,n))}function En(e,t){return typeof e=="function"?e(t):e}function In(e){return e.split("-")[0]}function hr(e){return e.split("-")[1]}function Ti(e){return e==="x"?"y":"x"}function ki(e){return e==="y"?"height":"width"}const ty=new Set(["top","bottom"]);function hn(e){return ty.has(In(e))?"y":"x"}function Ei(e){return Ti(hn(e))}function ny(e,t,n){n===void 0&&(n=!1);const r=hr(e),o=Ei(e),s=ki(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=Fo(i)),[i,Fo(i)]}function ry(e){const t=Fo(e);return[Ii(e),t,Ii(t)]}function Ii(e){return e.replace(/start|end/g,t=>ey[t])}const Ac=["left","right"],Nc=["right","left"],oy=["top","bottom"],sy=["bottom","top"];function iy(e,t,n){switch(e){case"top":case"bottom":return n?t?Nc:Ac:t?Ac:Nc;case"left":case"right":return t?oy:sy;default:return[]}}function ay(e,t,n,r){const o=hr(e);let s=iy(In(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Ii)))),s}function Fo(e){return e.replace(/left|right|bottom|top/g,t=>Qx[t])}function ly(e){return{top:0,right:0,bottom:0,left:0,...e}}function _c(e){return typeof e!="number"?ly(e):{top:e,right:e,bottom:e,left:e}}function Bo(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function jc(e,t,n){let{reference:r,floating:o}=e;const s=hn(t),i=Ei(t),a=ki(i),l=In(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let h;switch(l){case"top":h={x:d,y:r.y-o.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:f};break;case"left":h={x:r.x-o.width,y:f};break;default:h={x:r.x,y:r.y}}switch(hr(t)){case"start":h[i]-=p*(n&&c?-1:1);break;case"end":h[i]+=p*(n&&c?-1:1);break}return h}const cy=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=jc(c,r,l),p=r,h={},g=0;for(let m=0;m<a.length;m++){const{name:y,fn:x}=a[m],{x:w,y:S,data:k,reset:C}=await x({x:d,y:f,initialPlacement:r,placement:p,strategy:o,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=w??d,f=S??f,h={...h,[y]:{...h[y],...k}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):C.rects),{x:d,y:f}=jc(c,p,l)),m=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:h}};async function $r(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:h=0}=En(t,e),g=_c(h),y=a[p?f==="floating"?"reference":"floating":f],x=Bo(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),w=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},C=Bo(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:S,strategy:l}):w);return{top:(x.top-C.top+g.top)/k.y,bottom:(C.bottom-x.bottom+g.bottom)/k.y,left:(x.left-C.left+g.left)/k.x,right:(C.right-x.right+g.right)/k.x}}const uy=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=t,{element:c,padding:d=0}=En(e,t)||{};if(c==null)return{};const f=_c(d),p={x:n,y:r},h=Ei(o),g=ki(h),m=await i.getDimensions(c),y=h==="y",x=y?"top":"left",w=y?"bottom":"right",S=y?"clientHeight":"clientWidth",k=s.reference[g]+s.reference[h]-p[h]-s.floating[g],C=p[h]-s.reference[h],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=T?T[S]:0;(!E||!await(i.isElement==null?void 0:i.isElement(T)))&&(E=a.floating[S]||s.floating[g]);const N=k/2-C/2,_=E/2-m[g]/2-1,D=Mn(f[x],_),B=Mn(f[w],_),G=D,V=E-m[g]-B,P=E/2-m[g]/2+N,M=Ci(G,P,V),A=!l.arrow&&hr(o)!=null&&P!==M&&s.reference[g]/2-(P<G?D:B)-m[g]/2<0,F=A?P<G?P-G:P-V:0;return{[h]:p[h]+F,data:{[h]:M,centerOffset:P-M-F,...A&&{alignmentOffset:F}},reset:A}}}),dy=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...y}=En(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const x=In(o),w=hn(a),S=In(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(S||!m?[Fo(a)]:ry(a)),T=g!=="none";!p&&T&&C.push(...ay(a,m,g,k));const E=[a,...C],N=await $r(t,y),_=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&_.push(N[x]),f){const P=ny(o,i,k);_.push(N[P[0]],N[P[1]])}if(D=[...D,{placement:o,overflows:_}],!_.every(P=>P<=0)){var B,G;const P=(((B=s.flip)==null?void 0:B.index)||0)+1,M=E[P];if(M&&(!(f==="alignment"?w!==hn(M):!1)||D.every(L=>hn(L.placement)===w?L.overflows[0]>0:!0)))return{data:{index:P,overflows:D},reset:{placement:M}};let A=(G=D.filter(F=>F.overflows[0]<=0).sort((F,L)=>F.overflows[1]-L.overflows[1])[0])==null?void 0:G.placement;if(!A)switch(h){case"bestFit":{var V;const F=(V=D.filter(L=>{if(T){const R=hn(L.placement);return R===w||R==="y"}return!0}).map(L=>[L.placement,L.overflows.filter(R=>R>0).reduce((R,z)=>R+z,0)]).sort((L,R)=>L[1]-R[1])[0])==null?void 0:V[0];F&&(A=F);break}case"initialPlacement":A=a;break}if(o!==A)return{reset:{placement:A}}}return{}}}};function Mc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function Pc(e){return Zx.some(t=>e[t]>=0)}const fy=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=En(e,t);switch(r){case"referenceHidden":{const s=await $r(t,{...o,elementContext:"reference"}),i=Mc(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:Pc(i)}}}case"escaped":{const s=await $r(t,{...o,altBoundary:!0}),i=Mc(s,n.floating);return{data:{escapedOffsets:i,escaped:Pc(i)}}}default:return{}}}}},Rc=new Set(["left","top"]);async function py(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=In(n),a=hr(n),l=hn(n)==="y",c=Rc.has(i)?-1:1,d=s&&l?-1:1,f=En(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:g}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof g=="number"&&(h=a==="end"?g*-1:g),l?{x:h*d,y:p*c}:{x:p*c,y:h*d}}const hy=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=t,l=await py(t,e);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},my=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x,y:w}=y;return{x,y:w}}},...l}=En(e,t),c={x:n,y:r},d=await $r(t,l),f=hn(In(o)),p=Ti(f);let h=c[p],g=c[f];if(s){const y=p==="y"?"top":"left",x=p==="y"?"bottom":"right",w=h+d[y],S=h-d[x];h=Ci(w,h,S)}if(i){const y=f==="y"?"top":"left",x=f==="y"?"bottom":"right",w=g+d[y],S=g-d[x];g=Ci(w,g,S)}const m=a.fn({...t,[p]:h,[f]:g});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[f]:i}}}}}},gy=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=t,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=En(e,t),d={x:n,y:r},f=hn(o),p=Ti(f);let h=d[p],g=d[f];const m=En(a,t),y=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=p==="y"?"height":"width",k=s.reference[p]-s.floating[S]+y.mainAxis,C=s.reference[p]+s.reference[S]-y.mainAxis;h<k?h=k:h>C&&(h=C)}if(c){var x,w;const S=p==="y"?"width":"height",k=Rc.has(In(o)),C=s.reference[f]-s.floating[S]+(k&&((x=i.offset)==null?void 0:x[f])||0)+(k?0:y.crossAxis),T=s.reference[f]+s.reference[S]+(k?0:((w=i.offset)==null?void 0:w[f])||0)-(k?y.crossAxis:0);g<C?g=C:g>T&&(g=T)}return{[p]:h,[f]:g}}}},xy=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:s,platform:i,elements:a}=t,{apply:l=()=>{},...c}=En(e,t),d=await $r(t,c),f=In(o),p=hr(o),h=hn(o)==="y",{width:g,height:m}=s.floating;let y,x;f==="top"||f==="bottom"?(y=f,x=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(x=f,y=p==="end"?"top":"bottom");const w=m-d.top-d.bottom,S=g-d.left-d.right,k=Mn(m-d[y],w),C=Mn(g-d[x],S),T=!t.middlewareData.shift;let E=k,N=C;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(N=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=w),T&&!p){const D=Ut(d.left,0),B=Ut(d.right,0),G=Ut(d.top,0),V=Ut(d.bottom,0);h?N=g-2*(D!==0||B!==0?D+B:Ut(d.left,d.right)):E=m-2*(G!==0||V!==0?G+V:Ut(d.top,d.bottom))}await l({...t,availableWidth:N,availableHeight:E});const _=await i.getDimensions(a.floating);return g!==_.width||m!==_.height?{reset:{rects:!0}}:{}}}};function zo(){return typeof window<"u"}function mr(e){return Oc(e)?(e.nodeName||"").toLowerCase():"#document"}function Ht(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function mn(e){var t;return(t=(Oc(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Oc(e){return zo()?e instanceof Node||e instanceof Ht(e).Node:!1}function sn(e){return zo()?e instanceof Element||e instanceof Ht(e).Element:!1}function gn(e){return zo()?e instanceof HTMLElement||e instanceof Ht(e).HTMLElement:!1}function Dc(e){return!zo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ht(e).ShadowRoot}const yy=new Set(["inline","contents"]);function Fr(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=an(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!yy.has(o)}const vy=new Set(["table","td","th"]);function wy(e){return vy.has(mr(e))}const by=[":popover-open",":modal"];function Uo(e){return by.some(t=>{try{return e.matches(t)}catch{return!1}})}const Sy=["transform","translate","scale","rotate","perspective"],Cy=["transform","translate","scale","rotate","perspective","filter"],Ty=["paint","layout","strict","content"];function Ai(e){const t=Ni(),n=sn(e)?an(e):e;return Sy.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||Cy.some(r=>(n.willChange||"").includes(r))||Ty.some(r=>(n.contain||"").includes(r))}function ky(e){let t=Pn(e);for(;gn(t)&&!gr(t);){if(Ai(t))return t;if(Uo(t))return null;t=Pn(t)}return null}function Ni(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const Ey=new Set(["html","body","#document"]);function gr(e){return Ey.has(mr(e))}function an(e){return Ht(e).getComputedStyle(e)}function Ho(e){return sn(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Pn(e){if(mr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Dc(e)&&e.host||mn(e);return Dc(t)?t.host:t}function Lc(e){const t=Pn(e);return gr(t)?e.ownerDocument?e.ownerDocument.body:e.body:gn(t)&&Fr(t)?t:Lc(t)}function Br(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Lc(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Ht(o);if(s){const a=_i(i);return t.concat(i,i.visualViewport||[],Fr(o)?o:[],a&&n?Br(a):[])}return t.concat(o,Br(o,[],n))}function _i(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function $c(e){const t=an(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=gn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Lo(n)!==s||Lo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function ji(e){return sn(e)?e:e.contextElement}function xr(e){const t=ji(e);if(!gn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=$c(t);let i=(s?Lo(n.width):n.width)/r,a=(s?Lo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const Iy=pn(0);function Fc(e){const t=Ht(e);return!Ni()||!t.visualViewport?Iy:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Ay(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Ht(e)?!1:t}function Yn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=ji(e);let i=pn(1);t&&(r?sn(r)&&(i=xr(r)):i=xr(e));const a=Ay(s,n,r)?Fc(s):pn(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,d=o.width/i.x,f=o.height/i.y;if(s){const p=Ht(s),h=r&&sn(r)?Ht(r):r;let g=p,m=_i(g);for(;m&&r&&h!==g;){const y=xr(m),x=m.getBoundingClientRect(),w=an(m),S=x.left+(m.clientLeft+parseFloat(w.paddingLeft))*y.x,k=x.top+(m.clientTop+parseFloat(w.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=S,c+=k,g=Ht(m),m=_i(g)}}return Bo({width:d,height:f,x:l,y:c})}function Wo(e,t){const n=Ho(e).scrollLeft;return t?t.left+n:Yn(mn(e)).left+n}function Bc(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Wo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Ny(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=mn(r),a=t?Uo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=gn(r);if((f||!f&&!s)&&((mr(r)!=="body"||Fr(i))&&(l=Ho(r)),gn(r))){const h=Yn(r);c=xr(r),d.x=h.x+r.clientLeft,d.y=h.y+r.clientTop}const p=i&&!f&&!s?Bc(i,l):pn(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+p.x,y:n.y*c.y-l.scrollTop*c.y+d.y+p.y}}function _y(e){return Array.from(e.getClientRects())}function jy(e){const t=mn(e),n=Ho(e),r=e.ownerDocument.body,o=Ut(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ut(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Wo(e);const a=-n.scrollTop;return an(r).direction==="rtl"&&(i+=Ut(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const zc=25;function My(e,t){const n=Ht(e),r=mn(e),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const d=Ni();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Wo(r);if(c<=0){const d=r.ownerDocument,f=d.body,p=getComputedStyle(f),h=d.compatMode==="CSS1Compat"&&parseFloat(p.marginLeft)+parseFloat(p.marginRight)||0,g=Math.abs(r.clientWidth-f.clientWidth-h);g<=zc&&(s-=g)}else c<=zc&&(s+=c);return{width:s,height:i,x:a,y:l}}const Py=new Set(["absolute","fixed"]);function Ry(e,t){const n=Yn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=gn(e)?xr(e):pn(1),i=e.clientWidth*s.x,a=e.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function Uc(e,t,n){let r;if(t==="viewport")r=My(e,n);else if(t==="document")r=jy(mn(e));else if(sn(t))r=Ry(t,n);else{const o=Fc(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Bo(r)}function Hc(e,t){const n=Pn(e);return n===t||!sn(n)||gr(n)?!1:an(n).position==="fixed"||Hc(n,t)}function Oy(e,t){const n=t.get(e);if(n)return n;let r=Br(e,[],!1).filter(a=>sn(a)&&mr(a)!=="body"),o=null;const s=an(e).position==="fixed";let i=s?Pn(e):e;for(;sn(i)&&!gr(i);){const a=an(i),l=Ai(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&Py.has(o.position)||Fr(i)&&!l&&Hc(e,i))?r=r.filter(d=>d!==i):o=a,i=Pn(i)}return t.set(e,r),r}function Dy(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Uo(t)?[]:Oy(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=Uc(t,d,o);return c.top=Ut(f.top,c.top),c.right=Mn(f.right,c.right),c.bottom=Mn(f.bottom,c.bottom),c.left=Ut(f.left,c.left),c},Uc(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Ly(e){const{width:t,height:n}=$c(e);return{width:t,height:n}}function $y(e,t,n){const r=gn(t),o=mn(t),s=n==="fixed",i=Yn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=Wo(o)}if(r||!r&&!s)if((mr(t)!=="body"||Fr(o))&&(a=Ho(t)),r){const h=Yn(t,!0,s,t);l.x=h.x+t.clientLeft,l.y=h.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?Bc(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,p=i.top+a.scrollTop-l.y-d.y;return{x:f,y:p,width:i.width,height:i.height}}function Mi(e){return an(e).position==="static"}function Wc(e,t){if(!gn(e)||an(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return mn(e)===n&&(n=n.ownerDocument.body),n}function Vc(e,t){const n=Ht(e);if(Uo(e))return n;if(!gn(e)){let o=Pn(e);for(;o&&!gr(o);){if(sn(o)&&!Mi(o))return o;o=Pn(o)}return n}let r=Wc(e,t);for(;r&&wy(r)&&Mi(r);)r=Wc(r,t);return r&&gr(r)&&Mi(r)&&!Ai(r)?n:r||ky(e)||n}const Fy=async function(e){const t=this.getOffsetParent||Vc,n=this.getDimensions,r=await n(e.floating);return{reference:$y(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function By(e){return an(e).direction==="rtl"}const zy={convertOffsetParentRelativeRectToViewportRelativeRect:Ny,getDocumentElement:mn,getClippingRect:Dy,getOffsetParent:Vc,getElementRects:Fy,getClientRects:_y,getDimensions:Ly,getScale:xr,isElement:sn,isRTL:By};function Kc(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Uy(e,t){let n=null,r;const o=mn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:p,height:h}=c;if(a||t(),!p||!h)return;const g=$o(f),m=$o(o.clientWidth-(d+p)),y=$o(o.clientHeight-(f+h)),x=$o(d),S={rootMargin:-g+"px "+-m+"px "+-y+"px "+-x+"px",threshold:Ut(0,Mn(1,l))||1};let k=!0;function C(T){const E=T[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!Kc(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(C,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(C,S)}n.observe(e)}return i(!0),s}function Hy(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=ji(e),d=o||s?[...c?Br(c):[],...Br(t)]:[];d.forEach(x=>{o&&x.addEventListener("scroll",n,{passive:!0}),s&&x.addEventListener("resize",n)});const f=c&&a?Uy(c,n):null;let p=-1,h=null;i&&(h=new ResizeObserver(x=>{let[w]=x;w&&w.target===c&&h&&(h.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=h)==null||S.observe(t)})),n()}),c&&!l&&h.observe(c),h.observe(t));let g,m=l?Yn(e):null;l&&y();function y(){const x=Yn(e);m&&!Kc(m,x)&&n(),m=x,g=requestAnimationFrame(y)}return n(),()=>{var x;d.forEach(w=>{o&&w.removeEventListener("scroll",n),s&&w.removeEventListener("resize",n)}),f==null||f(),(x=h)==null||x.disconnect(),h=null,l&&cancelAnimationFrame(g)}}const Wy=hy,Vy=my,Ky=dy,qy=xy,Gy=fy,qc=uy,Yy=gy,Xy=(e,t,n)=>{const r=new Map,o={platform:zy,...n},s={...o.platform,_c:r};return cy(e,t,{...o,platform:s})};var Jy=typeof document<"u",Zy=function(){},Vo=Jy?b.useLayoutEffect:Zy;function Ko(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ko(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Ko(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function Gc(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Yc(e,t){const n=Gc(e);return Math.round(t*n)/n}function Pi(e){const t=v.useRef(e);return Vo(()=>{t.current=e}),t}function Qy(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[d,f]=v.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=v.useState(r);Ko(p,r)||h(r);const[g,m]=v.useState(null),[y,x]=v.useState(null),w=v.useCallback(L=>{L!==T.current&&(T.current=L,m(L))},[]),S=v.useCallback(L=>{L!==E.current&&(E.current=L,x(L))},[]),k=s||g,C=i||y,T=v.useRef(null),E=v.useRef(null),N=v.useRef(d),_=l!=null,D=Pi(l),B=Pi(o),G=Pi(c),V=v.useCallback(()=>{if(!T.current||!E.current)return;const L={placement:t,strategy:n,middleware:p};B.current&&(L.platform=B.current),Xy(T.current,E.current,L).then(R=>{const z={...R,isPositioned:G.current!==!1};P.current&&!Ko(N.current,z)&&(N.current=z,mo.flushSync(()=>{f(z)}))})},[p,t,n,B,G]);Vo(()=>{c===!1&&N.current.isPositioned&&(N.current.isPositioned=!1,f(L=>({...L,isPositioned:!1})))},[c]);const P=v.useRef(!1);Vo(()=>(P.current=!0,()=>{P.current=!1}),[]),Vo(()=>{if(k&&(T.current=k),C&&(E.current=C),k&&C){if(D.current)return D.current(k,C,V);V()}},[k,C,V,D,_]);const M=v.useMemo(()=>({reference:T,floating:E,setReference:w,setFloating:S}),[w,S]),A=v.useMemo(()=>({reference:k,floating:C}),[k,C]),F=v.useMemo(()=>{const L={position:n,left:0,top:0};if(!A.floating)return L;const R=Yc(A.floating,d.x),z=Yc(A.floating,d.y);return a?{...L,transform:"translate("+R+"px, "+z+"px)",...Gc(A.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:R,top:z}},[n,a,A.floating,d.x,d.y]);return v.useMemo(()=>({...d,update:V,refs:M,elements:A,floatingStyles:F}),[d,V,M,A,F])}const ev=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?qc({element:r.current,padding:o}).fn(n):{}:r?qc({element:r,padding:o}).fn(n):{}}}},tv=(e,t)=>({...Wy(e),options:[e,t]}),nv=(e,t)=>({...Vy(e),options:[e,t]}),rv=(e,t)=>({...Yy(e),options:[e,t]}),ov=(e,t)=>({...Ky(e),options:[e,t]}),sv=(e,t)=>({...qy(e),options:[e,t]}),iv=(e,t)=>({...Gy(e),options:[e,t]}),av=(e,t)=>({...ev(e),options:[e,t]});var lv="Arrow",Xc=v.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Ne.svg,{...s,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:u.jsx("polygon",{points:"0,0 30,0 15,10"})})});Xc.displayName=lv;var cv=Xc;function Jc(e){const[t,n]=v.useState(void 0);return kt(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=e.offsetWidth,a=e.offsetHeight;n({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var Ri="Popper",[Zc,qo]=Tn(Ri),[uv,Qc]=Zc(Ri),eu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=v.useState(null);return u.jsx(uv,{scope:t,anchor:r,onAnchorChange:o,children:n})};eu.displayName=Ri;var tu="PopperAnchor",nu=v.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Qc(tu,n),i=v.useRef(null),a=$e(t,i),l=v.useRef(null);return v.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:u.jsx(Ne.div,{...o,ref:a})});nu.displayName=tu;var Oi="PopperContent",[dv,fv]=Zc(Oi),ru=v.forwardRef((e,t)=>{var Z,$,Y,Q,de,oe;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:p=!1,updatePositionStrategy:h="optimized",onPlaced:g,...m}=e,y=Qc(Oi,n),[x,w]=v.useState(null),S=$e(t,_e=>w(_e)),[k,C]=v.useState(null),T=Jc(k),E=(T==null?void 0:T.width)??0,N=(T==null?void 0:T.height)??0,_=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},B=Array.isArray(c)?c:[c],G=B.length>0,V={padding:D,boundary:B.filter(hv),altBoundary:G},{refs:P,floatingStyles:M,placement:A,isPositioned:F,middlewareData:L}=Qy({strategy:"fixed",placement:_,whileElementsMounted:(..._e)=>Hy(..._e,{animationFrame:h==="always"}),elements:{reference:y.anchor},middleware:[tv({mainAxis:o+N,alignmentAxis:i}),l&&nv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?rv():void 0,...V}),l&&ov({...V}),sv({...V,apply:({elements:_e,rects:ze,availableWidth:se,availableHeight:me})=>{const{width:Pe,height:Ve}=ze.reference,ut=_e.floating.style;ut.setProperty("--radix-popper-available-width",`${se}px`),ut.setProperty("--radix-popper-available-height",`${me}px`),ut.setProperty("--radix-popper-anchor-width",`${Pe}px`),ut.setProperty("--radix-popper-anchor-height",`${Ve}px`)}}),k&&av({element:k,padding:a}),mv({arrowWidth:E,arrowHeight:N}),p&&iv({strategy:"referenceHidden",...V})]}),[R,z]=iu(A),X=Et(g);kt(()=>{F&&(X==null||X())},[F,X]);const ne=(Z=L.arrow)==null?void 0:Z.x,ye=($=L.arrow)==null?void 0:$.y,Te=((Y=L.arrow)==null?void 0:Y.centerOffset)!==0,[q,U]=v.useState();return kt(()=>{x&&U(window.getComputedStyle(x).zIndex)},[x]),u.jsx("div",{ref:P.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:F?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:q,"--radix-popper-transform-origin":[(Q=L.transformOrigin)==null?void 0:Q.x,(de=L.transformOrigin)==null?void 0:de.y].join(" "),...((oe=L.hide)==null?void 0:oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(dv,{scope:n,placedSide:R,onArrowChange:C,arrowX:ne,arrowY:ye,shouldHideArrow:Te,children:u.jsx(Ne.div,{"data-side":R,"data-align":z,...m,ref:S,style:{...m.style,animation:F?void 0:"none"}})})})});ru.displayName=Oi;var ou="PopperArrow",pv={top:"bottom",right:"left",bottom:"top",left:"right"},su=v.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=fv(ou,r),i=pv[s.placedSide];return u.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:u.jsx(cv,{...o,ref:n,style:{...o.style,display:"block"}})})});su.displayName=ou;function hv(e){return e!==null}var mv=e=>({name:"transformOrigin",options:e,fn(t){var y,x,w;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=iu(n),f={start:"0%",center:"50%",end:"100%"}[d],p=(((x=o.arrow)==null?void 0:x.x)??0)+a/2,h=(((w=o.arrow)==null?void 0:w.y)??0)+l/2;let g="",m="";return c==="bottom"?(g=i?f:`${p}px`,m=`${-l}px`):c==="top"?(g=i?f:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,m=i?f:`${h}px`):c==="left"&&(g=`${r.floating.width+l}px`,m=i?f:`${h}px`),{data:{x:g,y:m}}}});function iu(e){const[t,n="center"]=e.split("-");return[t,n]}var au=eu,lu=nu,cu=ru,uu=su,gv="Portal",Go=v.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=v.useState(!1);kt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Ys.createPortal(u.jsx(Ne.div,{...r,ref:t}),i):null});Go.displayName=gv;function xv(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Xt=e=>{const{present:t,children:n}=e,r=yv(t),o=typeof n=="function"?n({present:r.isPresent}):v.Children.only(n),s=$e(r.ref,vv(o));return typeof n=="function"||r.isPresent?v.cloneElement(o,{ref:s}):null};Xt.displayName="Presence";function yv(e){const[t,n]=v.useState(),r=v.useRef(null),o=v.useRef(e),s=v.useRef("none"),i=e?"mounted":"unmounted",[a,l]=xv(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return v.useEffect(()=>{const c=Yo(r.current);s.current=a==="mounted"?c:"none"},[a]),kt(()=>{const c=r.current,d=o.current;if(d!==e){const p=s.current,h=Yo(c);e?l("MOUNT"):h==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&p!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),kt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=h=>{const m=Yo(r.current).includes(CSS.escape(h.animationName));if(h.target===t&&m&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},p=h=>{h.target===t&&(s.current=Yo(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:v.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Yo(e){return(e==null?void 0:e.animationName)||"none"}function vv(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Di="rovingFocusGroup.onEntryFocus",wv={bubbles:!1,cancelable:!0},zr="RovingFocusGroup",[Li,du,bv]=xi(zr),[Sv,fu]=Tn(zr,[bv]),[Cv,Tv]=Sv(zr),pu=v.forwardRef((e,t)=>u.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(kv,{...e,ref:t})})}));pu.displayName=zr;var kv=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,p=v.useRef(null),h=$e(t,p),g=Ro(s),[m,y]=pr({prop:i,defaultProp:a??null,onChange:l,caller:zr}),[x,w]=v.useState(!1),S=Et(c),k=du(n),C=v.useRef(!1),[T,E]=v.useState(0);return v.useEffect(()=>{const N=p.current;if(N)return N.addEventListener(Di,S),()=>N.removeEventListener(Di,S)},[S]),u.jsx(Cv,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:m,onItemFocus:v.useCallback(N=>y(N),[y]),onItemShiftTab:v.useCallback(()=>w(!0),[]),onFocusableItemAdd:v.useCallback(()=>E(N=>N+1),[]),onFocusableItemRemove:v.useCallback(()=>E(N=>N-1),[]),children:u.jsx(Ne.div,{tabIndex:x||T===0?-1:0,"data-orientation":r,...f,ref:h,style:{outline:"none",...e.style},onMouseDown:pe(e.onMouseDown,()=>{C.current=!0}),onFocus:pe(e.onFocus,N=>{const _=!C.current;if(N.target===N.currentTarget&&_&&!x){const D=new CustomEvent(Di,wv);if(N.currentTarget.dispatchEvent(D),!D.defaultPrevented){const B=k().filter(A=>A.focusable),G=B.find(A=>A.active),V=B.find(A=>A.id===m),M=[G,V,...B].filter(Boolean).map(A=>A.ref.current);gu(M,d)}}C.current=!1}),onBlur:pe(e.onBlur,()=>w(!1))})})}),hu="RovingFocusGroupItem",mu=v.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=kn(),c=s||l,d=Tv(hu,n),f=d.currentTabStopId===c,p=du(n),{onFocusableItemAdd:h,onFocusableItemRemove:g,currentTabStopId:m}=d;return v.useEffect(()=>{if(r)return h(),()=>g()},[r,h,g]),u.jsx(Li.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Ne.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:pe(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:pe(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:pe(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const x=Av(y,d.orientation,d.dir);if(x!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let S=p().filter(k=>k.focusable).map(k=>k.ref.current);if(x==="last")S.reverse();else if(x==="prev"||x==="next"){x==="prev"&&S.reverse();const k=S.indexOf(y.currentTarget);S=d.loop?Nv(S,k+1):S.slice(k+1)}setTimeout(()=>gu(S))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:m!=null}):i})})});mu.displayName=hu;var Ev={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Iv(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Av(e,t,n){const r=Iv(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Ev[r]}function gu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Nv(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var _v=pu,jv=mu,Mv=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},yr=new WeakMap,Xo=new WeakMap,Jo={},$i=0,xu=function(e){return e&&(e.host||xu(e.parentNode))},Pv=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=xu(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Rv=function(e,t,n,r){var o=Pv(t,Array.isArray(e)?e:[e]);Jo[n]||(Jo[n]=new WeakMap);var s=Jo[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(p){if(a.has(p))d(p);else try{var h=p.getAttribute(r),g=h!==null&&h!=="false",m=(yr.get(p)||0)+1,y=(s.get(p)||0)+1;yr.set(p,m),s.set(p,y),i.push(p),m===1&&g&&Xo.set(p,!0),y===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(x){console.error("aria-hidden: cannot operate on ",p,x)}})};return d(t),a.clear(),$i++,function(){i.forEach(function(f){var p=yr.get(f)-1,h=s.get(f)-1;yr.set(f,p),s.set(f,h),p||(Xo.has(f)||f.removeAttribute(r),Xo.delete(f)),h||f.removeAttribute(n)}),$i--,$i||(yr=new WeakMap,yr=new WeakMap,Xo=new WeakMap,Jo={})}},Fi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Mv(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Rv(r,o,n,"aria-hidden")):function(){return null}},xn=function(){return xn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},xn.apply(this,arguments)};function yu(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function Ov(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Zo="right-scroll-bar-position",Qo="width-before-scroll-bar",Dv="with-scroll-bars-hidden",Lv="--removed-body-scroll-bar-size";function Bi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function $v(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Fv=typeof window<"u"?v.useLayoutEffect:v.useEffect,vu=new WeakMap;function Bv(e,t){var n=$v(null,function(r){return e.forEach(function(o){return Bi(o,r)})});return Fv(function(){var r=vu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Bi(a,null)}),s.forEach(function(a){o.has(a)||Bi(a,i)})}vu.set(n,e)},[e]),n}function zv(e){return e}function Uv(e,t){t===void 0&&(t=zv);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function Hv(e){e===void 0&&(e={});var t=Uv(null);return t.options=xn({async:!0,ssr:!1},e),t}var wu=function(e){var t=e.sideCar,n=yu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return v.createElement(r,xn({},n))};wu.isSideCarExport=!0;function Wv(e,t){return e.useMedium(t),wu}var bu=Hv(),zi=function(){},es=v.forwardRef(function(e,t){var n=v.useRef(null),r=v.useState({onScrollCapture:zi,onWheelCapture:zi,onTouchMoveCapture:zi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,p=e.sideCar,h=e.noRelative,g=e.noIsolation,m=e.inert,y=e.allowPinchZoom,x=e.as,w=x===void 0?"div":x,S=e.gapMode,k=yu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=p,T=Bv([n,t]),E=xn(xn({},k),o);return v.createElement(v.Fragment,null,d&&v.createElement(C,{sideCar:bu,removeScrollBar:c,shards:f,noRelative:h,noIsolation:g,inert:m,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:S}),i?v.cloneElement(v.Children.only(a),xn(xn({},E),{ref:T})):v.createElement(w,xn({},E,{className:l,ref:T}),a))});es.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},es.classNames={fullWidth:Qo,zeroRight:Zo};var Vv=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Kv(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Vv();return t&&e.setAttribute("nonce",t),e}function qv(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Gv(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Yv=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Kv())&&(qv(t,n),Gv(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Xv=function(){var e=Yv();return function(t,n){v.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Su=function(){var e=Xv(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Jv={left:0,top:0,right:0,gap:0},Ui=function(e){return parseInt(e||"",10)||0},Zv=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Ui(n),Ui(r),Ui(o)]},Qv=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Jv;var t=Zv(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},ew=Su(),vr="data-scroll-locked",tw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
39
39
  .`.concat(Dv,` {
40
40
  overflow: hidden `).concat(r,`;
41
41
  padding-right: `).concat(a,"px ").concat(r,`;
@@ -134,4 +134,4 @@ ${t}</tr>
134
134
  `}strong(t){return`<strong>${t}</strong>`}em(t){return`<em>${t}</em>`}codespan(t){return`<code>${t}</code>`}br(){return this.options.xhtml?"<br/>":"<br>"}del(t){return`<del>${t}</del>`}link(t,n,r){if(t=sp(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o='<a href="'+t+'"';return n&&(o+=' title="'+n+'"'),o+=">"+r+"</a>",o}image(t,n,r){if(t=sp(this.options.sanitize,this.options.baseUrl,t),t===null)return r;let o=`<img src="${t}" alt="${r}"`;return n&&(o+=` title="${n}"`),o+=this.options.xhtml?"/>":">",o}text(t){return t}}class up{strong(t){return t}em(t){return t}codespan(t){return t}del(t){return t}html(t){return t}text(t){return t}link(t,n,r){return""+r}image(t,n,r){return""+r}br(){return""}}class dp{constructor(){this.seen={}}serialize(t){return t.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig,"").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g,"").replace(/\s/g,"-")}getNextSafeSlug(t,n){let r=t,o=0;if(this.seen.hasOwnProperty(r)){o=this.seen[t];do o++,r=t+"-"+o;while(this.seen.hasOwnProperty(r))}return n||(this.seen[t]=o,this.seen[r]=0),r}slug(t,n={}){const r=this.serialize(t);return this.getNextSafeSlug(r,n.dryrun)}}class Fn{constructor(t){this.options=t||or,this.options.renderer=this.options.renderer||new _a,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new up,this.slugger=new dp}static parse(t,n){return new Fn(n).parse(t)}static parseInline(t,n){return new Fn(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,p,h,g,m,y,x,w,S,k,C,T;const E=t.length;for(o=0;o<E;o++){if(h=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[h.type]&&(T=this.options.extensions.renderers[h.type].call({parser:this},h),T!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(h.type))){r+=T||"";continue}switch(h.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(h.tokens),h.depth,op(this.parseInline(h.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(h.text,h.lang,h.escaped);continue}case"table":{for(f="",d="",a=h.header.length,s=0;s<a;s++)d+=this.renderer.tablecell(this.parseInline(h.header[s].tokens),{header:!0,align:h.align[s]});for(f+=this.renderer.tablerow(d),p="",a=h.rows.length,s=0;s<a;s++){for(c=h.rows[s],d="",l=c.length,i=0;i<l;i++)d+=this.renderer.tablecell(this.parseInline(c[i].tokens),{header:!1,align:h.align[i]});p+=this.renderer.tablerow(d)}r+=this.renderer.table(f,p);continue}case"blockquote":{p=this.parse(h.tokens),r+=this.renderer.blockquote(p);continue}case"list":{for(g=h.ordered,m=h.start,y=h.loose,a=h.items.length,p="",s=0;s<a;s++)w=h.items[s],S=w.checked,k=w.task,x="",w.task&&(C=this.renderer.checkbox(S),y?w.tokens.length>0&&w.tokens[0].type==="paragraph"?(w.tokens[0].text=C+" "+w.tokens[0].text,w.tokens[0].tokens&&w.tokens[0].tokens.length>0&&w.tokens[0].tokens[0].type==="text"&&(w.tokens[0].tokens[0].text=C+" "+w.tokens[0].tokens[0].text)):w.tokens.unshift({type:"text",text:C}):x+=C),x+=this.parse(w.tokens,y),p+=this.renderer.listitem(x,k,S);r+=this.renderer.list(p,g,m);continue}case"html":{r+=this.renderer.html(h.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(h.tokens));continue}case"text":{for(p=h.tokens?this.parseInline(h.tokens):h.text;o+1<E&&t[o+1].type==="text";)h=t[++o],p+=`
135
135
  `+(h.tokens?this.parseInline(h.tokens):h.text);r+=n?this.renderer.paragraph(p):p;continue}default:{const N='Token with "'+h.type+'" type was not found.';if(this.options.silent){console.error(N);return}else throw new Error(N)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const l='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(l);return}else throw new Error(l)}}}return r}}class Ds{constructor(t){this.options=t||or}preprocess(t){return t}postprocess(t){return t}}qh(Ds,"passThroughHooks",new Set(["preprocess","postprocess"]));function aC(e,t,n){return r=>{if(r.message+=`
136
136
  Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+jt(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function fp(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...xe.defaults,...s};const i=aC(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(oC(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(f){return i(f)}const c=function(f){let p;if(!f)try{r.walkTokens&&xe.walkTokens(l,r.walkTokens),p=t(l,r),r.hooks&&(p=r.hooks.postprocess(p))}catch(h){f=h}return r.highlight=a,f?i(f):o(null,p)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;xe.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(p,h){if(p)return c(p);h!=null&&h!==f.text&&(f.text=h,f.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(xe.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&xe.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function xe(e,t,n){return fp($n.lex,Fn.parse)(e,t,n)}xe.options=xe.setOptions=function(e){return xe.defaults={...xe.defaults,...e},VS(xe.defaults),xe},xe.getDefaults=ep,xe.defaults=or,xe.use=function(...e){const t=xe.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=xe.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=xe.defaults.renderer||new _a;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=xe.defaults.tokenizer||new Na;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=xe.defaults.hooks||new Ds;for(const s in n.hooks){const i=o[s];Ds.passThroughHooks.has(s)?o[s]=a=>{if(xe.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=xe.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}xe.setOptions(r)})},xe.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(xe,r)),r.type){case"table":{for(const o of r.header)n=n.concat(xe.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(xe.walkTokens(s.tokens,t));break}case"list":{n=n.concat(xe.walkTokens(r.items,t));break}default:xe.defaults.extensions&&xe.defaults.extensions.childTokens&&xe.defaults.extensions.childTokens[r.type]?xe.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(xe.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(xe.walkTokens(r.tokens,t)))}return n},xe.parseInline=fp($n.lexInline,Fn.parseInline),xe.Parser=Fn,xe.parser=Fn.parse,xe.Renderer=_a,xe.TextRenderer=up,xe.Lexer=$n,xe.lexer=$n.lex,xe.Tokenizer=Na,xe.Slugger=dp,xe.Hooks=Ds,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,Fn.parse,$n.lex;function io({content:e,className:t="",allowHtml:n=!1,style:r}){const o=b.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof xe.parse=="function"?xe.parse(i):xe(i)}return typeof xe.parse=="function"?xe.parse(e):xe(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=b.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:te("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}const lC={MODE:"library"};function cC(){var i;const e=typeof globalThis<"u"?globalThis.process:void 0,t=typeof((i=e==null?void 0:e.env)==null?void 0:i.NODE_ENV)=="string"?e.env.NODE_ENV:void 0;if(t)return t==="production";const n=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Xs&&Xs.tagName.toUpperCase()==="SCRIPT"&&Xs.src||new URL("index.umd.js",document.baseURI).href}<"u"?lC:void 0,r=typeof(n==null?void 0:n.MODE)=="string"?n.MODE:void 0,o=typeof(n==null?void 0:n.NODE_ENV)=="string"?n.NODE_ENV:void 0;return(r??o)==="production"}function uC(){return!cC()}function dC(){return typeof window>"u"?!1:window.__ARTIFACT_DEBUG__===!0}function fC(){return uC()||dC()}function pC({preview:e,idx:t}){return b.useEffect(()=>{fC()&&console.debug(`[MessageComponent] Preview ${t} mounted:`,{src:e.src.substring(0,100),alt:e.alt,label:e.label})},[t,e]),u.jsxs("div",{className:"space-y-2",children:[e.label&&u.jsxs("p",{className:"text-[0.65rem] uppercase tracking-wide text-muted-foreground",children:["Artifact: ",e.label]}),u.jsx("div",{className:"overflow-hidden rounded border border-border/60 bg-background/60 p-1 shadow-sm",children:u.jsx("img",{src:e.src,alt:e.alt,title:e.label,loading:"lazy",className:"h-auto max-h-[420px] w-full rounded object-contain",onLoad:()=>{},onError:n=>{console.error(`[MessageComponent] ❌ Image failed to load for artifact ${t}:`,{alt:e.alt,label:e.label,message:n.target.alt})}})})]})}const ao=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));ao.displayName="Card";const lo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("flex flex-col space-y-1.5 p-6",e),...t}));lo.displayName="CardHeader";const co=v.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:te("text-2xl font-semibold leading-none tracking-tight",e),...t}));co.displayName="CardTitle";const pp=v.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:te("text-sm text-muted-foreground",e),...t}));pp.displayName="CardDescription";const uo=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("p-6 pt-0",e),...t}));uo.displayName="CardContent";const hp=v.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:te("flex items-center p-6 pt-0",e),...t}));hp.displayName="CardFooter";function hC({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=oo(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(ao,{className:te("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(lo,{className:"pb-3",children:[u.jsx(co,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(pp,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(uo,{className:"pt-0 pb-3",children:a}),u.jsx(hp,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(Je,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(Je,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}const mC="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function mp({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:mC,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:oo(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:oo(e)})}function gC({message:e,isStreaming:t=!1}){const n=e.name??"tool",r=b.useMemo(()=>{const a=e.additionalKwargs??{};return Array.isArray(a.toolProgress)?[...a.toolProgress]:[]},[e]),s=r.some(a=>a.type==="tool.start"||a.type==="tool.call"||a.type==="message.start")?`Running ${n}…`:void 0;return t||r.length>0?u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[t&&u.jsx(le.Loader,{className:"h-3 w-3 animate-spin"}),u.jsx("span",{children:s??`Running ${n}…`})]}),r.length>0&&u.jsx("div",{className:"space-y-2 text-xs text-muted-foreground",children:r.map((a,l)=>{var c;return u.jsxs("div",{className:"rounded border border-current/10 bg-muted/60 p-2 text-[11px] leading-snug",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between text-[8px] uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:((c=a.type)==null?void 0:c.replace(/\./g," "))??"progress"}),u.jsx("span",{children:a.idx??l+1})]}),a.content&&u.jsx("p",{className:"mt-1 text-[12px] text-foreground/90",children:a.content}),u.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[10px] opacity-70",children:[typeof a.factsFound=="number"&&u.jsxs("span",{children:["Facts found: ",a.factsFound]}),typeof a.isSufficient=="boolean"&&u.jsxs("span",{children:["Research ",a.isSufficient?"sufficient":"needs more data"]})]})]},`tool-progress-${n}-${l}`)})})]}):null}function xC({message:e,viewMode:t,isStreaming:n=!1}){const o=Ef(e).name||"tool",s=l=>{if(l==null)return null;const c=typeof l=="string"?Sa(l)??l:l;if(c&&typeof c=="object")return u.jsx(mp,{data:c});const d=typeof c=="string"?c:(()=>{try{return oo(c)}catch{return String(c??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:d})},i=l=>{if(l==null)return null;const{content:c,isMarkdown:d}=gS(l);return d?u.jsx(io,{content:c,className:"text-current"}):s(l)},a=()=>{const l=e.content.find(f=>f.type!=="tool_call");if(!l)return u.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:u.jsxs("span",{children:["Running ",o,"…"]})});if(l.type==="text"){const p=(l.text??"").trim();if(!p)return null;const h=Ts(p);return i(h)}const c=ro(l),d=Ts(c);return i(d)};return u.jsxs("div",{className:"space-y-2",children:[u.jsx(gC,{message:e,isStreaming:n}),t==="expanded"&&a()]})}function yC(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=Aa(),[o,s]=b.useState({}),[i,a]=b.useState(null),[l,c]=b.useState(!1),d=b.useCallback(()=>{c(!1),a(null)},[]),f=b.useCallback(h=>{a(h),c(!0)},[]),p=b.useCallback(async(h,g,m)=>{var y,x;if(!t){h.preventDefault();return}if(o[m]){h.preventDefault();return}try{const w=String(g.url??""),S=w.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){h.preventDefault();const k=S[1],C=g.name||`file_${k}`,T=g.mimeType||"application/octet-stream";f({id:k,name:C,mimeType:T});return}if(w.startsWith("data:")){h.preventDefault(),s(C=>({...C,[m]:!0}));const k=r({title:"Fetching file...",description:"",open:!0});try{const C=await kS(n??void 0);if(!C||!Array.isArray(C))throw new Error("Invalid file list response");const T=C.find(E=>!E||typeof E!="object"||!((E.filename??"")===(g.name??""))?!1:typeof g.size=="number"&&typeof E.size=="number"?E.size===g.size:!0);if(!(T!=null&&T.id))throw new Error(`File "${g.name}" is not yet available on the server`);if(!T.id||!T.filename)throw new Error("Invalid file data received from server");f({id:T.id,name:g.name||T.filename||`file_${T.id}`,mimeType:g.mimeType||T.mime_type||"application/octet-stream"}),(y=k.update)==null||y.call(k,{id:k.id,title:"Success",description:`Opened ${g.name}`,open:!0})}catch(C){console.error("Failed to fetch server file:",C);const T=C instanceof Error?C.message:"Unknown error occurred";(x=k.update)==null||x.call(k,{id:k.id,title:"Failed",description:T}),r({title:"Failed to fetch file",description:T,open:!0})}finally{s(C=>({...C,[m]:!1}))}}}catch(w){console.error("File click error:",w),s(S=>({...S,[m]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:p,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function vC({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:te("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(io,{content:e,allowHtml:!1}):u.jsxs("pre",{className:te("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(Je,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(le.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(le.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function wC({className:e}){const[t,n]=b.useState(0);return b.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:te("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}function gp(e){var n;const t=(n=e.additionalKwargs)==null?void 0:n.toolProgress;return Array.isArray(t)?t:[]}const Ls=b.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:f=!0,showArtifactPreviews:p=!0,customStyles:h={},onEdit:g,onRegenerate:m,onCancelEdit:y,onCopy:x,activeInterrupt:w,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,checkpointCandidates:T=[],activeCheckpointId:E=null,onSelectCheckpoint:N,defaultCheckpointId:_=null,messageParentCheckpointId:D=null}){const[B,G]=b.useState(!1),[V,P]=b.useState("preview"),[M,A]=b.useState(!1),{currentThreadId:F}=jo(),{respondToInterrupt:L}=Mo(),R=l==="phone"||l==="half-screen",z=t.role,X=z==="tool",ne=b.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),ye=!!ne,Te=!(r&&z!=="user"),{uploadingFiles:q,handleFileClick:U,fileViewerOpen:Z,currentFileInfo:$,closeFileViewer:Y}=yC({allowFileOpen:Te,currentThreadId:F}),Q=b.useMemo(()=>{switch(z){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[z]),de=b.useMemo(()=>{if(ne)return"";const j=t.content;return Array.isArray(j)?xS(j):""},[ne,t]),oe=b.useMemo(()=>{if(ne)return{};const j=t.content;return Array.isArray(j)?Ef(t):{}},[ne,t]),_e=b.useMemo(()=>X?!!(t.additionalKwargs??{}).toolStreaming:!1,[X,t]),ze=b.useMemo(()=>{if(ne)return[];const j=t.content;return Array.isArray(j)?j.filter(J=>J.type==="image_url"):[]},[ne,t]),se=b.useMemo(()=>{if(ne)return[];const j=t.content;return Array.isArray(j)?j.filter(J=>J.type==="file"):[]},[ne,t]),me=b.useMemo(()=>{if(ne)return[];const j=t.content;return Array.isArray(j)?j.filter(J=>J.type==="interrupt"):[]},[ne,t]),Pe=(w==null?void 0:w.id)??(w==null?void 0:w.interrupt_id),Ve=ks(Pe),ut=w==null?void 0:w.value,Ke=b.useMemo(()=>{if(ne)return"";const j=t.content;return Array.isArray(j)?yS(j):""},[ne,t]),qe=b.useMemo(()=>{if(ne||!p)return[];const J=t.artifact;if(!J)return[];const re=[],ie=[...Array.isArray(J.plots)?J.plots:[]];for(const ce of ie){const Xe=CS(ce);Xe&&re.push(Xe)}return re},[ne,t,p]),Qe=b.useCallback(async()=>{const j=X?Ke:de;async function J(re){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(re);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const ie=new Blob([re],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":ie})]);return}throw new Error("Clipboard API not supported in this context.")}try{await J(j),G(!0),setTimeout(()=>G(!1),2e3),x==null||x(j)}catch(re){console.error("Failed to copy:",re)}},[X,Ke,de,x]),Ge=b.useCallback(()=>{if(!g)return;const j=X?Ke:de,J="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};g(t.id,j,J)},[g,t.id,X,Ke,de,t]),et=b.useCallback(()=>{m==null||m(n)},[m,n]),st=b.useCallback(()=>{const J=te(R?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",Q);switch(z){case"user":return u.jsx(le.User,{className:J});case"assistant":return u.jsx(le.Bot,{className:J});case"tool":return u.jsx(le.Wrench,{className:J});default:return u.jsx(le.Bot,{className:J})}},[R,Q,z]),Mt=b.useCallback(()=>{const j="group relative mb-4 flex w-full";switch(z){case"user":return te(j,"justify-end");case"assistant":case"tool":case"system":return te(j,"justify-start");default:return j}},[z]),gt=b.useCallback(()=>{const j=te("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",R&&"px-3 py-2 text-sm");if(ye)return te(j,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(z){case"user":return te(j,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return te(j,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return te(j,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return te(j,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return te(j,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[R,ye,z]),Ct=b.useCallback(async j=>{if(S)return;const J=ks((j==null?void 0:j.id)??(j==null?void 0:j.interrupt_id));if(!J){console.warn("Interrupt part missing id",j);return}try{k==null||k(),await L(J,!0)}catch(re){console.error("Failed to approve interrupt:",re)}finally{C==null||C()}},[S,C,k,L]),it=b.useCallback(async j=>{if(S)return;const J=ks((j==null?void 0:j.id)??(j==null?void 0:j.interrupt_id));if(!J){console.warn("Interrupt part missing id",j);return}try{k==null||k(),await L(J,!1)}catch(re){console.error("Failed to reject interrupt:",re)}finally{C==null||C()}},[S,C,k,L]),St=b.useCallback(({part:j,i:J})=>{if(j.type==="text"){const re=j.text??"",ie=re.trim(),ce=Sa(ie);return ce&&z!=="tool"?u.jsx(mp,{data:ce},J):z==="user"&&c&&ie.length>d?u.jsx(vC,{text:ie,expanded:M,onExpandedChange:A,previewLength:d,isCompact:R},J):u.jsx(io,{content:re,allowHtml:!1},J)}if(j.type==="image_url"){const re=j;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:re.url,alt:re.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},J)}if(j.type==="file"){const re=j,ie=re.name||"file";return u.jsxs("a",{href:re.url,onClick:ce=>U(ce.nativeEvent,re,J),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
137
- dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[q[J]?u.jsx(le.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[ie,q[J]?" (processing)":""]})]},J)}if(j.type==="interrupt"){const re=j,ie=ks((re==null?void 0:re.id)??(re==null?void 0:re.interrupt_id)),ce=!!(Ve&&ie&&ie===Ve),Xe=ce?ut??(re==null?void 0:re.value):re==null?void 0:re.value,Ie=ie?{...re,id:ie,interrupt_id:ie}:re;return u.jsx(hC,{interruptPart:Ie,onApprove:Ct,onReject:it,disabled:S,isActive:ce,payload:Xe},J)}return null},[U,q,Ct,it,z,c,d,M,R,Ve,ut,w,S,me]),Pt=b.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(le.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),zt=b.useCallback(()=>{const j=de.trim().length>0||ze.length>0||se.length>0||me.length>0;if(!X&&se.length>0&&!r)return Pt();if(!X&&!j&&!r)return null;if(X)return!f&&qe.length>0?null:f?u.jsx(xC,{message:t,viewMode:V,isStreaming:_e},t.id):null;if(!X&&!ne){const J=t,re=u.jsx("div",{className:"space-y-2",children:J.content.map((ie,ce)=>u.jsx(St,{part:ie,i:ce},ce))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[re,u.jsx(wC,{className:Q})]}):re}},[de,ze.length,se.length,me.length,r,X,V,f,qe.length,Pt,Q]),nn=b.useMemo(()=>ne?"Assistant":vS(t),[ne,t]),Le=b.useMemo(()=>ne?[]:Array.isArray(T)?T:[],[T,ne]),Sn=b.useMemo(()=>{var j;return Le.length?_&&Le.some(J=>J.id===_)?_:((j=Le[0])==null?void 0:j.id)??null:null},[_,Le]),We=b.useMemo(()=>!Le.length||!E?null:Le.some(j=>j.id===E)?E:null,[E,Le])??Sn,pt=z==="user"&&Le.length>0&&typeof N=="function",Rt=b.useCallback((j,J=!1)=>{if(!N)return;const re=(j==null?void 0:j.id)??null,ie=(j==null?void 0:j.parentId)??D??null;N(re,ie,J)},[D,N]),Ye=b.useMemo(()=>We?Le.findIndex(j=>j.id===We):-1,[We,Le]),H=b.useMemo(()=>Ye<0?null:Le[Ye]??null,[Ye,Le]);return X&&!f&&qe.length===0?null:ye&&ne?u.jsx("div",{className:te(Mt(),h.container),children:u.jsxs("div",{className:te(gt(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(le.Bot,{className:te("h-4 w-4",Q)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(io,{content:ne.content,className:"text-current"})]})}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:te(Mt(),h.container),children:u.jsxs("div",{className:te(gt(),h.content),children:[(i||a||X)&&u.jsxs("div",{className:te("flex items-center justify-between mb-2 pb-2 border-b border-current/10",R&&"mb-1 pb-1",Q,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[st(),a&&nn&&u.jsx("span",{className:te("font-medium",R?"text-xs":"text-sm"),children:nn}),X&&u.jsxs(Tf,{variant:"outline",className:te("text-xs flex items-center gap-1 cursor-pointer select-none",Q,"border border-current/40",R&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":V==="expanded",onClick:()=>P(j=>j==="expanded"?"preview":"expanded"),onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),P(J=>J==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:oe.name??"Tool Output"}),oe.toolCallId&&u.jsx("span",{className:"opacity-70",children:oe.toolCallId.slice(0,8)}),V==="expanded"?u.jsx(le.ChevronUp,{className:"h-3 w-3"}):u.jsx(le.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[pt&&H&&Ye>=0&&u.jsx("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ye<Le.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Ye>=Le.length-1)return;const j=Le[Ye+1];j&&Rt(j)},"aria-label":"Older checkpoint (back in time)",disabled:Ye>=Le.length-1,children:u.jsx(le.ChevronLeft,{className:"h-3 w-3"})}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"whitespace-nowrap",children:[Le.length-Ye," / ",Le.length]})}),u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ye>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(!(Ye<=0))if(Ye===1)Rt(null,!0);else{const j=Le[Ye-1];j&&Rt(j,!1)}},"aria-label":"Newer checkpoint (forward in time)",disabled:Ye<=0,children:u.jsx(le.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:te("text-xs opacity-60",Q,R&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:te("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:te("h-6 w-6 p-0 hover:bg-foreground/10",Q,R&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(le.Copy,{className:te(B?"text-success":Q,R?"h-3 w-3":"h-4 w-4")})})}),z==="user"&&g&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:Ge,className:te("h-6 w-6 p-0 hover:bg-foreground/10",Q,R&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(le.Edit,{className:te(Q,R?"h-3 w-3":"h-4 w-4")})}),z==="assistant"&&m&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:et,className:te("h-6 w-6 p-0 hover:bg-foreground/10",Q,R&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(le.RotateCcw,{className:te(Q,R?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[zt(),p&&qe.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:qe.map((j,J)=>u.jsx(pC,{preview:j,idx:J},`artifact-${J}`))})]}),X&&V==="expanded"&&(oe.toolCallId||oe.name)&&u.jsxs("div",{className:te("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",R&&"text-xs"),children:[oe.name&&u.jsxs("div",{children:["Function: ",oe.name]}),oe.toolCallId&&u.jsxs("div",{children:["Call ID: ",oe.toolCallId]})]}),!(i||a||X)&&s&&!o&&u.jsxs("div",{className:te("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(le.Copy,{className:te(B?"text-success":"text-current",R?"h-3 w-3":"h-4 w-4")})}),z==="user"&&g&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:Ge,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(le.Edit,{className:te("text-current",R?"h-3 w-3":"h-4 w-4")})}),z==="assistant"&&m&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:et,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(le.RotateCcw,{className:te("text-current",R?"h-3 w-3":"h-4 w-4")})})]})]})}),$&&u.jsx(WS,{isOpen:Z,onClose:Y,fileId:$.id,fileName:$.name,mimeType:$.mimeType})]})},(e,t)=>{var l,c,d,f,p,h,g,m;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&If(e.message)===If(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","attemptMeta"].every(y=>e[y]===t[y]),s=((l=e.customStyles)==null?void 0:l.container)===((c=t.customStyles)==null?void 0:c.container)&&((d=e.customStyles)==null?void 0:d.content)===((f=t.customStyles)==null?void 0:f.content)&&((p=e.customStyles)==null?void 0:p.actions)===((h=t.customStyles)==null?void 0:h.actions)&&((g=e.customStyles)==null?void 0:g.header)===((m=t.customStyles)==null?void 0:m.header);if(!o||!s)return!1;const i=gp(e.message),a=gp(t.message);return i.length===a.length});Ls.displayName="MessageComponent";function bC(e,t){return b.useMemo(()=>{var d,f,p,h,g;const n=e&&"type"in e&&e.type==="default_message";let r=[],o=null,s={},i={},a=null,l=null,c=null;if(!n&&e){const m=e,y=m.checkpointId??null;s=m.additionalKwargs??{},i=m.responseMetadata??{};const x=y&&t.checkpointMetaById?t.checkpointMetaById.get(y)??null:null;a=typeof s.step=="number"?s.step:typeof i.step=="number"?i.step:(x==null?void 0:x.step)??null;const w=typeof s.source=="string"?s.source:typeof i.source=="string"?i.source:(x==null?void 0:x.source)??null;l=w?String(w):null;const S=a!==null&&l?`${a}:${l}`:null;if(S&&((d=t.checkpointIndexByKey)!=null&&d.has(S))?r=t.checkpointIndexByKey.get(S)??[]:y&&x&&(r=[x]),o=y??((f=r[0])==null?void 0:f.id)??null,c=y?((p=t.attemptMetaById)==null?void 0:p.get(y))??null:null,!c&&(e==null?void 0:e.role)==="user"&&(e!=null&&e.id)&&t.userMessageIdToAttempts){const k=t.userMessageIdToAttempts.get(e.id);if(k&&k.length>0){const C=k[0].checkpointId;c=((h=t.attemptMetaById)==null?void 0:h.get(C))??null,c&&console.log(`[useMessageMetadata] Found attempt by user message ID "${e.id}":`,k.length,"versions")}}if(!c&&r.length>0&&t.attemptMetaById){const k=t.attemptMetaById.get(r[0].id);k&&(c=k)}if(c&&c.attemptCount>1&&t.attemptMetaById){const k=c.baseUserMessageId;if(k){const C=[];for(const[T,E]of t.attemptMetaById.entries())if(E.baseUserMessageId===k){const N=(g=t.checkpointMetaById)==null?void 0:g.get(T);N&&C.push(N)}C.length>0&&(r=C)}}if(c&&c.attemptCount>1&&t.checkpointMetaById&&t.attemptMetaById){const k=[];for(const[C,T]of t.checkpointMetaById.entries()){const E=t.attemptMetaById.get(C);E&&E.attemptCount===c.attemptCount&&E.baseUserMessageId===c.baseUserMessageId&&k.push(T)}k.sort((C,T)=>{const E=C.createdAt?Date.parse(C.createdAt):0;return(T.createdAt?Date.parse(T.createdAt):0)-E}),k.length>0&&(r=k,console.log("[useMessageMetadata] Populated checkpointCandidates with all attempts:",{messageId:e.id,attemptCount:c.attemptCount,candidateIds:r.map(C=>C.id)}))}}return{checkpointCandidates:r,defaultCheckpointId:o,attemptMeta:c,resolvedStep:a,resolvedSource:l}},[e,t.checkpointMetaById,t.checkpointIndexByKey,t.attemptMetaById,t.userMessageIdToAttempts])}const xp=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,yp=b.memo(function({message:t,index:n,isStreaming:r,streamingAssistantId:o,streamingDebounceMs:s,layoutSize:i,enableMessageEditing:a,editingMessageId:l,onEdit:c,onRegenerate:d,onCancelEdit:f,activeInterrupt:p,disableInterruptActions:h,onInterruptActionStart:g,onInterruptActionEnd:m,showToolMessages:y,showArtifactPreviews:x,checkpointMetaById:w,checkpointIndexByKey:S,attemptMetaById:k,userMessageIdToAttempts:C,activeCheckpointId:T,onSelectCheckpoint:E}){const N=xp(t,n),_="type"in t&&t.type==="default_message",{checkpointCandidates:D,defaultCheckpointId:B,attemptMeta:G}=bC(t,{checkpointMetaById:w,checkpointIndexByKey:S,attemptMetaById:k,userMessageIdToAttempts:C}),V=t&&!_?t.additionalKwargs??{}:{},P=t&&!_?t.responseMetadata??{}:{},M=(()=>{if(typeof V.parentCheckpointId=="string")return V.parentCheckpointId;if(typeof P.parentCheckpointId=="string")return P.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":N,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ls,{message:t,messageIndex:n,isStreamingMessage:r&&o===t.id,streamingDebounceMs:s,isEditing:l===t.id,showActions:a,showTimestamp:!1,showAgentName:!0,layoutSize:i,onEdit:c,onRegenerate:()=>d(n),onCancelEdit:f,activeInterrupt:p,disableInterruptActions:h,onInterruptActionStart:g,onInterruptActionEnd:m,showToolMessages:y,showArtifactPreviews:x,checkpointCandidates:D,activeCheckpointId:T??null,onSelectCheckpoint:E,defaultCheckpointId:B,messageParentCheckpointId:M,attemptMeta:G})})});yp.displayName="MessageRow";const ja=b.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:p,emptyMessage:h,followNewMessages:g=!0,isNavigatingCheckpoint:m=!1,onScrollAway:y,onAtBottom:x,activeInterrupt:w,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T=!0,showArtifactPreviews:E=!0,checkpointMetaById:N,checkpointIndexByKey:_,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:G,onSelectCheckpoint:V,createSyntheticThinkingMessage:P=!1},M)=>{const A=b.useRef(null),F=b.useRef(null),L=b.useRef(!1),R=b.useRef(!1),[z,X]=b.useState(!0),ne=b.useMemo(()=>w?e.some(se=>"type"in se&&se.type==="default_message"?!1:Array.isArray(se==null?void 0:se.content)&&se.content.some(me=>me&&me.type==="interrupt"&&(me.id??me.interrupt_id)===w.id)):!1,[w,e]),ye=b.useMemo(()=>{if(!w||ne)return null;const se=w.id&&String(w.id).trim()?String(w.id).trim():"pending-interrupt";let me;const Pe=w.value;if(Pe&&typeof Pe=="object"&&!Array.isArray(Pe)){const Ve=Pe.title;typeof Ve=="string"&&Ve.trim()&&(me=Ve.trim())}return{id:`interrupt-${se}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:se,value:Pe,title:me}]}},[w,ne]),Te=b.useMemo(()=>ye?[...e,ye]:e,[e,ye]),q=b.useMemo(()=>!P||!t?Te:!Te.some(me=>me.role==="assistant")&&Te.length>0?[...Te,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString()}]:Te,[Te,t,P]),U=b.useMemo(()=>T?q:q.filter(se=>(se==null?void 0:se.role)!=="tool"),[q,T]),Z=b.useCallback(se=>{X(se),y&&y(!se),x&&x(se)},[y,x]),$=b.useMemo(()=>{if(a)return async()=>{if(!L.current){L.current=!0;try{await a()}finally{L.current=!1}}}},[a]),Y=b.useMemo(()=>!g||m?!1:z?"auto":!1,[z,g,m]),Q=b.useMemo(()=>{if(typeof h!="string")return null;const se=h.trim();return se?{id:"default-message",role:"assistant",type:"default_message",content:se,createdAt:new Date().toISOString()}:null},[h]),de=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),oe=()=>Q?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Ls,{message:Q,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{},showArtifactPreviews:E})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:h??"No messages yet. Start a conversation!"}),_e=U.length,ze=_e>0;return b.useEffect(()=>{var se,me;if(_e===0){R.current=!1;return}if(!R.current)if(R.current=!0,A.current&&U.length>0){const Pe=U.length-1;(me=(se=A.current).scrollToIndex)==null||me.call(se,{index:Pe,align:"end",behavior:"auto"})}else F.current&&(F.current.scrollTop=F.current.scrollHeight)},[_e,U.length]),b.useImperativeHandle(M,()=>({scrollToLatest:()=>{var se,me;if(A.current&&U.length>0){const Pe=U.length-1;(me=(se=A.current).scrollToIndex)==null||me.call(se,{index:Pe,align:"end",behavior:"auto"})}else F.current&&(F.current.scrollTop=F.current.scrollHeight)},scrollToTop:()=>{var se,me;A.current&&U.length>0?(me=(se=A.current).scrollToIndex)==null||me.call(se,{index:0,align:"start",behavior:"auto"}):F.current&&(F.current.scrollTop=0)}}),[U]),u.jsx("div",{className:de,style:p,children:u.jsx("div",{className:"relative flex-1 min-h-0",children:ze?u.jsx(Q0,{ref:se=>{A.current=se},scrollerRef:se=>{F.current=se instanceof HTMLDivElement?se:null},data:U,followOutput:Y,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{$&&$()},atBottomStateChange:Z,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(se,me)=>xp(me,se),itemContent:(se,me)=>u.jsx(yp,{message:me,index:se,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:l,onRegenerate:c,onCancelEdit:d,activeInterrupt:w,disableInterruptActions:S,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T,showArtifactPreviews:E,checkpointMetaById:N,checkpointIndexByKey:_,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:G,onSelectCheckpoint:V})}):oe()})})});ja.displayName="MessageList";const vp={value:""};function $s({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:c=!0,showToolMessages:d=!0,showArtifactPreviews:f=!0,customStyles:p={},onMessageSent:h,onExcelUploadSuccess:g,onError:m}){const{api:y}=di(),{currentThreadId:x}=jo(),{threadId:w,messages:S,isHistoryLoading:k,isLoading:C,navigateToCheckpoint:T,returnToLatest:E,checkpoint:N,checkpoints:_,interrupt:D,metadata:B,timelineCheckpoints:G,messagePreviews:V}=Mo(),{isStreaming:P,error:M,connectionState:A,submit:F,stop:L}=pc(),R=w??x??null,z=(N==null?void 0:N.id)??null,X=(N==null?void 0:N.namespace)??null,ne=(B==null?void 0:B.assemblingMessageId)??null,ye=D,[Te,q]=b.useState(!1);b.useEffect(()=>{ye||q(!1)},[ye]);const U=b.useCallback(()=>{q(!0)},[]),Z=b.useCallback(()=>{q(!1)},[]),$=!!ye||Te,[Y,Q]=b.useState(null),[de,oe]=b.useState(""),[_e,ze]=b.useState(null),[se,me]=b.useState(null),[Pe,Ve]=b.useState([]),[ut,Ke]=b.useState(0),[qe,Qe]=b.useState(0),[Ge,et]=b.useState(!1),[st,Mt]=b.useState(null),[gt,Ct]=b.useState(null),[it,St]=b.useState(!1),[Pt,zt]=b.useState(null),nn=b.useRef(!1),[Le,Sn]=b.useState(()=>vp.value),tt=b.useRef(Le),We=b.useRef(null),pt=b.useCallback(he=>{vp.value=he,Sn(he)},[]),[Rt,Ye]=b.useState(!1),H=b.useRef(null),{checkpointMetaById:j,checkpointIndexByKey:J,attemptMetaById:re,userMessageIdToAttempts:ie}=Bb(_),ce=G??[],Xe=b.useRef(null),Ie=b.useRef(null),at=b.useCallback(()=>{Xe.current&&(Xe.current.value=""),Ie.current&&(Ie.current.value=""),Ke(he=>he+1),Qe(he=>he+1)},[]),ht=b.useCallback(he=>{pt(he)},[pt]),Kt=b.useRef(!1);b.useEffect(()=>{Kt.current&&!P&&(Ve([]),at()),Kt.current=P},[P,at]);const[Hn,Ar]=b.useState("desktop");b.useEffect(()=>{const he=()=>{const be=window.innerWidth;Ar(be<640?"phone":be<1024?"tablet":"desktop")};return he(),window.addEventListener("resize",he),()=>window.removeEventListener("resize",he)},[]),b.useEffect(()=>{nn.current=!1},[R]),b.useEffect(()=>{tt.current=Le},[Le]),b.useEffect(()=>{if(!Y){We.current=null;return}We.current===null&&(We.current=tt.current),pt(de??"")},[de,Y,pt]),b.useEffect(()=>{(async()=>{if(!y.baseUrl){zt(null);return}try{const Ee=(await y.getAgent("default")).uiDefaultMessage||"";zt(Ee||null)}catch(be){console.warn("Failed to fetch default message:",be),zt(null)}})()},[y.baseUrl]),b.useEffect(()=>{M&&!it&&(m==null||m(M))},[M,it,m]);const Nr=he=>{if(he.length>us)return`Message too long (${he.length}/${us} characters)`;try{return Hb(he),null}catch(be){return(be==null?void 0:be.message)||"Invalid message"}},po=async he=>{const be=he.trim();if(!(!be&&Pe.length===0)){if(be){const Ee=Nr(be);if(Ee){me(Ee);return}}try{const Ee=Y?(_e==null?void 0:_e.checkpointId)??z??void 0:z??void 0,Ue=Y?(_e==null?void 0:_e.checkpointNs)??X??void 0:X??void 0;await F({text:be||"",attachments:Pe},{checkpointId:Ee,checkpointNs:Ue,edit:!!Y,originalMessageId:Y??void 0}),h==null||h(be),pt(""),me(null),Ve([]),at(),Q(null),oe(""),ze(null)}catch(Ee){const Ue=(Ee==null?void 0:Ee.message)||"Failed to send message";me(Ue),m==null||m(Ue)}}},Nn=b.useCallback((he,be,Ee)=>{c&&(We.current=Le,Q(he),oe(be),pt(be),me(null),ze({checkpointId:(Ee==null?void 0:Ee.checkpointId)??null,checkpointNs:(Ee==null?void 0:Ee.checkpointNs)??null}))},[Le,c,pt]),I=b.useCallback(()=>{Q(null),oe(""),ze(null),me(null),pt(We.current??Le),We.current=null},[Le,pt]),W=b.useCallback((he,be,Ee)=>{Nn(he,be,Ee)},[Nn]),ae=b.useCallback(he=>{let be=null;for(let rn=he-1;rn>=0;rn--)if(S[rn].role==="user"){be=S[rn];break}if(!be)return;const Ee=Array.isArray(be.content)?be.content:[],Wn=Ee.filter(rn=>(rn==null?void 0:rn.type)==="text").map(rn=>rn.text).join("")||(()=>{try{return JSON.stringify(Ee,null,2)}catch{return String(Ee)}})();Wn&&F({text:Wn},{checkpointId:z??void 0,checkpointNs:X??void 0,edit:!0,originalMessageId:be.id})},[S,F,z,X]),we=he=>{const be=Array.from(he.target.files||[]);Ve(Ee=>[...Ee,...be]),he.target.value=""},Be=he=>{Ve(be=>{const Ee=be.filter((Ue,Wn)=>he!==Wn);return Ee.length===0&&at(),Ee})},nt=async he=>{const be=(he.target.files||[])[0];if(be){Mt(null),Ct(null),et(!0);try{await F({attachments:[be]},{checkpointId:z??void 0,checkpointNs:X??void 0});const Ee=`Uploaded ${be.name} - processing through chat stream`;Ct(Ee)}catch(Ee){const Ue=Ee instanceof Error?Ee.message:"Failed to upload Excel file";console.error("Excel upload failed",Ee),Mt(Ue),m==null||m(Ue)}finally{et(!1),he.target.value="",at()}}},De=async he=>{if(x){Ye(!0);try{if(!he){await E(),requestAnimationFrame(()=>{var Ue;(Ue=H.current)==null||Ue.scrollToLatest()});return}const be=_.find(Ue=>Ue.checkpointId===he),Ee=(be==null?void 0:be.checkpointNs)??null;await T(he,Ee),requestAnimationFrame(()=>{var Ue;(Ue=H.current)==null||Ue.scrollToTop()})}finally{Ye(!1)}}},Oe=b.useCallback(async(he,be,Ee)=>{await De(Ee?null:he)},[De]),It=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${p.container||""}`,mt=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${p.messagesArea||""}`,xt=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${p.inputArea||""}`;return u.jsxs("div",{className:It,children:[!!M&&!it&&u.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[u.jsx("span",{children:M}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>St(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(le.X,{size:16})})]}),u.jsxs("div",{className:`relative ${mt}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(ja,{ref:H,className:"h-full",style:{height:"100%"},messages:S,isStreaming:P,streamingAssistantId:ne,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Hn,enableMessageEditing:c,editingMessageId:Y,onEdit:W,onRegenerate:ae,onCancelEdit:I,emptyMessage:Pt??void 0,isNavigatingCheckpoint:Rt,activeInterrupt:ye,disableInterruptActions:Te,onInterruptActionStart:U,onInterruptActionEnd:Z,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:j,checkpointIndexByKey:J,attemptMetaById:re,userMessageIdToAttempts:ie,activeCheckpointId:z,onSelectCheckpoint:Oe,timelineCheckpoints:ce,messagePreviews:V}),(A==="reconnecting"||A==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(le.Loader2,{className:"h-3 w-3 animate-spin"}),A==="reconnecting"?"Reconnecting…":"Connecting…"]})}),A==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),C&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(le.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||Rt)&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(le.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]})]}),u.jsxs("div",{className:xt,children:[Y&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(le.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:I,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(le.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Xe,type:"file",multiple:!0,onChange:he=>we(he),className:"hidden"},ut),Pe.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:Pe.map((he,be)=>u.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[u.jsx(le.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:he.name}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>Be(be),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${he.name}`,children:u.jsx(le.X,{size:12})})]},be))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Ie,type:"file",accept:".xls,.xlsx,.xlsm",onChange:nt,className:"hidden"},qe),Ge&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(le.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),gt&&!Ge&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:gt}),st&&!Ge&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:st})]})]}),se&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:se}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(Eb,{children:[u.jsx(Ib,{asChild:!0,children:u.jsx(Je,{type:"button",size:"icon",variant:"outline",disabled:P||$,title:"More input actions",className:p.moreButton||"",children:u.jsx(le.Plus,{size:16})})}),u.jsxs(Td,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Zi,{onClick:()=>{var he;return(he=Xe.current)==null?void 0:he.click()},className:"cursor-pointer",children:[u.jsx(le.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Zi,{onClick:()=>{var he;Ge||(he=Ie.current)==null||he.click()},className:`cursor-pointer ${Ge?"opacity-60 pointer-events-none":""}`,children:[u.jsx(le.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(Ix,{initialValue:de,editingMessageId:Y,value:Le,onValueChange:ht,placeholder:Y?"Edit your message...":t,isStreaming:P,disabled:$,maxLength:us,onSend:po,onCancelEdit:I,onStop:L,allowEmptySend:Pe.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${Y?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${se?"border-red-400":""} ${p.textarea||""}`})})]})]})]})}const Fs=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:te("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground 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 md:text-sm",e),ref:r,...n}));Fs.displayName="Input";function Ma(e,[t,n]){return Math.min(n,Math.max(t,e))}function SC(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Pa="ScrollArea",[wp,pk]=Tn(Pa),[CC,en]=wp(Pa),bp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=v.useState(null),[c,d]=v.useState(null),[f,p]=v.useState(null),[h,g]=v.useState(null),[m,y]=v.useState(null),[x,w]=v.useState(0),[S,k]=v.useState(0),[C,T]=v.useState(!1),[E,N]=v.useState(!1),_=$e(t,B=>l(B)),D=Ro(o);return u.jsx(CC,{scope:n,type:r,dir:D,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:p,scrollbarX:h,onScrollbarXChange:g,scrollbarXEnabled:C,onScrollbarXEnabledChange:T,scrollbarY:m,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:N,onCornerWidthChange:w,onCornerHeightChange:k,children:u.jsx(Ne.div,{dir:D,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});bp.displayName=Pa;var Sp="ScrollAreaViewport",Cp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=en(Sp,n),a=v.useRef(null),l=$e(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),u.jsx(Ne.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Cp.displayName=Sp;var bn="ScrollAreaScrollbar",Ra=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(bn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return v.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(TC,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(kC,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(Tp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Oa,{...r,ref:t}):null});Ra.displayName=bn;var TC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(bn,e.__scopeScrollArea),[s,i]=v.useState(!1);return v.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Xt,{present:n||s,children:u.jsx(Tp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),kC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(bn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Hs(()=>l("SCROLL_END"),100),[a,l]=SC("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),v.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const p=()=>{const h=c[d];f!==h&&(l("SCROLL"),i()),f=h};return c.addEventListener("scroll",p),()=>c.removeEventListener("scroll",p)}},[o.viewport,s,l,i]),u.jsx(Xt,{present:n||a!=="hidden",children:u.jsx(Oa,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:pe(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:pe(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Tp=v.forwardRef((e,t)=>{const n=en(bn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=v.useState(!1),a=e.orientation==="horizontal",l=Hs(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return kr(n.viewport,l),kr(n.content,l),u.jsx(Xt,{present:r||s,children:u.jsx(Oa,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Oa=v.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=en(bn,e.__scopeScrollArea),s=v.useRef(null),i=v.useRef(0),[a,l]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Np(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:p=>s.current=p,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:p=>i.current=p};function f(p,h){return jC(p,i.current,a,h)}return n==="horizontal"?u.jsx(EC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollLeft,h=_p(p,a,o.dir);s.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=f(p,o.dir))}}):n==="vertical"?u.jsx(IC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollTop,h=_p(p,a);s.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=f(p))}}):null}),EC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=en(bn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=$e(t,l,s.onScrollbarXChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Ep,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Us(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(p),Mp(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:zs(i.paddingLeft),paddingEnd:zs(i.paddingRight)}})}})}),IC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=en(bn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=$e(t,l,s.onScrollbarYChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Ep,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Us(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(p),Mp(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:zs(i.paddingTop),paddingEnd:zs(i.paddingBottom)}})}})}),[AC,kp]=wp(bn),Ep=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...p}=e,h=en(bn,n),[g,m]=v.useState(null),y=$e(t,_=>m(_)),x=v.useRef(null),w=v.useRef(""),S=h.viewport,k=r.content-r.viewport,C=Et(d),T=Et(l),E=Hs(f,10);function N(_){if(x.current){const D=_.clientX-x.current.left,B=_.clientY-x.current.top;c({x:D,y:B})}}return v.useEffect(()=>{const _=D=>{const B=D.target;(g==null?void 0:g.contains(B))&&C(D,k)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[S,g,k,C]),v.useEffect(T,[r,T]),kr(g,E),kr(h.content,E),u.jsx(AC,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:Et(s),onThumbPointerUp:Et(i),onThumbPositionChange:T,onThumbPointerDown:Et(a),children:u.jsx(Ne.div,{...p,ref:y,style:{position:"absolute",...p.style},onPointerDown:pe(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),x.current=g.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),N(_))}),onPointerMove:pe(e.onPointerMove,N),onPointerUp:pe(e.onPointerUp,_=>{const D=_.target;D.hasPointerCapture(_.pointerId)&&D.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=w.current,h.viewport&&(h.viewport.style.scrollBehavior=""),x.current=null})})})}),Bs="ScrollAreaThumb",Ip=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=kp(Bs,e.__scopeScrollArea);return u.jsx(Xt,{present:n||o.hasThumb,children:u.jsx(NC,{ref:t,...r})})}),NC=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=en(Bs,n),i=kp(Bs,n),{onThumbPositionChange:a}=i,l=$e(t,f=>i.onThumbChange(f)),c=v.useRef(void 0),d=Hs(()=>{c.current&&(c.current(),c.current=void 0)},100);return v.useEffect(()=>{const f=s.viewport;if(f){const p=()=>{if(d(),!c.current){const h=MC(f,a);c.current=h,a()}};return a(),f.addEventListener("scroll",p),()=>f.removeEventListener("scroll",p)}},[s.viewport,d,a]),u.jsx(Ne.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:pe(e.onPointerDownCapture,f=>{const h=f.target.getBoundingClientRect(),g=f.clientX-h.left,m=f.clientY-h.top;i.onThumbPointerDown({x:g,y:m})}),onPointerUp:pe(e.onPointerUp,i.onThumbPointerUp)})});Ip.displayName=Bs;var Da="ScrollAreaCorner",Ap=v.forwardRef((e,t)=>{const n=en(Da,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(_C,{...e,ref:t}):null});Ap.displayName=Da;var _C=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=en(Da,n),[s,i]=v.useState(0),[a,l]=v.useState(0),c=!!(s&&a);return kr(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),kr(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(Ne.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function zs(e){return e?parseInt(e,10):0}function Np(e,t){const n=e/t;return isNaN(n)?0:n}function Us(e){const t=Np(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function jC(e,t,n,r="ltr"){const o=Us(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return jp([l,c],f)(e)}function _p(e,t,n="ltr"){const r=Us(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],c=Ma(e,l);return jp([0,i],[0,a])(c)}function jp(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Mp(e,t){return e>0&&e<t}var MC=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function Hs(e,t){const n=Et(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function kr(e,t){const n=Et(t);kt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Pp=bp,PC=Cp,RC=Ap;const Rp=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Pp,{ref:r,className:te("relative overflow-hidden",e),...n,children:[u.jsx(PC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Op,{}),u.jsx(RC,{})]}));Rp.displayName=Pp.displayName;const Op=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Ra,{ref:r,orientation:t,className:te("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(Ip,{className:"relative flex-1 rounded-full bg-border"})}));Op.displayName=Ra.displayName;const Dp=25;function La({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,currentThreadId:p,setCurrentThreadId:h,isLoading:g,actions:m}=jo(),{loadThread:y}=Mo(),{createThread:x,deleteThread:w,renameThread:S}=m,[k,C]=b.useState(Array.isArray(f)?f:[]),T=b.useRef(k.length>0),E=b.useRef(null),N=b.useRef(0),[_,D]=b.useState(null),[B,G]=b.useState(""),[V,P]=b.useState(!1);b.useEffect(()=>{const q=Array.isArray(f)?f:[];if(q.length>0){T.current=!0,C(q);return}g||(T.current=!1,C(q))},[f,g]),b.useEffect(()=>{if(!E.current)return;const q=E.current.querySelector("[data-radix-scroll-area-viewport]");if(!q)return;let U=null,Z=null;return U=requestAnimationFrame(()=>{Z=requestAnimationFrame(()=>{q.scrollTop=N.current})}),()=>{U!==null&&cancelAnimationFrame(U),Z!==null&&cancelAnimationFrame(Z)}},[k]);const M=async q=>{try{h(q),await y(q,void 0,{clearProgress:!0}),a==null||a(q),l==null||l(q)}catch(U){console.error("Failed to select thread:",U)}},A=async()=>{try{P(!0);const q=await x();q&&(c==null||c(q),a==null||a(q))}catch(q){console.error("Failed to create thread:",q)}finally{P(!1)}},F=async(q,U)=>{if(U.stopPropagation(),!!confirm("Delete this thread?")){if(E.current){const Z=E.current.querySelector("[data-radix-scroll-area-viewport]");Z&&(N.current=Z.scrollTop)}try{await w(q),d==null||d(q)}catch(Z){console.error("Failed to delete thread:",Z)}}},L=(q,U)=>{U.stopPropagation(),D(q.threadId),G(q.title||`Thread ${q.threadId.slice(0,8)}`)},R=async q=>{if(B.trim())try{await S(q,B.trim()),D(null),G("")}catch(U){console.error("Failed to update title:",U)}},z=()=>{D(null),G("")},X=(q,U)=>{q.key==="Enter"?R(U):q.key==="Escape"&&z()},ne=q=>{if(!q)return"";try{const U=new Date(q),$=new Date().getTime()-U.getTime(),Y=Math.floor($/(1e3*60*60*24));return Y===0?U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):Y===1?"Yesterday":Y<7?`${Y} days ago`:U.toLocaleDateString()}catch{return""}},ye=q=>q.title||`Thread ${q.threadId.slice(0,8)}`,Te=q=>{const U=ye(q);return U.length<=Dp?U:`${U.slice(0,Dp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:u.jsx(Je,{onClick:A,disabled:V||g,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:V?"Creating...":"New Chat",children:u.jsx(le.MessageSquarePlus,{size:20})})}),u.jsx(Rp,{ref:E,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:g?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(le.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):k.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(le.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):k.slice().sort((q,U)=>new Date(U.updatedAt||U.createdAt||"").getTime()-new Date(q.updatedAt||q.createdAt||"").getTime()).map(q=>u.jsxs("div",{onClick:()=>M(q.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??p)===q.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:_===q.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:U=>U.stopPropagation(),children:[u.jsx(Fs,{value:B,onChange:U=>G(U.target.value),onKeyDown:U=>X(U,q.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>R(q.threadId),className:"h-6 w-6 p-0",children:u.jsx(le.Check,{size:12})}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:z,className:"h-6 w-6 p-0",children:u.jsx(le.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:Te(q)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(le.Calendar,{size:10}),u.jsx("span",{children:ne(q.updatedAt||q.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&_!==q.threadId&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:U=>L(q,U),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(le.Edit3,{size:12})}),n&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:U=>F(q.threadId,U),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(le.Trash2,{size:12})})]})]}),i===q.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},q.threadId))})})]})}const OC=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r,className:o,onHoverStart:s,onHoverEnd:i})=>{const a=e??[],l=a.length>0,c=b.useMemo(()=>l?[...a].reverse():[],[a,l]),d=t??(a.length?a[a.length-1].id:null);if(!l)return null;const p=["w-32 flex-shrink-0 flex-col border-r border-border/40 pr-2 flex bg-white text-gray-900 dark:bg-slate-900 dark:text-slate-100",o].filter(Boolean).join(" ");return u.jsxs("div",{className:p,onMouseEnter:s,onMouseLeave:i,children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-4 pb-2 pr-1",children:[u.jsx("div",{className:"absolute left-0 right-0 top-1 px-2 pb-3 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:u.jsx("span",{children:"Timeline"})}),u.jsx("div",{className:"pointer-events-none absolute left-3 top-0 bottom-0 w-px bg-border/40"}),u.jsx("div",{className:"flex flex-col gap-3 pt-6 pr-2",children:c.map(h=>{const g=d===h.id,m=(r==null?void 0:r.get(h.id))??null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(h.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${g?"text-primary":"text-muted-foreground"} ${n?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-3 w-3 items-center justify-center rounded-full border ${g?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${g?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:h.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[h.step!==null?`STEP ${h.step}`:"STEP —",h.next?` - ${h.next}`:""]}),m&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:m,children:m})]})]},h.id)})})]}),n&&u.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(null),className:"mt-auto mb-3 rounded-md border border-border/70 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]})};function Er(e){if(!(typeof globalThis>"u"))return globalThis[e]}function DC(e){if(typeof e!="string")return;const t=e.trim();if(t)return Cn(t)}function Lp(){const e=[Er("__API_BASE_URL__"),Er("__CHAT_API_BASE_URL__"),Er("__CHAT_API_URL__")];for(const t of e){const n=DC(t);if(n)return n}}function $p(){const e=[Er("__API_AUTH_TOKEN__"),Er("__CHAT_API_KEY__"),Er("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function Fp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Cn(t);return Cn()}function Bp(){const e={},t=Lp(),n=$p();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function zp(){const e=Bp(),t=_n.getAuthToken(),n=Lp();return{apiBaseUrl:Fp(e.baseUrl,_n.baseUrl,n),apiKey:t||e.apiKey||$p()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Up="chat-settings";function LC(){try{const e=localStorage.getItem(Up);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function $C(e){try{const t={...e,apiBaseUrl:Cn(e.apiBaseUrl)};localStorage.setItem(Up,JSON.stringify(t)),t.apiKey&&_n.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function FC(){const e=zp(),t=LC(),n=_n.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:Fp(_n.baseUrl,r,e.apiBaseUrl)}}function BC(e){_n.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),$C(e)}var zC="Label",Hp=v.forwardRef((e,t)=>u.jsx(Ne.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Hp.displayName=zC;var Wp=Hp;const UC=ho.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),tn=v.forwardRef(({className:e,...t},n)=>u.jsx(Wp,{ref:n,className:te(UC(),e),...t}));tn.displayName=Wp.displayName;function Vp(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Kp=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),HC="VisuallyHidden",WC=v.forwardRef((e,t)=>u.jsx(Ne.span,{...e,ref:t,style:{...Kp,...e.style}}));WC.displayName=HC;var VC=[" ","Enter","ArrowUp","ArrowDown"],KC=[" ","Enter"],sr="Select",[Ws,Vs,qC]=xi(sr),[Ir,hk]=Tn(sr,[qC,qo]),Ks=qo(),[GC,Bn]=Ir(sr),[YC,XC]=Ir(sr),qp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:p,required:h,form:g}=e,m=Ks(t),[y,x]=v.useState(null),[w,S]=v.useState(null),[k,C]=v.useState(!1),T=Ro(c),[E,N]=pr({prop:r,defaultProp:o??!1,onChange:s,caller:sr}),[_,D]=pr({prop:i,defaultProp:a,onChange:l,caller:sr}),B=v.useRef(null),G=y?g||!!y.closest("form"):!0,[V,P]=v.useState(new Set),M=Array.from(V).map(A=>A.props.value).join(";");return u.jsx(au,{...m,children:u.jsxs(GC,{required:h,scope:t,trigger:y,onTriggerChange:x,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:k,onValueNodeHasChildrenChange:C,contentId:kn(),value:_,onValueChange:D,open:E,onOpenChange:N,dir:T,triggerPointerDownPosRef:B,disabled:p,children:[u.jsx(Ws.Provider,{scope:t,children:u.jsx(YC,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(A=>{P(F=>new Set(F).add(A))},[]),onNativeOptionRemove:v.useCallback(A=>{P(F=>{const L=new Set(F);return L.delete(A),L})},[]),children:n})}),G?u.jsxs(xh,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:A=>D(A.target.value),disabled:p,form:g,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(V)]},M):null]})})};qp.displayName=sr;var Gp="SelectTrigger",Yp=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Ks(n),i=Bn(Gp,n),a=i.disabled||r,l=$e(t,i.onTriggerChange),c=Vs(n),d=v.useRef("touch"),[f,p,h]=vh(m=>{const y=c().filter(S=>!S.disabled),x=y.find(S=>S.value===i.value),w=wh(y,m,x);w!==void 0&&i.onValueChange(w.value)}),g=m=>{a||(i.onOpenChange(!0),h()),m&&(i.triggerPointerDownPosRef.current={x:Math.round(m.pageX),y:Math.round(m.pageY)})};return u.jsx(lu,{asChild:!0,...s,children:u.jsx(Ne.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":yh(i.value)?"":void 0,...o,ref:l,onClick:pe(o.onClick,m=>{m.currentTarget.focus(),d.current!=="mouse"&&g(m)}),onPointerDown:pe(o.onPointerDown,m=>{d.current=m.pointerType;const y=m.target;y.hasPointerCapture(m.pointerId)&&y.releasePointerCapture(m.pointerId),m.button===0&&m.ctrlKey===!1&&m.pointerType==="mouse"&&(g(m),m.preventDefault())}),onKeyDown:pe(o.onKeyDown,m=>{const y=f.current!=="";!(m.ctrlKey||m.altKey||m.metaKey)&&m.key.length===1&&p(m.key),!(y&&m.key===" ")&&VC.includes(m.key)&&(g(),m.preventDefault())})})})});Yp.displayName=Gp;var Xp="SelectValue",Jp=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Bn(Xp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=$e(t,l.onValueNodeChange);return kt(()=>{c(d)},[c,d]),u.jsx(Ne.span,{...a,ref:f,style:{pointerEvents:"none"},children:yh(l.value)?u.jsx(u.Fragment,{children:i}):s})});Jp.displayName=Xp;var JC="SelectIcon",Zp=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(Ne.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Zp.displayName=JC;var ZC="SelectPortal",Qp=e=>u.jsx(Go,{asChild:!0,...e});Qp.displayName=ZC;var ir="SelectContent",eh=v.forwardRef((e,t)=>{const n=Bn(ir,e.__scopeSelect),[r,o]=v.useState();if(kt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?mo.createPortal(u.jsx(th,{scope:e.__scopeSelect,children:u.jsx(Ws.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(nh,{...e,ref:t})});eh.displayName=ir;var dn=10,[th,zn]=Ir(ir),QC="SelectContentImpl",eT=Vn.createSlot("SelectContent.RemoveScroll"),nh=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:y,...x}=e,w=Bn(ir,n),[S,k]=v.useState(null),[C,T]=v.useState(null),E=$e(t,Z=>k(Z)),[N,_]=v.useState(null),[D,B]=v.useState(null),G=Vs(n),[V,P]=v.useState(!1),M=v.useRef(!1);v.useEffect(()=>{if(S)return Fi(S)},[S]),wi();const A=v.useCallback(Z=>{const[$,...Y]=G().map(oe=>oe.ref.current),[Q]=Y.slice(-1),de=document.activeElement;for(const oe of Z)if(oe===de||(oe==null||oe.scrollIntoView({block:"nearest"}),oe===$&&C&&(C.scrollTop=0),oe===Q&&C&&(C.scrollTop=C.scrollHeight),oe==null||oe.focus(),document.activeElement!==de))return},[G,C]),F=v.useCallback(()=>A([N,S]),[A,N,S]);v.useEffect(()=>{V&&F()},[V,F]);const{onOpenChange:L,triggerPointerDownPosRef:R}=w;v.useEffect(()=>{if(S){let Z={x:0,y:0};const $=Q=>{var de,oe;Z={x:Math.abs(Math.round(Q.pageX)-(((de=R.current)==null?void 0:de.x)??0)),y:Math.abs(Math.round(Q.pageY)-(((oe=R.current)==null?void 0:oe.y)??0))}},Y=Q=>{Z.x<=10&&Z.y<=10?Q.preventDefault():S.contains(Q.target)||L(!1),document.removeEventListener("pointermove",$),R.current=null};return R.current!==null&&(document.addEventListener("pointermove",$),document.addEventListener("pointerup",Y,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",Y,{capture:!0})}}},[S,L,R]),v.useEffect(()=>{const Z=()=>L(!1);return window.addEventListener("blur",Z),window.addEventListener("resize",Z),()=>{window.removeEventListener("blur",Z),window.removeEventListener("resize",Z)}},[L]);const[z,X]=vh(Z=>{const $=G().filter(de=>!de.disabled),Y=$.find(de=>de.ref.current===document.activeElement),Q=wh($,Z,Y);Q&&setTimeout(()=>Q.ref.current.focus())}),ne=v.useCallback((Z,$,Y)=>{const Q=!M.current&&!Y;(w.value!==void 0&&w.value===$||Q)&&(_(Z),Q&&(M.current=!0))},[w.value]),ye=v.useCallback(()=>S==null?void 0:S.focus(),[S]),Te=v.useCallback((Z,$,Y)=>{const Q=!M.current&&!Y;(w.value!==void 0&&w.value===$||Q)&&B(Z)},[w.value]),q=r==="popper"?$a:rh,U=q===$a?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:y}:{};return u.jsx(th,{scope:n,content:S,viewport:C,onViewportChange:T,itemRefCallback:ne,selectedItem:N,onItemLeave:ye,itemTextRefCallback:Te,focusSelectedItem:F,selectedItemText:D,position:r,isPositioned:V,searchRef:z,children:u.jsx(rs,{as:eT,allowPinchZoom:!0,children:u.jsx(Do,{asChild:!0,trapped:w.open,onMountAutoFocus:Z=>{Z.preventDefault()},onUnmountAutoFocus:pe(o,Z=>{var $;($=w.trigger)==null||$.focus({preventScroll:!0}),Z.preventDefault()}),children:u.jsx(Oo,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:Z=>Z.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:u.jsx(q,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:Z=>Z.preventDefault(),...x,...U,onPlaced:()=>P(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:pe(x.onKeyDown,Z=>{const $=Z.ctrlKey||Z.altKey||Z.metaKey;if(Z.key==="Tab"&&Z.preventDefault(),!$&&Z.key.length===1&&X(Z.key),["ArrowUp","ArrowDown","Home","End"].includes(Z.key)){let Q=G().filter(de=>!de.disabled).map(de=>de.ref.current);if(["ArrowUp","End"].includes(Z.key)&&(Q=Q.slice().reverse()),["ArrowUp","ArrowDown"].includes(Z.key)){const de=Z.target,oe=Q.indexOf(de);Q=Q.slice(oe+1)}setTimeout(()=>A(Q)),Z.preventDefault()}})})})})})})});nh.displayName=QC;var tT="SelectItemAlignedPosition",rh=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Bn(ir,n),i=zn(ir,n),[a,l]=v.useState(null),[c,d]=v.useState(null),f=$e(t,E=>d(E)),p=Vs(n),h=v.useRef(!1),g=v.useRef(!0),{viewport:m,selectedItem:y,selectedItemText:x,focusSelectedItem:w}=i,S=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&m&&y&&x){const E=s.trigger.getBoundingClientRect(),N=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),D=x.getBoundingClientRect();if(s.dir!=="rtl"){const de=D.left-N.left,oe=_.left-de,_e=E.left-oe,ze=E.width+_e,se=Math.max(ze,N.width),me=window.innerWidth-dn,Pe=Ma(oe,[dn,Math.max(dn,me-se)]);a.style.minWidth=ze+"px",a.style.left=Pe+"px"}else{const de=N.right-D.right,oe=window.innerWidth-_.right-de,_e=window.innerWidth-E.right-oe,ze=E.width+_e,se=Math.max(ze,N.width),me=window.innerWidth-dn,Pe=Ma(oe,[dn,Math.max(dn,me-se)]);a.style.minWidth=ze+"px",a.style.right=Pe+"px"}const B=p(),G=window.innerHeight-dn*2,V=m.scrollHeight,P=window.getComputedStyle(c),M=parseInt(P.borderTopWidth,10),A=parseInt(P.paddingTop,10),F=parseInt(P.borderBottomWidth,10),L=parseInt(P.paddingBottom,10),R=M+A+V+L+F,z=Math.min(y.offsetHeight*5,R),X=window.getComputedStyle(m),ne=parseInt(X.paddingTop,10),ye=parseInt(X.paddingBottom,10),Te=E.top+E.height/2-dn,q=G-Te,U=y.offsetHeight/2,Z=y.offsetTop+U,$=M+A+Z,Y=R-$;if($<=Te){const de=B.length>0&&y===B[B.length-1].ref.current;a.style.bottom="0px";const oe=c.clientHeight-m.offsetTop-m.offsetHeight,_e=Math.max(q,U+(de?ye:0)+oe+F),ze=$+_e;a.style.height=ze+"px"}else{const de=B.length>0&&y===B[0].ref.current;a.style.top="0px";const _e=Math.max(Te,M+m.offsetTop+(de?ne:0)+U)+Y;a.style.height=_e+"px",m.scrollTop=$-Te+m.offsetTop}a.style.margin=`${dn}px 0`,a.style.minHeight=z+"px",a.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[p,s.trigger,s.valueNode,a,c,m,y,x,s.dir,r]);kt(()=>S(),[S]);const[k,C]=v.useState();kt(()=>{c&&C(window.getComputedStyle(c).zIndex)},[c]);const T=v.useCallback(E=>{E&&g.current===!0&&(S(),w==null||w(),g.current=!1)},[S,w]);return u.jsx(rT,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:h,onScrollButtonChange:T,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(Ne.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});rh.displayName=tT;var nT="SelectPopperPosition",$a=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=dn,...s}=e,i=Ks(n);return u.jsx(cu,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});$a.displayName=nT;var[rT,Fa]=Ir(ir,{}),Ba="SelectViewport",oh=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=zn(Ba,n),i=Fa(Ba,n),a=$e(t,s.onViewportChange),l=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx(Ws.Slot,{scope:n,children:u.jsx(Ne.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:pe(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&f){const h=Math.abs(l.current-d.scrollTop);if(h>0){const g=window.innerHeight-dn*2,m=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),x=Math.max(m,y);if(x<g){const w=x+h,S=Math.min(g,w),k=w-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});oh.displayName=Ba;var sh="SelectGroup",[oT,sT]=Ir(sh),iT=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=kn();return u.jsx(oT,{scope:n,id:o,children:u.jsx(Ne.div,{role:"group","aria-labelledby":o,...r,ref:t})})});iT.displayName=sh;var ih="SelectLabel",ah=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=sT(ih,n);return u.jsx(Ne.div,{id:o.id,...r,ref:t})});ah.displayName=ih;var qs="SelectItem",[aT,lh]=Ir(qs),ch=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Bn(qs,n),l=zn(qs,n),c=a.value===r,[d,f]=v.useState(s??""),[p,h]=v.useState(!1),g=$e(t,w=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,w,r,o)}),m=kn(),y=v.useRef("touch"),x=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(aT,{scope:n,value:r,disabled:o,textId:m,isSelected:c,onItemTextChange:v.useCallback(w=>{f(S=>S||((w==null?void 0:w.textContent)??"").trim())},[]),children:u.jsx(Ws.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(Ne.div,{role:"option","aria-labelledby":m,"data-highlighted":p?"":void 0,"aria-selected":c&&p,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:g,onFocus:pe(i.onFocus,()=>h(!0)),onBlur:pe(i.onBlur,()=>h(!1)),onClick:pe(i.onClick,()=>{y.current!=="mouse"&&x()}),onPointerUp:pe(i.onPointerUp,()=>{y.current==="mouse"&&x()}),onPointerDown:pe(i.onPointerDown,w=>{y.current=w.pointerType}),onPointerMove:pe(i.onPointerMove,w=>{var S;y.current=w.pointerType,o?(S=l.onItemLeave)==null||S.call(l):y.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:pe(i.onPointerLeave,w=>{var S;w.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:pe(i.onKeyDown,w=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&w.key===" "||(KC.includes(w.key)&&x(),w.key===" "&&w.preventDefault())})})})})});ch.displayName=qs;var fo="SelectItemText",uh=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Bn(fo,n),a=zn(fo,n),l=lh(fo,n),c=XC(fo,n),[d,f]=v.useState(null),p=$e(t,x=>f(x),l.onItemTextChange,x=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,x,l.value,l.disabled)}),h=d==null?void 0:d.textContent,g=v.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:m,onNativeOptionRemove:y}=c;return kt(()=>(m(g),()=>y(g)),[m,y,g]),u.jsxs(u.Fragment,{children:[u.jsx(Ne.span,{id:l.textId,...s,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?mo.createPortal(s.children,i.valueNode):null]})});uh.displayName=fo;var dh="SelectItemIndicator",fh=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return lh(dh,n).isSelected?u.jsx(Ne.span,{"aria-hidden":!0,...r,ref:t}):null});fh.displayName=dh;var za="SelectScrollUpButton",ph=v.forwardRef((e,t)=>{const n=zn(za,e.__scopeSelect),r=Fa(za,e.__scopeSelect),[o,s]=v.useState(!1),i=$e(t,r.onScrollButtonChange);return kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(mh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});ph.displayName=za;var Ua="SelectScrollDownButton",hh=v.forwardRef((e,t)=>{const n=zn(Ua,e.__scopeSelect),r=Fa(Ua,e.__scopeSelect),[o,s]=v.useState(!1),i=$e(t,r.onScrollButtonChange);return kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(mh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});hh.displayName=Ua;var mh=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=zn("SelectScrollButton",n),i=v.useRef(null),a=Vs(n),l=v.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return v.useEffect(()=>()=>l(),[l]),kt(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(Ne.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:pe(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:pe(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:pe(o.onPointerLeave,()=>{l()})})}),lT="SelectSeparator",gh=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Ne.div,{"aria-hidden":!0,...r,ref:t})});gh.displayName=lT;var Ha="SelectArrow",cT=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ks(n),s=Bn(Ha,n),i=zn(Ha,n);return s.open&&i.position==="popper"?u.jsx(uu,{...o,...r,ref:t}):null});cT.displayName=Ha;var uT="SelectBubbleInput",xh=v.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=v.useRef(null),s=$e(r,o),i=Vp(t);return v.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(Ne.select,{...n,style:{...Kp,...n.style},ref:s,defaultValue:t})});xh.displayName=uT;function yh(e){return e===""||e===void 0}function vh(e){const t=Et(e),n=v.useRef(""),r=v.useRef(0),o=v.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function wh(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=dT(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function dT(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var fT=qp,bh=Yp,pT=Jp,hT=Zp,mT=Qp,Sh=eh,gT=oh,Ch=ah,Th=ch,xT=uh,yT=fh,kh=ph,Eh=hh,Ih=gh;const Ah=fT,Nh=pT,Wa=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(bh,{ref:r,className:te("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(hT,{asChild:!0,children:u.jsx(le.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Wa.displayName=bh.displayName;const _h=v.forwardRef(({className:e,...t},n)=>u.jsx(kh,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(le.ChevronUp,{className:"h-4 w-4"})}));_h.displayName=kh.displayName;const jh=v.forwardRef(({className:e,...t},n)=>u.jsx(Eh,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(le.ChevronDown,{className:"h-4 w-4"})}));jh.displayName=Eh.displayName;const Va=v.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(mT,{children:u.jsxs(Sh,{ref:o,className:te("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(_h,{}),u.jsx(gT,{className:te("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(jh,{})]})}));Va.displayName=Sh.displayName;const vT=v.forwardRef(({className:e,...t},n)=>u.jsx(Ch,{ref:n,className:te("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));vT.displayName=Ch.displayName;const ar=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Th,{ref:r,className:te("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(yT,{children:u.jsx(le.Check,{className:"h-4 w-4"})})}),u.jsx(xT,{children:t})]}));ar.displayName=Th.displayName;const wT=v.forwardRef(({className:e,...t},n)=>u.jsx(Ih,{ref:n,className:te("-mx-1 my-1 h-px bg-muted",e),...t}));wT.displayName=Ih.displayName;var bT="Separator",Mh="horizontal",ST=["horizontal","vertical"],Ph=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Mh,...o}=e,s=CT(r)?r:Mh,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(Ne.div,{"data-orientation":s,...a,...o,ref:t})});Ph.displayName=bT;function CT(e){return ST.includes(e)}var Rh=Ph;const Oh=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Rh,{ref:o,decorative:n,orientation:t,className:te("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Oh.displayName=Rh.displayName;const TT=Kf,kT=OS,ET=qf,Dh=v.forwardRef(({className:e,...t},n)=>u.jsx(As,{className:te("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));Dh.displayName=As.displayName;const IT=ho.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Lh=v.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(ET,{children:[u.jsx(Dh,{}),u.jsxs(Ns,{ref:o,className:te(IT({side:e}),t),...r,children:[n,u.jsxs(Gf,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(le.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Lh.displayName=Ns.displayName;const $h=({className:e,...t})=>u.jsx("div",{className:te("flex flex-col space-y-2 text-center sm:text-left",e),...t});$h.displayName="SheetHeader";const Fh=v.forwardRef(({className:e,...t},n)=>u.jsx(rr,{ref:n,className:te("text-lg font-semibold text-foreground",e),...t}));Fh.displayName=rr.displayName;const Bh=v.forwardRef(({className:e,...t},n)=>u.jsx(_s,{ref:n,className:te("text-sm text-muted-foreground",e),...t}));Bh.displayName=_s.displayName;var Gs="Switch",[AT,mk]=Tn(Gs),[NT,_T]=AT(Gs),zh=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[p,h]=v.useState(null),g=$e(t,S=>h(S)),m=v.useRef(!1),y=p?d||!!p.closest("form"):!0,[x,w]=pr({prop:o,defaultProp:s??!1,onChange:c,caller:Gs});return u.jsxs(NT,{scope:n,checked:x,disabled:a,children:[u.jsx(Ne.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":Vh(x),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:g,onClick:pe(e.onClick,S=>{w(k=>!k),y&&(m.current=S.isPropagationStopped(),m.current||S.stopPropagation())})}),y&&u.jsx(Wh,{control:p,bubbles:!m.current,name:r,value:l,checked:x,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});zh.displayName=Gs;var Uh="SwitchThumb",Hh=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_T(Uh,n);return u.jsx(Ne.span,{"data-state":Vh(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Hh.displayName=Uh;var jT="SwitchBubbleInput",Wh=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=v.useRef(null),a=$e(i,s),l=Vp(n),c=Jc(t);return v.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&h){const g=new Event("click",{bubbles:r});h.call(d,n),d.dispatchEvent(g)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Wh.displayName=jT;function Vh(e){return e?"checked":"unchecked"}var Kh=zh,MT=Hh;const Un=v.forwardRef(({className:e,...t},n)=>u.jsx(Kh,{className:te("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(MT,{className:te("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Un.displayName=Kh.displayName;const PT={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function RT({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=b.useState(!1),[s,i]=b.useState(!1),[a,l]=b.useState(e),[c,d]=b.useState(!1),{toast:f}=Aa();b.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),b.useEffect(()=>{l(e)},[e]);const p=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},h=()=>{l(PT),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},g=()=>{l(e),d(!1),o(!1)},m=async()=>{try{const x=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${x.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(TT,{open:r,onOpenChange:o,children:[u.jsx(kT,{asChild:!0,children:u.jsxs(Je,{variant:"outline",size:"sm",className:n,children:[u.jsx(le.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Tf,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(Lh,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs($h,{children:[u.jsx(Fh,{children:"Chat Settings"}),u.jsx(Bh,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(ao,{children:[u.jsx(lo,{className:"pb-3",children:u.jsxs(co,{className:"text-lg flex items-center gap-2",children:[u.jsx(le.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(uo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Fs,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(x=>({...x,api:{...x.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(Je,{variant:"outline",onClick:m,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Un,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(x=>({...x,api:{...x.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Fs,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(x=>({...x,api:{...x.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(Je,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(le.EyeOff,{className:"h-4 w-4"}):u.jsx(le.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(ao,{children:[u.jsx(lo,{className:"pb-3",children:u.jsxs(co,{className:"text-lg flex items-center gap-2",children:[u.jsx(le.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(uo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(Ah,{value:a.ui.layout,onValueChange:y=>l(x=>({...x,ui:{...x.ui,layout:y}})),children:[u.jsx(Wa,{children:u.jsx(Nh,{})}),u.jsxs(Va,{children:[u.jsx(ar,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(ar,{value:"fullscreen",children:"Fullscreen"}),u.jsx(ar,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"theme",children:"Theme"}),u.jsxs(Ah,{value:a.ui.theme,onValueChange:y=>l(x=>({...x,ui:{...x.ui,theme:y}})),children:[u.jsx(Wa,{children:u.jsx(Nh,{})}),u.jsxs(Va,{children:[u.jsx(ar,{value:"light",children:"Light"}),u.jsx(ar,{value:"dark",children:"Dark"}),u.jsx(ar,{value:"system",children:"System"})]})]})]}),u.jsx(Oh,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Un,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Un,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Un,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(ao,{children:[u.jsx(lo,{className:"pb-3",children:u.jsxs(co,{className:"text-lg flex items-center gap-2",children:[u.jsx(le.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(uo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(Un,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(Un,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(Un,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(Je,{variant:"outline",onClick:h,children:[u.jsx(le.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Je,{variant:"outline",onClick:g,children:"Cancel"}),u.jsxs(Je,{onClick:p,disabled:!c,children:[u.jsx(le.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function OT({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=b.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(Po,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx($s,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(Po,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(La,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx($s,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(Po,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(La,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx($s,{onError:s.onError,enableFileUpload:!0})})]})})}Se.ChatApi=Bl,Se.ChatInput=mc,Se.ChatInterface=$s,Se.ChatProviders=Po,Se.ChatSettings=RT,Se.MarkdownContent=io,Se.MessageComponent=Ls,Se.MessageList=ja,Se.ThreadManager=La,Se.TimelineColumn=OC,Se.applySettings=BC,Se.buildMessagePreviewMap=Yg,Se.chatApiClient=_n,Se.default=OT,Se.del=Fl,Se.get=Gt,Se.getChatToken=Dl,Se.getCurrentSettings=FC,Se.getDefaultApiConfig=Bp,Se.getDefaultChatSettings=zp,Se.onChatTokenChanged=Ll,Se.post=ui,Se.put=$l,Se.setChatToken=Io,Se.useApi=di,Se.useChatStream=lc,Se.useMessagesReducer=Ql,Se.useStream=pc,Se.useThreadState=Mo,Se.useThreads=jo,Object.defineProperties(Se,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
137
+ dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[q[J]?u.jsx(le.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[ie,q[J]?" (processing)":""]})]},J)}if(j.type==="interrupt"){const re=j,ie=ks((re==null?void 0:re.id)??(re==null?void 0:re.interrupt_id)),ce=!!(Ve&&ie&&ie===Ve),Xe=ce?ut??(re==null?void 0:re.value):re==null?void 0:re.value,Ie=ie?{...re,id:ie,interrupt_id:ie}:re;return u.jsx(hC,{interruptPart:Ie,onApprove:Ct,onReject:it,disabled:S,isActive:ce,payload:Xe},J)}return null},[U,q,Ct,it,z,c,d,M,R,Ve,ut,w,S,me]),Pt=b.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(le.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),zt=b.useCallback(()=>{const j=de.trim().length>0||ze.length>0||se.length>0||me.length>0;if(!X&&se.length>0&&!r)return Pt();if(!X&&!j&&!r)return null;if(X)return!f&&qe.length>0?null:f?u.jsx(xC,{message:t,viewMode:V,isStreaming:_e},t.id):null;if(!X&&!ne){const J=t,re=u.jsx("div",{className:"space-y-2",children:J.content.map((ie,ce)=>u.jsx(St,{part:ie,i:ce},ce))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[re,u.jsx(wC,{className:Q})]}):re}},[de,ze.length,se.length,me.length,r,X,V,f,qe.length,Pt,Q]),nn=b.useMemo(()=>ne?"Assistant":vS(t),[ne,t]),Le=b.useMemo(()=>ne?[]:Array.isArray(T)?T:[],[T,ne]),Sn=b.useMemo(()=>{var j;return Le.length?_&&Le.some(J=>J.id===_)?_:((j=Le[0])==null?void 0:j.id)??null:null},[_,Le]),We=b.useMemo(()=>!Le.length||!E?null:Le.some(j=>j.id===E)?E:null,[E,Le])??Sn,pt=z==="user"&&Le.length>0&&typeof N=="function",Rt=b.useCallback((j,J=!1)=>{if(!N)return;const re=(j==null?void 0:j.id)??null,ie=(j==null?void 0:j.parentId)??D??null;N(re,ie,J)},[D,N]),Ye=b.useMemo(()=>We?Le.findIndex(j=>j.id===We):-1,[We,Le]),H=b.useMemo(()=>Ye<0?null:Le[Ye]??null,[Ye,Le]);return X&&!f&&qe.length===0?null:ye&&ne?u.jsx("div",{className:te(Mt(),h.container),children:u.jsxs("div",{className:te(gt(),h.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(le.Bot,{className:te("h-4 w-4",Q)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(io,{content:ne.content,className:"text-current"})]})}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:te(Mt(),h.container),children:u.jsxs("div",{className:te(gt(),h.content),children:[(i||a||X)&&u.jsxs("div",{className:te("flex items-center justify-between mb-2 pb-2 border-b border-current/10",R&&"mb-1 pb-1",Q,h.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[st(),a&&nn&&u.jsx("span",{className:te("font-medium",R?"text-xs":"text-sm"),children:nn}),X&&u.jsxs(Tf,{variant:"outline",className:te("text-xs flex items-center gap-1 cursor-pointer select-none",Q,"border border-current/40",R&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":V==="expanded",onClick:()=>P(j=>j==="expanded"?"preview":"expanded"),onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),P(J=>J==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:oe.name??"Tool Output"}),oe.toolCallId&&u.jsx("span",{className:"opacity-70",children:oe.toolCallId.slice(0,8)}),V==="expanded"?u.jsx(le.ChevronUp,{className:"h-3 w-3"}):u.jsx(le.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[pt&&H&&Ye>=0&&u.jsx("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ye<Le.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Ye>=Le.length-1)return;const j=Le[Ye+1];j&&Rt(j)},"aria-label":"Older checkpoint (back in time)",disabled:Ye>=Le.length-1,children:u.jsx(le.ChevronLeft,{className:"h-3 w-3"})}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"whitespace-nowrap",children:[Le.length-Ye," / ",Le.length]})}),u.jsx("button",{type:"button",className:te("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ye>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(!(Ye<=0))if(Ye===1)Rt(null,!0);else{const j=Le[Ye-1];j&&Rt(j,!1)}},"aria-label":"Newer checkpoint (forward in time)",disabled:Ye<=0,children:u.jsx(le.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:te("text-xs opacity-60",Q,R&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:te("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:te("h-6 w-6 p-0 hover:bg-foreground/10",Q,R&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(le.Copy,{className:te(B?"text-success":Q,R?"h-3 w-3":"h-4 w-4")})})}),z==="user"&&g&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:Ge,className:te("h-6 w-6 p-0 hover:bg-foreground/10",Q,R&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(le.Edit,{className:te(Q,R?"h-3 w-3":"h-4 w-4")})}),z==="assistant"&&m&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:et,className:te("h-6 w-6 p-0 hover:bg-foreground/10",Q,R&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(le.RotateCcw,{className:te(Q,R?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[zt(),p&&qe.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:qe.map((j,J)=>u.jsx(pC,{preview:j,idx:J},`artifact-${J}`))})]}),X&&V==="expanded"&&(oe.toolCallId||oe.name)&&u.jsxs("div",{className:te("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",R&&"text-xs"),children:[oe.name&&u.jsxs("div",{children:["Function: ",oe.name]}),oe.toolCallId&&u.jsxs("div",{children:["Call ID: ",oe.toolCallId]})]}),!(i||a||X)&&s&&!o&&u.jsxs("div",{className:te("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",h.actions),children:[u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>Qe(),className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(le.Copy,{className:te(B?"text-success":"text-current",R?"h-3 w-3":"h-4 w-4")})}),z==="user"&&g&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:Ge,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(le.Edit,{className:te("text-current",R?"h-3 w-3":"h-4 w-4")})}),z==="assistant"&&m&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:et,className:te("h-6 w-6 p-0 hover:bg-background/50 text-current",R&&"h-5 w-5"),children:u.jsx(le.RotateCcw,{className:te("text-current",R?"h-3 w-3":"h-4 w-4")})})]})]})}),$&&u.jsx(WS,{isOpen:Z,onClose:Y,fileId:$.id,fileName:$.name,mimeType:$.mimeType})]})},(e,t)=>{var l,c,d,f,p,h,g,m;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&If(e.message)===If(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages","attemptMeta"].every(y=>e[y]===t[y]),s=((l=e.customStyles)==null?void 0:l.container)===((c=t.customStyles)==null?void 0:c.container)&&((d=e.customStyles)==null?void 0:d.content)===((f=t.customStyles)==null?void 0:f.content)&&((p=e.customStyles)==null?void 0:p.actions)===((h=t.customStyles)==null?void 0:h.actions)&&((g=e.customStyles)==null?void 0:g.header)===((m=t.customStyles)==null?void 0:m.header);if(!o||!s)return!1;const i=gp(e.message),a=gp(t.message);return i.length===a.length});Ls.displayName="MessageComponent";function bC(e,t){return b.useMemo(()=>{var d,f,p,h,g;const n=e&&"type"in e&&e.type==="default_message";let r=[],o=null,s={},i={},a=null,l=null,c=null;if(!n&&e){const m=e,y=m.checkpointId??null;s=m.additionalKwargs??{},i=m.responseMetadata??{};const x=y&&t.checkpointMetaById?t.checkpointMetaById.get(y)??null:null;a=typeof s.step=="number"?s.step:typeof i.step=="number"?i.step:(x==null?void 0:x.step)??null;const w=typeof s.source=="string"?s.source:typeof i.source=="string"?i.source:(x==null?void 0:x.source)??null;l=w?String(w):null;const S=a!==null&&l?`${a}:${l}`:null;if(S&&((d=t.checkpointIndexByKey)!=null&&d.has(S))?r=t.checkpointIndexByKey.get(S)??[]:y&&x&&(r=[x]),o=y??((f=r[0])==null?void 0:f.id)??null,c=y?((p=t.attemptMetaById)==null?void 0:p.get(y))??null:null,!c&&(e==null?void 0:e.role)==="user"&&(e!=null&&e.id)&&t.userMessageIdToAttempts){const k=t.userMessageIdToAttempts.get(e.id);if(k&&k.length>0){const C=k[0].checkpointId;c=((h=t.attemptMetaById)==null?void 0:h.get(C))??null,c&&console.log(`[useMessageMetadata] Found attempt by user message ID "${e.id}":`,k.length,"versions")}}if(!c&&r.length>0&&t.attemptMetaById){const k=t.attemptMetaById.get(r[0].id);k&&(c=k)}if(c&&c.attemptCount>1&&t.attemptMetaById){const k=c.baseUserMessageId;if(k){const C=[];for(const[T,E]of t.attemptMetaById.entries())if(E.baseUserMessageId===k){const N=(g=t.checkpointMetaById)==null?void 0:g.get(T);N&&C.push(N)}C.length>0&&(r=C)}}if(c&&c.attemptCount>1&&t.checkpointMetaById&&t.attemptMetaById){const k=[];for(const[C,T]of t.checkpointMetaById.entries()){const E=t.attemptMetaById.get(C);E&&E.attemptCount===c.attemptCount&&E.baseUserMessageId===c.baseUserMessageId&&k.push(T)}k.sort((C,T)=>{const E=C.createdAt?Date.parse(C.createdAt):0;return(T.createdAt?Date.parse(T.createdAt):0)-E}),k.length>0&&(r=k,console.log("[useMessageMetadata] Populated checkpointCandidates with all attempts:",{messageId:e.id,attemptCount:c.attemptCount,candidateIds:r.map(C=>C.id)}))}}return{checkpointCandidates:r,defaultCheckpointId:o,attemptMeta:c,resolvedStep:a,resolvedSource:l}},[e,t.checkpointMetaById,t.checkpointIndexByKey,t.attemptMetaById,t.userMessageIdToAttempts])}const xp=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,yp=b.memo(function({message:t,index:n,isStreaming:r,streamingAssistantId:o,streamingDebounceMs:s,layoutSize:i,enableMessageEditing:a,editingMessageId:l,onEdit:c,onRegenerate:d,onCancelEdit:f,activeInterrupt:p,disableInterruptActions:h,onInterruptActionStart:g,onInterruptActionEnd:m,showToolMessages:y,showArtifactPreviews:x,checkpointMetaById:w,checkpointIndexByKey:S,attemptMetaById:k,userMessageIdToAttempts:C,activeCheckpointId:T,onSelectCheckpoint:E}){const N=xp(t,n),_="type"in t&&t.type==="default_message",{checkpointCandidates:D,defaultCheckpointId:B,attemptMeta:G}=bC(t,{checkpointMetaById:w,checkpointIndexByKey:S,attemptMetaById:k,userMessageIdToAttempts:C}),V=t&&!_?t.additionalKwargs??{}:{},P=t&&!_?t.responseMetadata??{}:{},M=(()=>{if(typeof V.parentCheckpointId=="string")return V.parentCheckpointId;if(typeof P.parentCheckpointId=="string")return P.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":N,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ls,{message:t,messageIndex:n,isStreamingMessage:r&&o===t.id,streamingDebounceMs:s,isEditing:l===t.id,showActions:a,showTimestamp:!1,showAgentName:!0,layoutSize:i,onEdit:c,onRegenerate:()=>d(n),onCancelEdit:f,activeInterrupt:p,disableInterruptActions:h,onInterruptActionStart:g,onInterruptActionEnd:m,showToolMessages:y,showArtifactPreviews:x,checkpointCandidates:D,activeCheckpointId:T??null,onSelectCheckpoint:E,defaultCheckpointId:B,messageParentCheckpointId:M,attemptMeta:G})})});yp.displayName="MessageRow";const ja=b.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:f,style:p,emptyMessage:h,followNewMessages:g=!0,isNavigatingCheckpoint:m=!1,onScrollAway:y,onAtBottom:x,activeInterrupt:w,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T=!0,showArtifactPreviews:E=!0,checkpointMetaById:N,checkpointIndexByKey:_,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:G,onSelectCheckpoint:V,createSyntheticThinkingMessage:P=!1},M)=>{const A=b.useRef(null),F=b.useRef(null),L=b.useRef(!1),R=b.useRef(!1),[z,X]=b.useState(!0),ne=b.useMemo(()=>w?e.some(se=>"type"in se&&se.type==="default_message"?!1:Array.isArray(se==null?void 0:se.content)&&se.content.some(me=>me&&me.type==="interrupt"&&(me.id??me.interrupt_id)===w.id)):!1,[w,e]),ye=b.useMemo(()=>{if(!w||ne)return null;const se=w.id&&String(w.id).trim()?String(w.id).trim():"pending-interrupt";let me;const Pe=w.value;if(Pe&&typeof Pe=="object"&&!Array.isArray(Pe)){const Ve=Pe.title;typeof Ve=="string"&&Ve.trim()&&(me=Ve.trim())}return{id:`interrupt-${se}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:se,value:Pe,title:me}]}},[w,ne]),Te=b.useMemo(()=>ye?[...e,ye]:e,[e,ye]),q=b.useMemo(()=>!P||!t?Te:!Te.some(me=>me.role==="assistant")&&Te.length>0?[...Te,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString()}]:Te,[Te,t,P]),U=b.useMemo(()=>T?q:q.filter(se=>(se==null?void 0:se.role)!=="tool"),[q,T]),Z=b.useCallback(se=>{X(se),y&&y(!se),x&&x(se)},[y,x]),$=b.useMemo(()=>{if(a)return async()=>{if(!L.current){L.current=!0;try{await a()}finally{L.current=!1}}}},[a]),Y=b.useMemo(()=>!g||m?!1:z?"auto":!1,[z,g,m]),Q=b.useMemo(()=>{if(typeof h!="string")return null;const se=h.trim();return se?{id:"default-message",role:"assistant",type:"default_message",content:se,createdAt:new Date().toISOString()}:null},[h]),de=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),oe=()=>Q?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Ls,{message:Q,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{},showArtifactPreviews:E})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:h??"No messages yet. Start a conversation!"}),_e=U.length,ze=_e>0;return b.useEffect(()=>{var se,me;if(_e===0){R.current=!1;return}if(!R.current)if(R.current=!0,A.current&&U.length>0){const Pe=U.length-1;(me=(se=A.current).scrollToIndex)==null||me.call(se,{index:Pe,align:"end",behavior:"auto"})}else F.current&&(F.current.scrollTop=F.current.scrollHeight)},[_e,U.length]),b.useImperativeHandle(M,()=>({scrollToLatest:()=>{var se,me;if(A.current&&U.length>0){const Pe=U.length-1;(me=(se=A.current).scrollToIndex)==null||me.call(se,{index:Pe,align:"end",behavior:"auto"})}else F.current&&(F.current.scrollTop=F.current.scrollHeight)},scrollToTop:()=>{var se,me;A.current&&U.length>0?(me=(se=A.current).scrollToIndex)==null||me.call(se,{index:0,align:"start",behavior:"auto"}):F.current&&(F.current.scrollTop=0)}}),[U]),u.jsx("div",{className:de,style:p,children:u.jsx("div",{className:"relative flex-1 min-h-0",children:ze?u.jsx(Q0,{ref:se=>{A.current=se},scrollerRef:se=>{F.current=se instanceof HTMLDivElement?se:null},data:U,followOutput:Y,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{$&&$()},atBottomStateChange:Z,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(se,me)=>xp(me,se),itemContent:(se,me)=>u.jsx(yp,{message:me,index:se,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:l,onRegenerate:c,onCancelEdit:d,activeInterrupt:w,disableInterruptActions:S,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T,showArtifactPreviews:E,checkpointMetaById:N,checkpointIndexByKey:_,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:G,onSelectCheckpoint:V})}):oe()})})});ja.displayName="MessageList";const vp={value:""};function $s({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:c=!0,showToolMessages:d=!0,showArtifactPreviews:f=!0,customStyles:p={},onMessageSent:h,onExcelUploadSuccess:g,onError:m}){const{api:y}=di(),{currentThreadId:x}=jo(),{threadId:w,messages:S,isHistoryLoading:k,isLoading:C,navigateToCheckpoint:T,returnToLatest:E,checkpoint:N,checkpoints:_,interrupt:D,metadata:B,timelineCheckpoints:G,messagePreviews:V}=Mo(),{isStreaming:P,error:M,connectionState:A,submit:F,stop:L}=pc(),R=w??x??null,z=(N==null?void 0:N.id)??null,X=(N==null?void 0:N.namespace)??null,ne=(B==null?void 0:B.assemblingMessageId)??null,ye=D,[Te,q]=b.useState(!1);b.useEffect(()=>{ye||q(!1)},[ye]);const U=b.useCallback(()=>{q(!0)},[]),Z=b.useCallback(()=>{q(!1)},[]),$=!!ye||Te,[Y,Q]=b.useState(null),[de,oe]=b.useState(""),[_e,ze]=b.useState(null),[se,me]=b.useState(null),[Pe,Ve]=b.useState([]),[ut,Ke]=b.useState(0),[qe,Qe]=b.useState(0),[Ge,et]=b.useState(!1),[st,Mt]=b.useState(null),[gt,Ct]=b.useState(null),[it,St]=b.useState(!1),[Pt,zt]=b.useState(null),nn=b.useRef(!1),[Le,Sn]=b.useState(()=>vp.value),tt=b.useRef(Le),We=b.useRef(null),pt=b.useCallback(he=>{vp.value=he,Sn(he)},[]),[Rt,Ye]=b.useState(!1),H=b.useRef(null),{checkpointMetaById:j,checkpointIndexByKey:J,attemptMetaById:re,userMessageIdToAttempts:ie}=Bb(_),ce=G??[],Xe=b.useRef(null),Ie=b.useRef(null),at=b.useCallback(()=>{Xe.current&&(Xe.current.value=""),Ie.current&&(Ie.current.value=""),Ke(he=>he+1),Qe(he=>he+1)},[]),ht=b.useCallback(he=>{pt(he)},[pt]),Kt=b.useRef(!1);b.useEffect(()=>{Kt.current&&!P&&(Ve([]),at()),Kt.current=P},[P,at]);const[Hn,Ar]=b.useState("desktop");b.useEffect(()=>{const he=()=>{const be=window.innerWidth;Ar(be<640?"phone":be<1024?"tablet":"desktop")};return he(),window.addEventListener("resize",he),()=>window.removeEventListener("resize",he)},[]),b.useEffect(()=>{nn.current=!1},[R]),b.useEffect(()=>{tt.current=Le},[Le]),b.useEffect(()=>{if(!Y){We.current=null;return}We.current===null&&(We.current=tt.current),pt(de??"")},[de,Y,pt]),b.useEffect(()=>{(async()=>{if(!y.baseUrl){zt(null);return}try{const Ee=(await y.getAgent("default")).uiDefaultMessage||"";zt(Ee||null)}catch(be){console.warn("Failed to fetch default message:",be),zt(null)}})()},[y.baseUrl]),b.useEffect(()=>{M&&!it&&(m==null||m(M))},[M,it,m]);const Nr=he=>{if(he.length>us)return`Message too long (${he.length}/${us} characters)`;try{return Hb(he),null}catch(be){return(be==null?void 0:be.message)||"Invalid message"}},po=async he=>{const be=he.trim();if(!(!be&&Pe.length===0)){if(be){const Ee=Nr(be);if(Ee){me(Ee);return}}try{const Ee=Y?(_e==null?void 0:_e.checkpointId)??z??void 0:z??void 0,Ue=Y?(_e==null?void 0:_e.checkpointNs)??X??void 0:X??void 0;await F({text:be||"",attachments:Pe},{checkpointId:Ee,checkpointNs:Ue,edit:!!Y,originalMessageId:Y??void 0}),h==null||h(be),pt(""),me(null),Ve([]),at(),Q(null),oe(""),ze(null)}catch(Ee){const Ue=(Ee==null?void 0:Ee.message)||"Failed to send message";me(Ue),m==null||m(Ue)}}},Nn=b.useCallback((he,be,Ee)=>{c&&(We.current=Le,Q(he),oe(be),pt(be),me(null),ze({checkpointId:(Ee==null?void 0:Ee.checkpointId)??null,checkpointNs:(Ee==null?void 0:Ee.checkpointNs)??null}))},[Le,c,pt]),I=b.useCallback(()=>{Q(null),oe(""),ze(null),me(null),pt(We.current??Le),We.current=null},[Le,pt]),W=b.useCallback((he,be,Ee)=>{Nn(he,be,Ee)},[Nn]),ae=b.useCallback(he=>{let be=null;for(let rn=he-1;rn>=0;rn--)if(S[rn].role==="user"){be=S[rn];break}if(!be)return;const Ee=Array.isArray(be.content)?be.content:[],Wn=Ee.filter(rn=>(rn==null?void 0:rn.type)==="text").map(rn=>rn.text).join("")||(()=>{try{return JSON.stringify(Ee,null,2)}catch{return String(Ee)}})();Wn&&F({text:Wn},{checkpointId:z??void 0,checkpointNs:X??void 0,edit:!0,originalMessageId:be.id})},[S,F,z,X]),we=he=>{const be=Array.from(he.target.files||[]);Ve(Ee=>[...Ee,...be]),he.target.value=""},Be=he=>{Ve(be=>{const Ee=be.filter((Ue,Wn)=>he!==Wn);return Ee.length===0&&at(),Ee})},nt=async he=>{const be=(he.target.files||[])[0];if(be){Mt(null),Ct(null),et(!0);try{await F({attachments:[be]},{checkpointId:z??void 0,checkpointNs:X??void 0});const Ee=`Uploaded ${be.name} - processing through chat stream`;Ct(Ee)}catch(Ee){const Ue=Ee instanceof Error?Ee.message:"Failed to upload Excel file";console.error("Excel upload failed",Ee),Mt(Ue),m==null||m(Ue)}finally{et(!1),he.target.value="",at()}}},De=async he=>{if(x){Ye(!0);try{if(!he){await E(),requestAnimationFrame(()=>{var Ue;(Ue=H.current)==null||Ue.scrollToLatest()});return}const be=_.find(Ue=>Ue.checkpointId===he),Ee=(be==null?void 0:be.checkpointNs)??null;await T(he,Ee),requestAnimationFrame(()=>{var Ue;(Ue=H.current)==null||Ue.scrollToTop()})}finally{Ye(!1)}}},Oe=b.useCallback(async(he,be,Ee)=>{await De(Ee?null:he)},[De]),It=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${p.container||""}`,mt=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${p.messagesArea||""}`,xt=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${p.inputArea||""}`;return u.jsxs("div",{className:It,children:[!!M&&!it&&u.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[u.jsx("span",{children:M}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>St(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(le.X,{size:16})})]}),u.jsxs("div",{className:`relative ${mt}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(ja,{ref:H,className:"h-full",style:{height:"100%"},messages:S,isStreaming:P,streamingAssistantId:ne,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Hn,enableMessageEditing:c,editingMessageId:Y,onEdit:W,onRegenerate:ae,onCancelEdit:I,emptyMessage:Pt??void 0,isNavigatingCheckpoint:Rt,activeInterrupt:ye,disableInterruptActions:Te,onInterruptActionStart:U,onInterruptActionEnd:Z,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:j,checkpointIndexByKey:J,attemptMetaById:re,userMessageIdToAttempts:ie,activeCheckpointId:z,onSelectCheckpoint:Oe,timelineCheckpoints:ce,messagePreviews:V}),(A==="reconnecting"||A==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(le.Loader2,{className:"h-3 w-3 animate-spin"}),A==="reconnecting"?"Reconnecting…":"Connecting…"]})}),A==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),C&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(le.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||Rt)&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(le.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]})]}),u.jsxs("div",{className:xt,children:[Y&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(le.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:I,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(le.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Xe,type:"file",multiple:!0,onChange:he=>we(he),className:"hidden"},ut),Pe.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:Pe.map((he,be)=>u.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[u.jsx(le.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:he.name}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>Be(be),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${he.name}`,children:u.jsx(le.X,{size:12})})]},be))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Ie,type:"file",accept:".xls,.xlsx,.xlsm",onChange:nt,className:"hidden"},qe),Ge&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(le.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),gt&&!Ge&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:gt}),st&&!Ge&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:st})]})]}),se&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:se}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(Eb,{children:[u.jsx(Ib,{asChild:!0,children:u.jsx(Je,{type:"button",size:"icon",variant:"outline",disabled:P||$,title:"More input actions",className:p.moreButton||"",children:u.jsx(le.Plus,{size:16})})}),u.jsxs(Td,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Zi,{onClick:()=>{var he;return(he=Xe.current)==null?void 0:he.click()},className:"cursor-pointer",children:[u.jsx(le.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Zi,{onClick:()=>{var he;Ge||(he=Ie.current)==null||he.click()},className:`cursor-pointer ${Ge?"opacity-60 pointer-events-none":""}`,children:[u.jsx(le.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(Ix,{initialValue:de,editingMessageId:Y,value:Le,onValueChange:ht,placeholder:Y?"Edit your message...":t,isStreaming:P,disabled:$,maxLength:us,onSend:po,onCancelEdit:I,onStop:L,allowEmptySend:Pe.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${Y?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${se?"border-red-400":""} ${p.textarea||""}`})})]})]})]})}const Fs=v.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:te("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground 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 md:text-sm",e),ref:r,...n}));Fs.displayName="Input";function Ma(e,[t,n]){return Math.min(n,Math.max(t,e))}function SC(e,t){return v.useReducer((n,r)=>t[n][r]??n,e)}var Pa="ScrollArea",[wp,pk]=Tn(Pa),[CC,en]=wp(Pa),bp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=v.useState(null),[c,d]=v.useState(null),[f,p]=v.useState(null),[h,g]=v.useState(null),[m,y]=v.useState(null),[x,w]=v.useState(0),[S,k]=v.useState(0),[C,T]=v.useState(!1),[E,N]=v.useState(!1),_=$e(t,B=>l(B)),D=Ro(o);return u.jsx(CC,{scope:n,type:r,dir:D,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:p,scrollbarX:h,onScrollbarXChange:g,scrollbarXEnabled:C,onScrollbarXEnabledChange:T,scrollbarY:m,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:N,onCornerWidthChange:w,onCornerHeightChange:k,children:u.jsx(Ne.div,{dir:D,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":S+"px",...e.style}})})});bp.displayName=Pa;var Sp="ScrollAreaViewport",Cp=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=en(Sp,n),a=v.useRef(null),l=$e(t,a,i.onViewportChange);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),u.jsx(Ne.div,{"data-radix-scroll-area-viewport":"",...s,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:u.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Cp.displayName=Sp;var bn="ScrollAreaScrollbar",Ra=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(bn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return v.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(TC,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(kC,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(Tp,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Oa,{...r,ref:t}):null});Ra.displayName=bn;var TC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(bn,e.__scopeScrollArea),[s,i]=v.useState(!1);return v.useEffect(()=>{const a=o.scrollArea;let l=0;if(a){const c=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",d)}}},[o.scrollArea,o.scrollHideDelay]),u.jsx(Xt,{present:n||s,children:u.jsx(Tp,{"data-state":s?"visible":"hidden",...r,ref:t})})}),kC=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=en(bn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Hs(()=>l("SCROLL_END"),100),[a,l]=SC("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return v.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),v.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const p=()=>{const h=c[d];f!==h&&(l("SCROLL"),i()),f=h};return c.addEventListener("scroll",p),()=>c.removeEventListener("scroll",p)}},[o.viewport,s,l,i]),u.jsx(Xt,{present:n||a!=="hidden",children:u.jsx(Oa,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:pe(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:pe(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Tp=v.forwardRef((e,t)=>{const n=en(bn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=v.useState(!1),a=e.orientation==="horizontal",l=Hs(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return kr(n.viewport,l),kr(n.content,l),u.jsx(Xt,{present:r||s,children:u.jsx(Oa,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Oa=v.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=en(bn,e.__scopeScrollArea),s=v.useRef(null),i=v.useRef(0),[a,l]=v.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Np(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:p=>s.current=p,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:p=>i.current=p};function f(p,h){return jC(p,i.current,a,h)}return n==="horizontal"?u.jsx(EC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollLeft,h=_p(p,a,o.dir);s.current.style.transform=`translate3d(${h}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=f(p,o.dir))}}):n==="vertical"?u.jsx(IC,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const p=o.viewport.scrollTop,h=_p(p,a);s.current.style.transform=`translate3d(0, ${h}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=f(p))}}):null}),EC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=en(bn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=$e(t,l,s.onScrollbarXChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Ep,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Us(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(p),Mp(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:zs(i.paddingLeft),paddingEnd:zs(i.paddingRight)}})}})}),IC=v.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=en(bn,e.__scopeScrollArea),[i,a]=v.useState(),l=v.useRef(null),c=$e(t,l,s.onScrollbarYChange);return v.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Ep,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Us(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const p=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(p),Mp(p,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:zs(i.paddingTop),paddingEnd:zs(i.paddingBottom)}})}})}),[AC,kp]=wp(bn),Ep=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...p}=e,h=en(bn,n),[g,m]=v.useState(null),y=$e(t,_=>m(_)),x=v.useRef(null),w=v.useRef(""),S=h.viewport,k=r.content-r.viewport,C=Et(d),T=Et(l),E=Hs(f,10);function N(_){if(x.current){const D=_.clientX-x.current.left,B=_.clientY-x.current.top;c({x:D,y:B})}}return v.useEffect(()=>{const _=D=>{const B=D.target;(g==null?void 0:g.contains(B))&&C(D,k)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[S,g,k,C]),v.useEffect(T,[r,T]),kr(g,E),kr(h.content,E),u.jsx(AC,{scope:n,scrollbar:g,hasThumb:o,onThumbChange:Et(s),onThumbPointerUp:Et(i),onThumbPositionChange:T,onThumbPointerDown:Et(a),children:u.jsx(Ne.div,{...p,ref:y,style:{position:"absolute",...p.style},onPointerDown:pe(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),x.current=g.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",h.viewport&&(h.viewport.style.scrollBehavior="auto"),N(_))}),onPointerMove:pe(e.onPointerMove,N),onPointerUp:pe(e.onPointerUp,_=>{const D=_.target;D.hasPointerCapture(_.pointerId)&&D.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=w.current,h.viewport&&(h.viewport.style.scrollBehavior=""),x.current=null})})})}),Bs="ScrollAreaThumb",Ip=v.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=kp(Bs,e.__scopeScrollArea);return u.jsx(Xt,{present:n||o.hasThumb,children:u.jsx(NC,{ref:t,...r})})}),NC=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=en(Bs,n),i=kp(Bs,n),{onThumbPositionChange:a}=i,l=$e(t,f=>i.onThumbChange(f)),c=v.useRef(void 0),d=Hs(()=>{c.current&&(c.current(),c.current=void 0)},100);return v.useEffect(()=>{const f=s.viewport;if(f){const p=()=>{if(d(),!c.current){const h=MC(f,a);c.current=h,a()}};return a(),f.addEventListener("scroll",p),()=>f.removeEventListener("scroll",p)}},[s.viewport,d,a]),u.jsx(Ne.div,{"data-state":i.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:pe(e.onPointerDownCapture,f=>{const h=f.target.getBoundingClientRect(),g=f.clientX-h.left,m=f.clientY-h.top;i.onThumbPointerDown({x:g,y:m})}),onPointerUp:pe(e.onPointerUp,i.onThumbPointerUp)})});Ip.displayName=Bs;var Da="ScrollAreaCorner",Ap=v.forwardRef((e,t)=>{const n=en(Da,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(_C,{...e,ref:t}):null});Ap.displayName=Da;var _C=v.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=en(Da,n),[s,i]=v.useState(0),[a,l]=v.useState(0),c=!!(s&&a);return kr(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),kr(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(Ne.div,{...r,ref:t,style:{width:s,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function zs(e){return e?parseInt(e,10):0}function Np(e,t){const n=e/t;return isNaN(n)?0:n}function Us(e){const t=Np(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function jC(e,t,n,r="ltr"){const o=Us(n),s=o/2,i=t||s,a=o-i,l=n.scrollbar.paddingStart+i,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return jp([l,c],f)(e)}function _p(e,t,n="ltr"){const r=Us(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,i=t.content-t.viewport,a=s-r,l=n==="ltr"?[0,i]:[i*-1,0],c=Ma(e,l);return jp([0,i],[0,a])(c)}function jp(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Mp(e,t){return e>0&&e<t}var MC=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},i=n.left!==s.left,a=n.top!==s.top;(i||a)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function Hs(e,t){const n=Et(e),r=v.useRef(0);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),v.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function kr(e,t){const n=Et(t);kt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Pp=bp,PC=Cp,RC=Ap;const Rp=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Pp,{ref:r,className:te("relative overflow-hidden",e),...n,children:[u.jsx(PC,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Op,{}),u.jsx(RC,{})]}));Rp.displayName=Pp.displayName;const Op=v.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Ra,{ref:r,orientation:t,className:te("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:u.jsx(Ip,{className:"relative flex-1 rounded-full bg-border"})}));Op.displayName=Ra.displayName;const Dp=25;function La({className:e="",showCreateButton:t=!0,showDeleteButton:n=!0,showEditTitle:r=!0,maxHeight:o="400px",customStyles:s={},currentThreadId:i=null,navigateToThread:a,onThreadSelect:l,onThreadCreate:c,onThreadDelete:d}){const{threads:f,currentThreadId:p,setCurrentThreadId:h,isLoading:g,actions:m}=jo(),{loadThread:y}=Mo(),{createThread:x,deleteThread:w,renameThread:S}=m,[k,C]=b.useState(Array.isArray(f)?f:[]),T=b.useRef(k.length>0),E=b.useRef(null),N=b.useRef(0),[_,D]=b.useState(null),[B,G]=b.useState(""),[V,P]=b.useState(!1);b.useEffect(()=>{const q=Array.isArray(f)?f:[];if(q.length>0){T.current=!0,C(q);return}g||(T.current=!1,C(q))},[f,g]),b.useEffect(()=>{if(!E.current)return;const q=E.current.querySelector("[data-radix-scroll-area-viewport]");if(!q)return;let U=null,Z=null;return U=requestAnimationFrame(()=>{Z=requestAnimationFrame(()=>{q.scrollTop=N.current})}),()=>{U!==null&&cancelAnimationFrame(U),Z!==null&&cancelAnimationFrame(Z)}},[k]);const M=async q=>{try{h(q),await y(q,void 0,{clearProgress:!0}),a==null||a(q),l==null||l(q)}catch(U){console.error("Failed to select thread:",U)}},A=async()=>{try{P(!0);const q=await x();q&&(c==null||c(q),a==null||a(q))}catch(q){console.error("Failed to create thread:",q)}finally{P(!1)}},F=async(q,U)=>{if(U.stopPropagation(),!!confirm("Delete this thread?")){if(E.current){const Z=E.current.querySelector("[data-radix-scroll-area-viewport]");Z&&(N.current=Z.scrollTop)}try{await w(q),d==null||d(q)}catch(Z){console.error("Failed to delete thread:",Z)}}},L=(q,U)=>{U.stopPropagation(),D(q.threadId),G(q.title||`Thread ${q.threadId.slice(0,8)}`)},R=async q=>{if(B.trim())try{await S(q,B.trim()),D(null),G("")}catch(U){console.error("Failed to update title:",U)}},z=()=>{D(null),G("")},X=(q,U)=>{q.key==="Enter"?R(U):q.key==="Escape"&&z()},ne=q=>{if(!q)return"";try{const U=new Date(q),$=new Date().getTime()-U.getTime(),Y=Math.floor($/(1e3*60*60*24));return Y===0?U.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):Y===1?"Yesterday":Y<7?`${Y} days ago`:U.toLocaleDateString()}catch{return""}},ye=q=>q.title||`Thread ${q.threadId.slice(0,8)}`,Te=q=>{const U=ye(q);return U.length<=Dp?U:`${U.slice(0,Dp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[t&&u.jsx("div",{className:s.header||"flex-shrink-0 p-2 border-b bg-slate-800 border-slate-700 text-slate-100 flex justify-end",children:u.jsx(Je,{onClick:A,disabled:V||g,className:s.createButton||"p-2",size:"sm",variant:"ghost",title:V?"Creating...":"New Chat",children:u.jsx(le.MessageSquarePlus,{size:20})})}),u.jsx(Rp,{ref:E,className:`flex-1 min-h-0 ${s.threadList||""}`,style:o?{maxHeight:o}:void 0,children:u.jsx("div",{className:"p-2 space-y-1 pb-4",children:g?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(le.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):k.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(le.MessageSquare,{className:"w-8 h-8 mx-auto mb-2 opacity-40 text-slate-500"}),u.jsx("p",{className:"text-sm text-slate-500",children:"No conversations yet"})]}):k.slice().sort((q,U)=>new Date(U.updatedAt||U.createdAt||"").getTime()-new Date(q.updatedAt||q.createdAt||"").getTime()).map(q=>u.jsxs("div",{onClick:()=>M(q.threadId),className:`group relative p-3 rounded-lg cursor-pointer transition-colors border ${(i??p)===q.threadId?`${s.activeThread||"bg-slate-600 border-slate-500"} `:`${s.threadItem||"bg-slate-700 border-slate-600 hover:bg-slate-600 text-gray-900 dark:text-slate-100"}`} ${s.threadItem||""} text-gray-900 dark:text-slate-100`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:_===q.threadId?u.jsxs("div",{className:"flex items-center gap-2",onClick:U=>U.stopPropagation(),children:[u.jsx(Fs,{value:B,onChange:U=>G(U.target.value),onKeyDown:U=>X(U,q.threadId),className:"h-6 text-sm",autoFocus:!0}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:()=>R(q.threadId),className:"h-6 w-6 p-0",children:u.jsx(le.Check,{size:12})}),u.jsx(Je,{variant:"ghost",size:"sm",onClick:z,className:"h-6 w-6 p-0",children:u.jsx(le.X,{size:12})})]}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"font-medium text-sm truncate text-gray-900 dark:text-slate-100",children:Te(q)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(le.Calendar,{size:10}),u.jsx("span",{children:ne(q.updatedAt||q.createdAt)})]})]})}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:[r&&_!==q.threadId&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:U=>L(q,U),className:"h-6 w-6 p-0",title:"Edit title",children:u.jsx(le.Edit3,{size:12})}),n&&u.jsx(Je,{variant:"ghost",size:"sm",onClick:U=>F(q.threadId,U),className:"h-6 w-6 p-0 text-red-400 hover:text-red-300 hover:bg-red-900/20",title:"Delete thread",children:u.jsx(le.Trash2,{size:12})})]})]}),i===q.threadId&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]},q.threadId))})})]})}const OC=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r,className:o,onHoverStart:s,onHoverEnd:i})=>{const a=e??[],l=a.length>0,c=b.useMemo(()=>l?[...a].reverse():[],[a,l]),d=t??(a.length?a[a.length-1].id:null);if(!l)return null;const p=["w-32 flex-shrink-0 flex-col border-r border-border/40 pr-2 flex bg-white text-gray-900 dark:bg-slate-900 dark:text-slate-100",o].filter(Boolean).join(" ");return u.jsxs("div",{className:p,onMouseEnter:s,onMouseLeave:i,children:[u.jsxs("div",{className:"relative flex-1 overflow-y-auto pt-4 pb-2 pr-1",children:[u.jsx("div",{className:"absolute left-0 right-0 top-1 px-2 pb-3 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:u.jsx("span",{children:"Timeline"})}),u.jsx("div",{className:"pointer-events-none absolute left-3 top-0 bottom-0 w-px bg-border/40"}),u.jsx("div",{className:"flex flex-col gap-3 pt-6 pr-2",children:c.map(h=>{const g=d===h.id,m=(r==null?void 0:r.get(h.id))??null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(h.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${g?"text-primary":"text-muted-foreground"} ${n?"hover:text-foreground":"cursor-default opacity-70"}`,children:[u.jsx("span",{className:`mt-1 inline-flex h-3 w-3 items-center justify-center rounded-full border ${g?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${g?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:h.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[h.step!==null?`STEP ${h.step}`:"STEP —",h.next?` - ${h.next}`:""]}),m&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:m,children:m})]})]},h.id)})})]}),n&&u.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(null),className:"mt-auto mb-3 rounded-md border border-border/70 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground transition hover:border-foreground/60 hover:text-foreground",children:"Latest"})]})};function Er(e){if(!(typeof globalThis>"u"))return globalThis[e]}function DC(e){if(typeof e!="string")return;const t=e.trim();if(t)return Cn(t)}function Lp(){const e=[Er("__API_BASE_URL__"),Er("__CHAT_API_BASE_URL__"),Er("__CHAT_API_URL__")];for(const t of e){const n=DC(t);if(n)return n}}function $p(){const e=[Er("__API_AUTH_TOKEN__"),Er("__CHAT_API_KEY__"),Er("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function Fp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Cn(t);return Cn()}function Bp(){const e={},t=Lp(),n=$p();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function zp(){const e=Bp(),t=_n.getAuthToken(),n=Lp();return{apiBaseUrl:Fp(e.baseUrl,_n.baseUrl,n),apiKey:t||e.apiKey||$p()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Up="chat-settings";function LC(){try{const e=localStorage.getItem(Up);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function $C(e){try{const t={...e,apiBaseUrl:Cn(e.apiBaseUrl)};localStorage.setItem(Up,JSON.stringify(t)),t.apiKey&&_n.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function FC(){const e=zp(),t=LC(),n=_n.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:Fp(_n.baseUrl,r,e.apiBaseUrl)}}function BC(e){_n.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),$C(e)}var zC="Label",Hp=v.forwardRef((e,t)=>u.jsx(Ne.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Hp.displayName=zC;var Wp=Hp;const UC=ho.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),tn=v.forwardRef(({className:e,...t},n)=>u.jsx(Wp,{ref:n,className:te(UC(),e),...t}));tn.displayName=Wp.displayName;function Vp(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Kp=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),HC="VisuallyHidden",WC=v.forwardRef((e,t)=>u.jsx(Ne.span,{...e,ref:t,style:{...Kp,...e.style}}));WC.displayName=HC;var VC=[" ","Enter","ArrowUp","ArrowDown"],KC=[" ","Enter"],sr="Select",[Ws,Vs,qC]=xi(sr),[Ir,hk]=Tn(sr,[qC,qo]),Ks=qo(),[GC,Bn]=Ir(sr),[YC,XC]=Ir(sr),qp=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:f,disabled:p,required:h,form:g}=e,m=Ks(t),[y,x]=v.useState(null),[w,S]=v.useState(null),[k,C]=v.useState(!1),T=Ro(c),[E,N]=pr({prop:r,defaultProp:o??!1,onChange:s,caller:sr}),[_,D]=pr({prop:i,defaultProp:a,onChange:l,caller:sr}),B=v.useRef(null),G=y?g||!!y.closest("form"):!0,[V,P]=v.useState(new Set),M=Array.from(V).map(A=>A.props.value).join(";");return u.jsx(au,{...m,children:u.jsxs(GC,{required:h,scope:t,trigger:y,onTriggerChange:x,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:k,onValueNodeHasChildrenChange:C,contentId:kn(),value:_,onValueChange:D,open:E,onOpenChange:N,dir:T,triggerPointerDownPosRef:B,disabled:p,children:[u.jsx(Ws.Provider,{scope:t,children:u.jsx(YC,{scope:e.__scopeSelect,onNativeOptionAdd:v.useCallback(A=>{P(F=>new Set(F).add(A))},[]),onNativeOptionRemove:v.useCallback(A=>{P(F=>{const L=new Set(F);return L.delete(A),L})},[]),children:n})}),G?u.jsxs(xh,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:A=>D(A.target.value),disabled:p,form:g,children:[_===void 0?u.jsx("option",{value:""}):null,Array.from(V)]},M):null]})})};qp.displayName=sr;var Gp="SelectTrigger",Yp=v.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Ks(n),i=Bn(Gp,n),a=i.disabled||r,l=$e(t,i.onTriggerChange),c=Vs(n),d=v.useRef("touch"),[f,p,h]=vh(m=>{const y=c().filter(S=>!S.disabled),x=y.find(S=>S.value===i.value),w=wh(y,m,x);w!==void 0&&i.onValueChange(w.value)}),g=m=>{a||(i.onOpenChange(!0),h()),m&&(i.triggerPointerDownPosRef.current={x:Math.round(m.pageX),y:Math.round(m.pageY)})};return u.jsx(lu,{asChild:!0,...s,children:u.jsx(Ne.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":yh(i.value)?"":void 0,...o,ref:l,onClick:pe(o.onClick,m=>{m.currentTarget.focus(),d.current!=="mouse"&&g(m)}),onPointerDown:pe(o.onPointerDown,m=>{d.current=m.pointerType;const y=m.target;y.hasPointerCapture(m.pointerId)&&y.releasePointerCapture(m.pointerId),m.button===0&&m.ctrlKey===!1&&m.pointerType==="mouse"&&(g(m),m.preventDefault())}),onKeyDown:pe(o.onKeyDown,m=>{const y=f.current!=="";!(m.ctrlKey||m.altKey||m.metaKey)&&m.key.length===1&&p(m.key),!(y&&m.key===" ")&&VC.includes(m.key)&&(g(),m.preventDefault())})})})});Yp.displayName=Gp;var Xp="SelectValue",Jp=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Bn(Xp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=$e(t,l.onValueNodeChange);return kt(()=>{c(d)},[c,d]),u.jsx(Ne.span,{...a,ref:f,style:{pointerEvents:"none"},children:yh(l.value)?u.jsx(u.Fragment,{children:i}):s})});Jp.displayName=Xp;var JC="SelectIcon",Zp=v.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(Ne.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Zp.displayName=JC;var ZC="SelectPortal",Qp=e=>u.jsx(Go,{asChild:!0,...e});Qp.displayName=ZC;var ir="SelectContent",eh=v.forwardRef((e,t)=>{const n=Bn(ir,e.__scopeSelect),[r,o]=v.useState();if(kt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?mo.createPortal(u.jsx(th,{scope:e.__scopeSelect,children:u.jsx(Ws.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(nh,{...e,ref:t})});eh.displayName=ir;var dn=10,[th,zn]=Ir(ir),QC="SelectContentImpl",eT=Vn.createSlot("SelectContent.RemoveScroll"),nh=v.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:y,...x}=e,w=Bn(ir,n),[S,k]=v.useState(null),[C,T]=v.useState(null),E=$e(t,Z=>k(Z)),[N,_]=v.useState(null),[D,B]=v.useState(null),G=Vs(n),[V,P]=v.useState(!1),M=v.useRef(!1);v.useEffect(()=>{if(S)return Fi(S)},[S]),wi();const A=v.useCallback(Z=>{const[$,...Y]=G().map(oe=>oe.ref.current),[Q]=Y.slice(-1),de=document.activeElement;for(const oe of Z)if(oe===de||(oe==null||oe.scrollIntoView({block:"nearest"}),oe===$&&C&&(C.scrollTop=0),oe===Q&&C&&(C.scrollTop=C.scrollHeight),oe==null||oe.focus(),document.activeElement!==de))return},[G,C]),F=v.useCallback(()=>A([N,S]),[A,N,S]);v.useEffect(()=>{V&&F()},[V,F]);const{onOpenChange:L,triggerPointerDownPosRef:R}=w;v.useEffect(()=>{if(S){let Z={x:0,y:0};const $=Q=>{var de,oe;Z={x:Math.abs(Math.round(Q.pageX)-(((de=R.current)==null?void 0:de.x)??0)),y:Math.abs(Math.round(Q.pageY)-(((oe=R.current)==null?void 0:oe.y)??0))}},Y=Q=>{Z.x<=10&&Z.y<=10?Q.preventDefault():S.contains(Q.target)||L(!1),document.removeEventListener("pointermove",$),R.current=null};return R.current!==null&&(document.addEventListener("pointermove",$),document.addEventListener("pointerup",Y,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",Y,{capture:!0})}}},[S,L,R]),v.useEffect(()=>{const Z=()=>L(!1);return window.addEventListener("blur",Z),window.addEventListener("resize",Z),()=>{window.removeEventListener("blur",Z),window.removeEventListener("resize",Z)}},[L]);const[z,X]=vh(Z=>{const $=G().filter(de=>!de.disabled),Y=$.find(de=>de.ref.current===document.activeElement),Q=wh($,Z,Y);Q&&setTimeout(()=>Q.ref.current.focus())}),ne=v.useCallback((Z,$,Y)=>{const Q=!M.current&&!Y;(w.value!==void 0&&w.value===$||Q)&&(_(Z),Q&&(M.current=!0))},[w.value]),ye=v.useCallback(()=>S==null?void 0:S.focus(),[S]),Te=v.useCallback((Z,$,Y)=>{const Q=!M.current&&!Y;(w.value!==void 0&&w.value===$||Q)&&B(Z)},[w.value]),q=r==="popper"?$a:rh,U=q===$a?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:g,hideWhenDetached:m,avoidCollisions:y}:{};return u.jsx(th,{scope:n,content:S,viewport:C,onViewportChange:T,itemRefCallback:ne,selectedItem:N,onItemLeave:ye,itemTextRefCallback:Te,focusSelectedItem:F,selectedItemText:D,position:r,isPositioned:V,searchRef:z,children:u.jsx(rs,{as:eT,allowPinchZoom:!0,children:u.jsx(Do,{asChild:!0,trapped:w.open,onMountAutoFocus:Z=>{Z.preventDefault()},onUnmountAutoFocus:pe(o,Z=>{var $;($=w.trigger)==null||$.focus({preventScroll:!0}),Z.preventDefault()}),children:u.jsx(Oo,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:Z=>Z.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:u.jsx(q,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:Z=>Z.preventDefault(),...x,...U,onPlaced:()=>P(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:pe(x.onKeyDown,Z=>{const $=Z.ctrlKey||Z.altKey||Z.metaKey;if(Z.key==="Tab"&&Z.preventDefault(),!$&&Z.key.length===1&&X(Z.key),["ArrowUp","ArrowDown","Home","End"].includes(Z.key)){let Q=G().filter(de=>!de.disabled).map(de=>de.ref.current);if(["ArrowUp","End"].includes(Z.key)&&(Q=Q.slice().reverse()),["ArrowUp","ArrowDown"].includes(Z.key)){const de=Z.target,oe=Q.indexOf(de);Q=Q.slice(oe+1)}setTimeout(()=>A(Q)),Z.preventDefault()}})})})})})})});nh.displayName=QC;var tT="SelectItemAlignedPosition",rh=v.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Bn(ir,n),i=zn(ir,n),[a,l]=v.useState(null),[c,d]=v.useState(null),f=$e(t,E=>d(E)),p=Vs(n),h=v.useRef(!1),g=v.useRef(!0),{viewport:m,selectedItem:y,selectedItemText:x,focusSelectedItem:w}=i,S=v.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&m&&y&&x){const E=s.trigger.getBoundingClientRect(),N=c.getBoundingClientRect(),_=s.valueNode.getBoundingClientRect(),D=x.getBoundingClientRect();if(s.dir!=="rtl"){const de=D.left-N.left,oe=_.left-de,_e=E.left-oe,ze=E.width+_e,se=Math.max(ze,N.width),me=window.innerWidth-dn,Pe=Ma(oe,[dn,Math.max(dn,me-se)]);a.style.minWidth=ze+"px",a.style.left=Pe+"px"}else{const de=N.right-D.right,oe=window.innerWidth-_.right-de,_e=window.innerWidth-E.right-oe,ze=E.width+_e,se=Math.max(ze,N.width),me=window.innerWidth-dn,Pe=Ma(oe,[dn,Math.max(dn,me-se)]);a.style.minWidth=ze+"px",a.style.right=Pe+"px"}const B=p(),G=window.innerHeight-dn*2,V=m.scrollHeight,P=window.getComputedStyle(c),M=parseInt(P.borderTopWidth,10),A=parseInt(P.paddingTop,10),F=parseInt(P.borderBottomWidth,10),L=parseInt(P.paddingBottom,10),R=M+A+V+L+F,z=Math.min(y.offsetHeight*5,R),X=window.getComputedStyle(m),ne=parseInt(X.paddingTop,10),ye=parseInt(X.paddingBottom,10),Te=E.top+E.height/2-dn,q=G-Te,U=y.offsetHeight/2,Z=y.offsetTop+U,$=M+A+Z,Y=R-$;if($<=Te){const de=B.length>0&&y===B[B.length-1].ref.current;a.style.bottom="0px";const oe=c.clientHeight-m.offsetTop-m.offsetHeight,_e=Math.max(q,U+(de?ye:0)+oe+F),ze=$+_e;a.style.height=ze+"px"}else{const de=B.length>0&&y===B[0].ref.current;a.style.top="0px";const _e=Math.max(Te,M+m.offsetTop+(de?ne:0)+U)+Y;a.style.height=_e+"px",m.scrollTop=$-Te+m.offsetTop}a.style.margin=`${dn}px 0`,a.style.minHeight=z+"px",a.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[p,s.trigger,s.valueNode,a,c,m,y,x,s.dir,r]);kt(()=>S(),[S]);const[k,C]=v.useState();kt(()=>{c&&C(window.getComputedStyle(c).zIndex)},[c]);const T=v.useCallback(E=>{E&&g.current===!0&&(S(),w==null||w(),g.current=!1)},[S,w]);return u.jsx(rT,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:h,onScrollButtonChange:T,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(Ne.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});rh.displayName=tT;var nT="SelectPopperPosition",$a=v.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=dn,...s}=e,i=Ks(n);return u.jsx(cu,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});$a.displayName=nT;var[rT,Fa]=Ir(ir,{}),Ba="SelectViewport",oh=v.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=zn(Ba,n),i=Fa(Ba,n),a=$e(t,s.onViewportChange),l=v.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx(Ws.Slot,{scope:n,children:u.jsx(Ne.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:pe(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&f){const h=Math.abs(l.current-d.scrollTop);if(h>0){const g=window.innerHeight-dn*2,m=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),x=Math.max(m,y);if(x<g){const w=x+h,S=Math.min(g,w),k=w-S;f.style.height=S+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});oh.displayName=Ba;var sh="SelectGroup",[oT,sT]=Ir(sh),iT=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=kn();return u.jsx(oT,{scope:n,id:o,children:u.jsx(Ne.div,{role:"group","aria-labelledby":o,...r,ref:t})})});iT.displayName=sh;var ih="SelectLabel",ah=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=sT(ih,n);return u.jsx(Ne.div,{id:o.id,...r,ref:t})});ah.displayName=ih;var qs="SelectItem",[aT,lh]=Ir(qs),ch=v.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Bn(qs,n),l=zn(qs,n),c=a.value===r,[d,f]=v.useState(s??""),[p,h]=v.useState(!1),g=$e(t,w=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,w,r,o)}),m=kn(),y=v.useRef("touch"),x=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(aT,{scope:n,value:r,disabled:o,textId:m,isSelected:c,onItemTextChange:v.useCallback(w=>{f(S=>S||((w==null?void 0:w.textContent)??"").trim())},[]),children:u.jsx(Ws.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(Ne.div,{role:"option","aria-labelledby":m,"data-highlighted":p?"":void 0,"aria-selected":c&&p,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:g,onFocus:pe(i.onFocus,()=>h(!0)),onBlur:pe(i.onBlur,()=>h(!1)),onClick:pe(i.onClick,()=>{y.current!=="mouse"&&x()}),onPointerUp:pe(i.onPointerUp,()=>{y.current==="mouse"&&x()}),onPointerDown:pe(i.onPointerDown,w=>{y.current=w.pointerType}),onPointerMove:pe(i.onPointerMove,w=>{var S;y.current=w.pointerType,o?(S=l.onItemLeave)==null||S.call(l):y.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:pe(i.onPointerLeave,w=>{var S;w.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:pe(i.onKeyDown,w=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&w.key===" "||(KC.includes(w.key)&&x(),w.key===" "&&w.preventDefault())})})})})});ch.displayName=qs;var fo="SelectItemText",uh=v.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Bn(fo,n),a=zn(fo,n),l=lh(fo,n),c=XC(fo,n),[d,f]=v.useState(null),p=$e(t,x=>f(x),l.onItemTextChange,x=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,x,l.value,l.disabled)}),h=d==null?void 0:d.textContent,g=v.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:h},l.value),[l.disabled,l.value,h]),{onNativeOptionAdd:m,onNativeOptionRemove:y}=c;return kt(()=>(m(g),()=>y(g)),[m,y,g]),u.jsxs(u.Fragment,{children:[u.jsx(Ne.span,{id:l.textId,...s,ref:p}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?mo.createPortal(s.children,i.valueNode):null]})});uh.displayName=fo;var dh="SelectItemIndicator",fh=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return lh(dh,n).isSelected?u.jsx(Ne.span,{"aria-hidden":!0,...r,ref:t}):null});fh.displayName=dh;var za="SelectScrollUpButton",ph=v.forwardRef((e,t)=>{const n=zn(za,e.__scopeSelect),r=Fa(za,e.__scopeSelect),[o,s]=v.useState(!1),i=$e(t,r.onScrollButtonChange);return kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(mh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});ph.displayName=za;var Ua="SelectScrollDownButton",hh=v.forwardRef((e,t)=>{const n=zn(Ua,e.__scopeSelect),r=Fa(Ua,e.__scopeSelect),[o,s]=v.useState(!1),i=$e(t,r.onScrollButtonChange);return kt(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(mh,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});hh.displayName=Ua;var mh=v.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=zn("SelectScrollButton",n),i=v.useRef(null),a=Vs(n),l=v.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return v.useEffect(()=>()=>l(),[l]),kt(()=>{var d;const c=a().find(f=>f.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(Ne.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:pe(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:pe(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:pe(o.onPointerLeave,()=>{l()})})}),lT="SelectSeparator",gh=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Ne.div,{"aria-hidden":!0,...r,ref:t})});gh.displayName=lT;var Ha="SelectArrow",cT=v.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ks(n),s=Bn(Ha,n),i=zn(Ha,n);return s.open&&i.position==="popper"?u.jsx(uu,{...o,...r,ref:t}):null});cT.displayName=Ha;var uT="SelectBubbleInput",xh=v.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=v.useRef(null),s=$e(r,o),i=Vp(t);return v.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),u.jsx(Ne.select,{...n,style:{...Kp,...n.style},ref:s,defaultValue:t})});xh.displayName=uT;function yh(e){return e===""||e===void 0}function vh(e){const t=Et(e),n=v.useRef(""),r=v.useRef(0),o=v.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=v.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return v.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function wh(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=dT(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function dT(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var fT=qp,bh=Yp,pT=Jp,hT=Zp,mT=Qp,Sh=eh,gT=oh,Ch=ah,Th=ch,xT=uh,yT=fh,kh=ph,Eh=hh,Ih=gh;const Ah=fT,Nh=pT,Wa=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(bh,{ref:r,className:te("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(hT,{asChild:!0,children:u.jsx(le.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Wa.displayName=bh.displayName;const _h=v.forwardRef(({className:e,...t},n)=>u.jsx(kh,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(le.ChevronUp,{className:"h-4 w-4"})}));_h.displayName=kh.displayName;const jh=v.forwardRef(({className:e,...t},n)=>u.jsx(Eh,{ref:n,className:te("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(le.ChevronDown,{className:"h-4 w-4"})}));jh.displayName=Eh.displayName;const Va=v.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(mT,{children:u.jsxs(Sh,{ref:o,className:te("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(_h,{}),u.jsx(gT,{className:te("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(jh,{})]})}));Va.displayName=Sh.displayName;const vT=v.forwardRef(({className:e,...t},n)=>u.jsx(Ch,{ref:n,className:te("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));vT.displayName=Ch.displayName;const ar=v.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Th,{ref:r,className:te("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx(yT,{children:u.jsx(le.Check,{className:"h-4 w-4"})})}),u.jsx(xT,{children:t})]}));ar.displayName=Th.displayName;const wT=v.forwardRef(({className:e,...t},n)=>u.jsx(Ih,{ref:n,className:te("-mx-1 my-1 h-px bg-muted",e),...t}));wT.displayName=Ih.displayName;var bT="Separator",Mh="horizontal",ST=["horizontal","vertical"],Ph=v.forwardRef((e,t)=>{const{decorative:n,orientation:r=Mh,...o}=e,s=CT(r)?r:Mh,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(Ne.div,{"data-orientation":s,...a,...o,ref:t})});Ph.displayName=bT;function CT(e){return ST.includes(e)}var Rh=Ph;const Oh=v.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Rh,{ref:o,decorative:n,orientation:t,className:te("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Oh.displayName=Rh.displayName;const TT=Kf,kT=OS,ET=qf,Dh=v.forwardRef(({className:e,...t},n)=>u.jsx(As,{className:te("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));Dh.displayName=As.displayName;const IT=ho.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Lh=v.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(ET,{children:[u.jsx(Dh,{}),u.jsxs(Ns,{ref:o,className:te(IT({side:e}),t),...r,children:[n,u.jsxs(Gf,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(le.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Lh.displayName=Ns.displayName;const $h=({className:e,...t})=>u.jsx("div",{className:te("flex flex-col space-y-2 text-center sm:text-left",e),...t});$h.displayName="SheetHeader";const Fh=v.forwardRef(({className:e,...t},n)=>u.jsx(rr,{ref:n,className:te("text-lg font-semibold text-foreground",e),...t}));Fh.displayName=rr.displayName;const Bh=v.forwardRef(({className:e,...t},n)=>u.jsx(_s,{ref:n,className:te("text-sm text-muted-foreground",e),...t}));Bh.displayName=_s.displayName;var Gs="Switch",[AT,mk]=Tn(Gs),[NT,_T]=AT(Gs),zh=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...f}=e,[p,h]=v.useState(null),g=$e(t,S=>h(S)),m=v.useRef(!1),y=p?d||!!p.closest("form"):!0,[x,w]=pr({prop:o,defaultProp:s??!1,onChange:c,caller:Gs});return u.jsxs(NT,{scope:n,checked:x,disabled:a,children:[u.jsx(Ne.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":Vh(x),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:g,onClick:pe(e.onClick,S=>{w(k=>!k),y&&(m.current=S.isPropagationStopped(),m.current||S.stopPropagation())})}),y&&u.jsx(Wh,{control:p,bubbles:!m.current,name:r,value:l,checked:x,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});zh.displayName=Gs;var Uh="SwitchThumb",Hh=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_T(Uh,n);return u.jsx(Ne.span,{"data-state":Vh(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Hh.displayName=Uh;var jT="SwitchBubbleInput",Wh=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=v.useRef(null),a=$e(i,s),l=Vp(n),c=Jc(t);return v.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&h){const g=new Event("click",{bubbles:r});h.call(d,n),d.dispatchEvent(g)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Wh.displayName=jT;function Vh(e){return e?"checked":"unchecked"}var Kh=zh,MT=Hh;const Un=v.forwardRef(({className:e,...t},n)=>u.jsx(Kh,{className:te("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(MT,{className:te("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Un.displayName=Kh.displayName;const PT={api:{baseUrl:"http://localhost:8000/api",authToken:"",enableAuth:!1},ui:{layout:"sidebar",theme:"light",showTimestamps:!0,showAgentNames:!0,compactMessages:!1},behavior:{autoSave:!0,enableStreaming:!0,showTypingIndicator:!0}};function RT({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=b.useState(!1),[s,i]=b.useState(!1),[a,l]=b.useState(e),[c,d]=b.useState(!1),{toast:f}=Aa();b.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),b.useEffect(()=>{l(e)},[e]);const p=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},h=()=>{l(PT),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},g=()=>{l(e),d(!1),o(!1)},m=async()=>{try{const x=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${x.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(TT,{open:r,onOpenChange:o,children:[u.jsx(kT,{asChild:!0,children:u.jsxs(Je,{variant:"outline",size:"sm",className:n,children:[u.jsx(le.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Tf,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(Lh,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs($h,{children:[u.jsx(Fh,{children:"Chat Settings"}),u.jsx(Bh,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(ao,{children:[u.jsx(lo,{className:"pb-3",children:u.jsxs(co,{className:"text-lg flex items-center gap-2",children:[u.jsx(le.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(uo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Fs,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(x=>({...x,api:{...x.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(Je,{variant:"outline",onClick:m,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Un,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(x=>({...x,api:{...x.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Fs,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(x=>({...x,api:{...x.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(Je,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(le.EyeOff,{className:"h-4 w-4"}):u.jsx(le.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(ao,{children:[u.jsx(lo,{className:"pb-3",children:u.jsxs(co,{className:"text-lg flex items-center gap-2",children:[u.jsx(le.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(uo,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(Ah,{value:a.ui.layout,onValueChange:y=>l(x=>({...x,ui:{...x.ui,layout:y}})),children:[u.jsx(Wa,{children:u.jsx(Nh,{})}),u.jsxs(Va,{children:[u.jsx(ar,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(ar,{value:"fullscreen",children:"Fullscreen"}),u.jsx(ar,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(tn,{htmlFor:"theme",children:"Theme"}),u.jsxs(Ah,{value:a.ui.theme,onValueChange:y=>l(x=>({...x,ui:{...x.ui,theme:y}})),children:[u.jsx(Wa,{children:u.jsx(Nh,{})}),u.jsxs(Va,{children:[u.jsx(ar,{value:"light",children:"Light"}),u.jsx(ar,{value:"dark",children:"Dark"}),u.jsx(ar,{value:"system",children:"System"})]})]})]}),u.jsx(Oh,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Un,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Un,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(tn,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Un,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(x=>({...x,ui:{...x.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(ao,{children:[u.jsx(lo,{className:"pb-3",children:u.jsxs(co,{className:"text-lg flex items-center gap-2",children:[u.jsx(le.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(uo,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"auto-save",children:"Auto-save Conversations"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically save messages to threads"})]}),u.jsx(Un,{id:"auto-save",checked:a.behavior.autoSave,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"enable-streaming",children:"Enable Streaming"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Stream responses in real-time"})]}),u.jsx(Un,{id:"enable-streaming",checked:a.behavior.enableStreaming,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(tn,{htmlFor:"typing-indicator",children:"Typing Indicator"}),u.jsx("p",{className:"text-sm text-muted-foreground",children:"Show typing indicator during responses"})]}),u.jsx(Un,{id:"typing-indicator",checked:a.behavior.showTypingIndicator,onCheckedChange:y=>l(x=>({...x,behavior:{...x.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(Je,{variant:"outline",onClick:h,children:[u.jsx(le.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Je,{variant:"outline",onClick:g,children:"Cancel"}),u.jsxs(Je,{onClick:p,disabled:!c,children:[u.jsx(le.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function OT({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=b.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(Po,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx($s,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(Po,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(La,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx($s,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(Po,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(La,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx($s,{onError:s.onError,enableFileUpload:!0})})]})})}Se.ChatApi=Bl,Se.ChatInput=mc,Se.ChatInterface=$s,Se.ChatProviders=Po,Se.ChatSettings=RT,Se.MarkdownContent=io,Se.MessageComponent=Ls,Se.MessageList=ja,Se.ThreadManager=La,Se.TimelineColumn=OC,Se.applySettings=BC,Se.buildMessagePreviewMap=Yg,Se.chatApiClient=_n,Se.default=OT,Se.del=Fl,Se.get=Gt,Se.getChatToken=Dl,Se.getCurrentSettings=FC,Se.getDefaultApiConfig=Bp,Se.getDefaultChatSettings=zp,Se.onChatTokenChanged=Ll,Se.post=ui,Se.put=$l,Se.setChatToken=Io,Se.useApi=di,Se.useChatStream=lc,Se.useMessagesReducer=ic,Se.useStream=pc,Se.useThreadState=Mo,Se.useThreads=jo,Object.defineProperties(Se,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});