teodor-new-chat-ui 4.3.379 → 4.3.381

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -3364,6 +3364,10 @@ function Ky(e, t) {
3364
3364
  pendingInterrupt: null,
3365
3365
  toolTimelines: {}
3366
3366
  };
3367
+ case "user_message": {
3368
+ const { message: r } = t.payload;
3369
+ return { ...e, messages: [...e.messages, r] };
3370
+ }
3367
3371
  case "seed": {
3368
3372
  const r = xi(t.payload.messages), { messages: o, toolTimelines: s } = yr(
3369
3373
  r,
@@ -15911,7 +15915,8 @@ function Di({
15911
15915
  activeCheckpointId: K,
15912
15916
  onSelectCheckpoint: Be,
15913
15917
  timelineCheckpoints: De,
15914
- messagePreviews: q
15918
+ messagePreviews: q,
15919
+ createSyntheticThinkingMessage: !0
15915
15920
  }
15916
15921
  ),
15917
15922
  (I === "reconnecting" || I === "connecting") && /* @__PURE__ */ 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: /* @__PURE__ */ u.jsxs("span", { className: "flex items-center gap-2", children: [
package/dist/index.umd.js CHANGED
@@ -32,7 +32,7 @@ React keys must be passed directly to JSX without using spread:
32
32
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[$l]=this[$l]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Lr(i);r[a]||(Dg(o,i),r[a]=!0)}return F.isArray(t)?t.forEach(s):s(t),this}};Ut.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),F.reduceDescriptors(Ut.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),F.freezeMethods(Ut);function mi(e,t){const n=this||Dr,r=t||n,o=Ut.from(r.headers);let s=r.data;return F.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function Fl(e){return!!(e&&e.__CANCEL__)}function dr(e,t,n){Re.call(this,e??"canceled",Re.ERR_CANCELED,t,n),this.name="CanceledError"}F.inherits(dr,Re,{__CANCEL__:!0});function Bl(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Re("Request failed with status code "+n.status,[Re.ERR_BAD_REQUEST,Re.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Lg(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function $g(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let f=s,h=0;for(;f!==o;)h+=n[f++],f=f%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const p=d&&c-d;return p?Math.round(h*1e3/p):void 0}}function Fg(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 No=(e,t,n=3)=>{let r=0;const o=$g(50,250);return Fg(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)},zl=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ul=e=>(...t)=>F.asap(()=>e(...t)),Bg=_t.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,_t.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(_t.origin),_t.navigator&&/(msie|trident)/i.test(_t.navigator.userAgent)):()=>!0,zg=_t.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];F.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),F.isString(r)&&i.push("path="+r),F.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 Ug(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Hg(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Hl(e,t,n){let r=!Ug(t);return e&&(r||n==!1)?Hg(e,t):t}const Wl=e=>e instanceof Ut?{...e}:e;function Kn(e,t){t=t||{};const n={};function r(c,d,f,h){return F.isPlainObject(c)&&F.isPlainObject(d)?F.merge.call({caseless:h},c,d):F.isPlainObject(d)?F.merge({},d):F.isArray(d)?d.slice():d}function o(c,d,f,h){if(F.isUndefined(d)){if(!F.isUndefined(c))return r(void 0,c,f,h)}else return r(c,d,f,h)}function s(c,d){if(!F.isUndefined(d))return r(void 0,d)}function i(c,d){if(F.isUndefined(d)){if(!F.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 F.forEach(Object.keys({...e,...t}),function(d){const f=l[d]||o,h=f(e[d],t[d],d);F.isUndefined(h)&&f!==a||(n[d]=h)}),n}const Vl=e=>{const t=Kn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=Ut.from(i),t.url=Pl(Hl(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),F.isFormData(n)){if(_t.hasStandardBrowserEnv||_t.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(F.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(_t.hasStandardBrowserEnv&&(r&&F.isFunction(r)&&(r=r(t)),r||r!==!1&&Bg(t.url))){const l=o&&s&&zg.read(s);l&&i.set(o,l)}return t},Wg=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=Vl(e);let s=o.data;const i=Ut.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,f,h,p,v;function x(){p&&p(),v&&v(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let y=new XMLHttpRequest;y.open(o.method.toUpperCase(),o.url,!0),y.timeout=o.timeout;function g(){if(!y)return;const T=Ut.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),S={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:T,config:e,request:y};Bl(function(E){n(E),x()},function(E){r(E),x()},S),y=null}"onloadend"in y?y.onloadend=g:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(g)},y.onabort=function(){y&&(r(new Re("Request aborted",Re.ECONNABORTED,e,y)),y=null)},y.onerror=function(k){const S=k&&k.message?k.message:"Network Error",C=new Re(S,Re.ERR_NETWORK,e,y);C.event=k||null,r(C),y=null},y.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const S=o.transitional||Dl;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new Re(k,S.clarifyTimeoutError?Re.ETIMEDOUT:Re.ECONNABORTED,e,y)),y=null},s===void 0&&i.setContentType(null),"setRequestHeader"in y&&F.forEach(i.toJSON(),function(k,S){y.setRequestHeader(S,k)}),F.isUndefined(o.withCredentials)||(y.withCredentials=!!o.withCredentials),a&&a!=="json"&&(y.responseType=o.responseType),c&&([h,v]=No(c,!0),y.addEventListener("progress",h)),l&&y.upload&&([f,p]=No(l),y.upload.addEventListener("progress",f),y.upload.addEventListener("loadend",p)),(o.cancelToken||o.signal)&&(d=T=>{y&&(r(!T||T.type?new dr(null,e,y):T),y.abort(),y=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const b=Lg(o.url);if(b&&_t.protocols.indexOf(b)===-1){r(new Re("Unsupported protocol "+b+":",Re.ERR_BAD_REQUEST,e));return}y.send(s||null)})},Vg=(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 Re?d:new dr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Re(`timeout ${t} of ms exceeded`,Re.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=()=>F.asap(a),l}},Kg=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},qg=async function*(e,t){for await(const n of Gg(e))yield*Kg(n,t)},Gg=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()}},Kl=(e,t,n,r)=>{const o=qg(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let f=d.byteLength;if(n){let h=s+=f;n(h)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},ql=64*1024,{isFunction:Ao}=F,Yg=(({Request:e,Response:t})=>({Request:e,Response:t}))(F.global),{ReadableStream:Gl,TextEncoder:Yl}=F.global,Xl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Xg=e=>{e=F.merge.call({skipUndefined:!0},Yg,e);const{fetch:t,Request:n,Response:r}=e,o=t?Ao(t):typeof fetch=="function",s=Ao(n),i=Ao(r);if(!o)return!1;const a=o&&Ao(Gl),l=o&&(typeof Yl=="function"?(v=>x=>v.encode(x))(new Yl):async v=>new Uint8Array(await new n(v).arrayBuffer())),c=s&&a&&Xl(()=>{let v=!1;const x=new n(_t.origin,{body:new Gl,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!x}),d=i&&a&&Xl(()=>F.isReadableStream(new r("").body)),f={stream:d&&(v=>v.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!f[v]&&(f[v]=(x,y)=>{let g=x&&x[v];if(g)return g.call(x);throw new Re(`Response type '${v}' is not supported`,Re.ERR_NOT_SUPPORT,y)})});const h=async v=>{if(v==null)return 0;if(F.isBlob(v))return v.size;if(F.isSpecCompliantForm(v))return(await new n(_t.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(F.isArrayBufferView(v)||F.isArrayBuffer(v))return v.byteLength;if(F.isURLSearchParams(v)&&(v=v+""),F.isString(v))return(await l(v)).byteLength},p=async(v,x)=>{const y=F.toFiniteNumber(v.getContentLength());return y??h(x)};return async v=>{let{url:x,method:y,data:g,signal:b,cancelToken:T,timeout:k,onDownloadProgress:S,onUploadProgress:C,responseType:E,headers:A,withCredentials:R="same-origin",fetchOptions:D}=Vl(v),B=t||fetch;E=E?(E+"").toLowerCase():"text";let Y=Vg([b,T&&T.toAbortSignal()],k),G=null;const M=Y&&Y.unsubscribe&&(()=>{Y.unsubscribe()});let j;try{if(C&&c&&y!=="get"&&y!=="head"&&(j=await p(A,g))!==0){let Z=new n(x,{method:"POST",body:g,duplex:"half"}),_;if(F.isFormData(g)&&(_=Z.headers.get("content-type"))&&A.setContentType(_),Z.body){const[Q,V]=zl(j,No(Ul(C)));g=Kl(Z.body,ql,Q,V)}}F.isString(R)||(R=R?"include":"omit");const I=s&&"credentials"in n.prototype,U={...D,signal:Y,method:y.toUpperCase(),headers:A.normalize().toJSON(),body:g,duplex:"half",credentials:I?R:void 0};G=s&&new n(x,U);let $=await(s?B(G,D):B(x,U));const P=d&&(E==="stream"||E==="response");if(d&&(S||P&&M)){const Z={};["status","statusText","headers"].forEach(H=>{Z[H]=$[H]});const _=F.toFiniteNumber($.headers.get("content-length")),[Q,V]=S&&zl(_,No(Ul(S),!0))||[];$=new r(Kl($.body,ql,Q,()=>{V&&V(),M&&M()}),Z)}E=E||"text";let q=await f[F.findKey(f,E)||"text"]($,v);return!P&&M&&M(),await new Promise((Z,_)=>{Bl(Z,_,{data:q,headers:Ut.from($.headers),status:$.status,statusText:$.statusText,config:v,request:G})})}catch(I){throw M&&M(),I&&I.name==="TypeError"&&/Load failed|fetch/i.test(I.message)?Object.assign(new Re("Network Error",Re.ERR_NETWORK,v,G),{cause:I.cause||I}):Re.from(I,I&&I.code,v,G)}}},Jg=new Map,Jl=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=Jg;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:Xg(t)),d=c;return c};Jl();const gi={http:vg,xhr:Wg,fetch:{get:Jl}};F.forEach(gi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Zl=e=>`- ${e}`,Zg=e=>F.isFunction(e)||e===null||e===!1,Ql={getAdapter:(e,t)=>{e=F.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,!Zg(r)&&(o=gi[(a=String(r)).toLowerCase()],o===void 0))throw new Re(`Unknown adapter '${a}'`);if(o&&(F.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(Zl).join(`
34
34
  `):" "+Zl(i[0]):"as no adapter specified";throw new Re("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:gi};function xi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new dr(null,e)}function ec(e){return xi(e),e.headers=Ut.from(e.headers),e.data=mi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Ql.getAdapter(e.adapter||Dr.adapter,e)(e).then(function(r){return xi(e),r.data=mi.call(e,e.transformResponse,r),r.headers=Ut.from(r.headers),r},function(r){return Fl(r)||(xi(e),r&&r.response&&(r.response.data=mi.call(e,e.transformResponse,r.response),r.response.headers=Ut.from(r.response.headers))),Promise.reject(r)})}const tc="1.12.2",jo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{jo[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const nc={};jo.transitional=function(t,n,r){function o(s,i){return"[Axios v"+tc+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Re(o(i," has been removed"+(n?" in "+n:"")),Re.ERR_DEPRECATED);return n&&!nc[i]&&(nc[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}},jo.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Qg(e,t,n){if(typeof e!="object")throw new Re("options must be an object",Re.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 Re("option "+s+" must be "+l,Re.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Re("Unknown option "+s,Re.ERR_BAD_OPTION)}}const _o={assertOptions:Qg,validators:jo},hn=_o.validators;let qn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ol,response:new Ol}}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=Kn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&_o.assertOptions(r,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),o!=null&&(F.isFunction(o)?n.paramsSerializer={serialize:o}:_o.assertOptions(o,{encode:hn.function,serialize:hn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),_o.assertOptions(n,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&F.merge(s.common,s[n.method]);s&&F.forEach(["delete","get","head","post","put","patch","common"],v=>{delete s[v]}),n.headers=Ut.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(l=l&&x.synchronous,a.unshift(x.fulfilled,x.rejected))});const c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let d,f=0,h;if(!l){const v=[ec.bind(this),void 0];for(v.unshift(...a),v.push(...c),h=v.length,d=Promise.resolve(n);f<h;)d=d.then(v[f++],v[f++]);return d}h=a.length;let p=n;for(;f<h;){const v=a[f++],x=a[f++];try{p=v(p)}catch(y){x.call(this,y);break}}try{d=ec.call(this,p)}catch(v){return Promise.reject(v)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Kn(this.defaults,t);const n=Hl(t.baseURL,t.url,t.allowAbsoluteUrls);return Pl(n,t.params,t.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(t){qn.prototype[t]=function(n,r){return this.request(Kn(r||{},{method:t,url:n,data:(r||{}).data}))}}),F.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Kn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}qn.prototype[t]=n(),qn.prototype[t+"Form"]=n(!0)});let ex=class jm{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 dr(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 jm(function(o){t=o}),cancel:t}}};function tx(e){return function(n){return e.apply(null,n)}}function nx(e){return F.isObject(e)&&e.isAxiosError===!0}const yi={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(yi).forEach(([e,t])=>{yi[t]=e});function rc(e){const t=new qn(e),n=vl(qn.prototype.request,t);return F.extend(n,qn.prototype,t,{allOwnKeys:!0}),F.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return rc(Kn(e,o))},n}const yt=rc(Dr);yt.Axios=qn,yt.CanceledError=dr,yt.CancelToken=ex,yt.isCancel=Fl,yt.VERSION=tc,yt.toFormData=Eo,yt.AxiosError=Re,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=tx,yt.isAxiosError=nx,yt.mergeConfig=Kn,yt.AxiosHeaders=Ut,yt.formToJSON=e=>Ll(F.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Ql.getAdapter,yt.HttpStatusCode=yi,yt.default=yt;const{Axios:aE,AxiosError:lE,CanceledError:cE,isCancel:uE,CancelToken:dE,VERSION:fE,all:hE,Cancel:pE,isAxiosError:mE,spread:gE,toFormData:xE,AxiosHeaders:yE,HttpStatusCode:vE,formToJSON:bE,getAdapter:wE,mergeConfig:SE}=yt,oc=typeof window<"u"?window.__API_BASE_URL__:void 0,sc=oc?Cn(oc):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 Mo=null;const vi=new Set;function ic(){return Mo}function Ro(e){Mo=e,vi.forEach(t=>t(e))}function ac(e){return vi.add(e),()=>vi.delete(e)}const rx=3e4,ox=9e4,Ht=yt.create({...sc?{baseURL:sc}:{},timeout:rx,withCredentials:!0});Ht.interceptors.request.use(e=>(Mo&&(e.headers.Authorization=`Bearer ${Mo}`),e)),Ht.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),Ro(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 Wt(e,t){return Ht.defaults.baseURL?(await Ht.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Po(e,t,n){return Ht.defaults.baseURL?(await Ht.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function lc(e,t,n){return Ht.defaults.baseURL?(await Ht.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function bi(e,t){return Ht.defaults.baseURL?(await Ht.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Mt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class cc{get baseUrl(){const t=Ht.defaults.baseURL;return t?Cn(String(t)):""}updateConfig(t){t.baseUrl&&(Ht.defaults.baseURL=Cn(String(t.baseUrl))),t.authToken!==void 0&&Ro(t.authToken)}getAuthToken(){return ic()}setAuthToken(t){Ro(t)}onTokenChange(t){return ac(t)}async listThreads(){const t=await Wt("/threads"),n=Mt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await Wt("/threads/shared"),n=Mt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSmartOrgUsers(){const t=Ht.defaults.baseURL?Ht.defaults.baseURL.replace(/\/chat\/?$/,""):"/api",n=await Wt("/auth/users",{baseURL:t}),r=Mt(n);return(r==null?void 0:r.users)??[]}async createThread(t){const r=await Po("/threads",t?{title:t}:void 0);return Mt(r)}async updateThread(t,n){const r=await lc(`/threads/${t}`,{title:n});return Mt(r)}async deleteThread(t){const n=await bi(`/threads/${t}`);return Mt(n)}async shareThread(t,n){const r=await Po(`/threads/${t}/share`,{shared_with_user_id:n});return Mt(r)}async threadInfo(t){const n=await Wt(`/threads/${t}/info`);return Mt(n)}async listAgents(){const t=await Wt("/agents"),n=Mt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Wt(`/agents/${t}`);return Mt(n)}async getAgentSchema(t){const n=await Wt(`/agents/${t}/schema`);return Mt(n)}async getState(t){const n=await Wt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Mt(n)}async getStateHistory(t){const n=await Wt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:ox});return Mt(n)}async cancelRun(t){const n=await Po("/runs/cancel",{threadId:t});return Mt(n)}async listCheckpointSummaries(t){const n=await Wt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Mt(n);return(r==null?void 0:r.items)??[]}async unshareThread(t,n){const r=await bi(`/threads/${t}/share/${n}`);return Mt(r)}}const Nn=new cc,uc=w.createContext(null);function sx({children:e,apiConfig:t}){const n=Nn;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(uc.Provider,{value:r,children:e})}function wi(){const e=w.useContext(uc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function ix(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 ax(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await ix(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const dc=120;function lx(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>dc?`${n.slice(0,dc-3)}…`:n:""}function fc(e){return lx(e.content)||""}function cx(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=fc(n);r&&t.set(n.id,r)}return t}function ux(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=fc(o);s&&t.set(r.checkpointId,s)}}return t}const dx={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Si(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 fx(e,t){return`${e??""}::${t??""}`}function fr(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(!Si(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=px(t),i=hc(r,0),a=mx(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function hc(e,t){if(!Si(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(R=>!!R&&typeof R=="object").map(R=>({...R})):a===null?null:void 0,c=r.map((R,D)=>Tx(R,D)).filter(R=>!!R),d=Lt(e.config),f=Lt(d==null?void 0:d.configurable),h=dt(f,["checkpoint_id","checkpointId"]),p=dt(f,["checkpoint_ns","checkpointNs"]),v=Lt(e==null?void 0:e.parentConfig),x=Lt(v==null?void 0:v.configurable),y=dt(x,["checkpoint_id","checkpointId"])??null,g=dt(x,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,T=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(R=>R.role==="user")??null,S=Lt(e==null?void 0:e.metadata),C=dt(S,["branch_label","branchLabel"]),E=dt(x,["checkpoint_id","checkpointId"]),A=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:y,nextCursorNs:g,interrupt:hx(a,c,t),createdAt:T,parentId:E??null,branchLabel:C??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:S??null,config:d??null,parentConfig:v??null,next:A??null,tasks:l??null,values:i??null}}function hx(e,t,n){const r=Sx(e,n);return r||wx(t,n)}function px(e){const t=new Map;e.forEach((o,s)=>{if(!Si(o))return;const i=hc(o,s);if(!(i!=null&&i.checkpointId))return;const a=fx(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,yx(l,i))});const n=Array.from(t.values());n.sort((o,s)=>mc(s.createdAt??"")-mc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function mx(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=xx(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,h=o.lastUserMessageId??f,p=gx(o.next);t.push({id:s,label:a,messageId:h,step:l,source:c??null,createdAt:d,next:p??void 0,parentConfig:o.parentConfig??null})}return t}function gx(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 xx(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 yx(e,t){return{...e,metadata:Oo(e.metadata,t.metadata)??null,config:Oo(e.config,t.config)??null,parentConfig:Oo(e.parentConfig,t.parentConfig)??null,next:vx(e.next,t.next)??null,tasks:bx(e.tasks,t.tasks)??null,values:Oo(e.values,t.values)??null}}function Oo(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 vx(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 bx(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 wx(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 Sx(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Cx(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=$r(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=$r(r.state,`${o}-state`);if(s)return s}}return null}function Cx(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,v=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",x=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:v,interrupts:x,state:y!==void 0?y:f}}const n=Lt(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 $r(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=pc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=$r(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=$r(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=$r(l,t,n+1,r);if(c)return c}}return null}function pc(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=pc(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 mc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Tx(e,t){if(!e||typeof e!="object")return null;const n=e,r=Lt(e)??{},o=Lt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=dx[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=Lt(o.additional_kwargs)??Lt(o.additionalKwargs),d=Lt(o.response_metadata)??Lt(o.responseMetadata),f=dt(c,["createdAt","created_at"])??dt(o,["created_at","createdAt"]),h=dt(c,["checkpointId","checkpoint_id"]),p=dt(c,["checkpointNs","checkpoint_ns"]),v=kx(o.content),x={id:l,role:i,content:v};f&&(x.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(x.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(x.model=String(d.model_name)),!x.model&&typeof o.model=="string"&&(x.model=o.model),h&&(x.checkpointId=h),p&&(x.checkpointNs=p);const y=Nx(Lt(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(x.artifact=y);const g=Mx(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),b=d?{...d}:void 0;g&&Object.keys(g).length&&(x.additionalKwargs=g),b&&Object.keys(b).length&&(x.responseMetadata=b);const T=Ex((c==null?void 0:c.tool_calls)??o.tool_calls);if(T.length&&(x.content=[...x.content,...T]),i==="tool"){const k=Ix(o,x.content);k&&(x.content=k)}return x}function kx(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>gc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=gc(e);return t?[t]:[]}return[]}function gc(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 xc(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 xc(e,t){var s;const n=dt(e,["id","call_id"])??t,r=dt(e,["name"])??dt(Lt(e.function),["name"]);if(!n||!r)return null;const o=_x(e.args??e.arguments??((s=Lt(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Ex(e){return Array.isArray(e)?e.map((t,n)=>xc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ix(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 Nx(e){return e?{plots:Ax(e.plots)}:void 0}function Ax(e){return Array.isArray(e)?e.map(t=>jx(t)).filter(t=>!!t):[]}function jx(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 _x(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 Lt(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 Mx(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 yc="aiNav:tool-progress";function Ci(){return typeof window<"u"&&typeof window.localStorage<"u"}function vc(e){return`${yc}:${e}`}function Rx(e,t,n){if(!Ci()||!e)return;const r=vc(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 Px(e){if(!Ci()||!e)return;const t=vc(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 bc(){if(!Ci())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(yc)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const It=[];for(let e=0;e<256;++e)It.push((e+256).toString(16).slice(1));function Ox(e,t=0){return(It[e[t+0]]+It[e[t+1]]+It[e[t+2]]+It[e[t+3]]+"-"+It[e[t+4]]+It[e[t+5]]+"-"+It[e[t+6]]+It[e[t+7]]+"-"+It[e[t+8]]+It[e[t+9]]+"-"+It[e[t+10]]+It[e[t+11]]+It[e[t+12]]+It[e[t+13]]+It[e[t+14]]+It[e[t+15]]).toLowerCase()}let Ti;const Dx=new Uint8Array(16);function Lx(){if(!Ti){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ti=crypto.getRandomValues.bind(crypto)}return Ti(Dx)}const wc={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function $x(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??Lx();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,Ox(r)}function Fx(e,t,n){return wc.randomUUID&&!e?wc.randomUUID():$x(e)}function ki(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 Do(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Sc(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 Cc(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 Bx(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=qx(e);for(const o of r)n.add(o);return Array.from(n)}function kc(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 zx(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 Lo(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:Fx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),Rx(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function Ec(e,t){return e.includes(t)?e:[...e,t]}function Ux(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function hr(e,t){let n=!1;const r={},o=e.map(s=>{const i=Gx(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??Px(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 Hx(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=Wx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",v={...h,text:p+l};c=[...c.slice(0,c.length-1),v]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function Nc(e){return e.replace(/\s+/g," ").trim()}function Wx(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=Nc(e),o=Nc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function Vx(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 Do(e,r,s)}return e}function Kx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function qx(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 Gx(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}const Yx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function Xx(e,t){var n;switch(t.type){case"reset":return{messages:ki(((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=ki(t.payload.messages),{messages:o,toolTimelines:s}=hr(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=ki(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}=hr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"event":return jc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>jc(o,s),e):e}case"interrupt_response":return{...e,messages:Sc(e.messages),pendingInterrupt:null};default:return e}}function Ac(e=[]){const[t,n]=w.useReducer(Xx,{...Yx,messages:e}),r=w.useRef([]),o=w.useRef(null),s=w.useRef(null),i=w.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=w.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=w.useCallback(d=>{r.current.push(d),a()},[a]);w.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=w.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function jc(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=Kx(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??Cc(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(T=>T.id===i&&T.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:Ic(c.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof f.lastSeq=="number"&&h<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:f.lastSeq}),e;const{newParts:p,newMeta:v,changed:x}=Hx(c.content,t.delta,f,h);if(!x)return e;const y={...c,content:p},g=Do(a,l,y),b={...d,[i]:v};return{...e,messages:g,messagesStreamMeta:b}}if(t.type==="message.end"){const i=e.assemblingId??Cc(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 h;return(f==null?void 0:f.type)==="text"&&((h=f.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=c.content)==null?void 0:o.map(h=>(h==null?void 0:h.type)==="text"?String(h.text).slice(0,100):h==null?void 0:h.type)});const 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},h={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},p=e.toolStreamingMessageId;if(!p){const b={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...zx(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},T=Bx(b,c.length?c:[d]),k=[...e.messages,b],S=Lo(k,b.id,h),{messages:C,toolTimelines:E}=hr(S,e.toolTimelines);return{...e,messages:C,toolIndex:kc(e.toolIndex,b.id,T),toolStreamingMessageId:b.id,toolStreamingStack:Ec(e.toolStreamingStack??[],a??d),toolTimelines:E}}const v=Lo(e.messages,p,h),{messages:x,toolTimelines:y}=hr(v,e.toolTimelines);return{...e,messages:x,toolIndex:kc(e.toolIndex,p,c),toolStreamingStack:Ec(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=Ux(l,a),f=d[0]?e.toolIndex[d[0]]:null,h=e.toolStreamingMessageId,p=c===a,v=t.name??((s=e.messages.find(S=>S.id===h))==null?void 0:s.name)??"tool",x=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),y={type:"tool.end",toolId:a,toolName:v,content:x==null?void 0:x.slice(0,200)};let g=e.messages;if(h&&(g=Lo(g,h,y)),p&&h){const S=g.findIndex(C=>C.id===h);if(S>=0){const C=g[S],A={type:"text",text:(()=>{if(typeof t.output=="string"){const D=t.output.trim();try{return D}catch{return D}}return JSON.stringify(t.output??"")})()},R={...C,content:[A],artifact:t.artifact??C.artifact,additionalKwargs:{...C.additionalKwargs??{}}};g=Do(g,S,R)}}const b=d,{messages:T,toolTimelines:k}=hr(g,e.toolTimelines);return{...e,messages:T,toolTimelines:k,toolStreamingMessageId:p?f:h,toolStreamingStack:b}}if(t.type==="tool.progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"tool.progress",content:t.content??null},l=Lo(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},h={...d,additionalKwargs:f},p=Do(l,c,h),{messages:v,toolTimelines:x}=hr(p,e.toolTimelines);return{...e,messages:v,toolTimelines:x}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=Vx(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=fr(t),a=i.interrupt,l=i.latest,c=a===null?Sc(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 _c(e={}){const t=w.useMemo(()=>Cn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,h]=w.useState(""),[p,v]=w.useState(null),[x,y]=w.useState(0),[g,b]=w.useState(!1),T=w.useRef(null),k=w.useRef(!0),S=w.useRef(0),C=w.useRef(null),E=w.useRef(null),A=w.useRef(null),R=w.useRef(null),D=w.useCallback(M=>{o(M)},[]),B=w.useCallback(()=>{h(""),v(null),d(null),E.current=null,A.current=null,R.current=null},[]),Y=w.useCallback(()=>{var M;console.debug("[use-chat] stop() invoked - aborting stream"),(M=T.current)==null||M.abort(),T.current=null,C.current=null,l(!1),b(!1),S.current=0,y(0)},[]),G=w.useCallback((M,j,I)=>{T.current&&(T.current.abort(),T.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),v(null),E.current=null,A.current=null,R.current=null;const U=new AbortController;T.current=U;let $=null,P=null,q=!1;return C.current={threadId:M.threadId??null,headers:{}},(async()=>{var _,Q,V,H,ne,W,O,K,z,te,X,ge,le,oe,me,be,Me,Ce;const Z=Ue=>{var et;try{const rt=JSON.parse(JSON.stringify(Ue));return(et=rt==null?void 0:rt.payload)!=null&&et.files_info&&Array.isArray(rt.payload.files_info)&&(rt.payload.files_info=rt.payload.files_info.map(Ke=>({...Ke,data:Ke!=null&&Ke.data?`<base64 ${String(Ke.data).length} chars>`:Ke==null?void 0:Ke.data}))),rt}catch{return Ue}};try{let Ue={};try{if(r)Ue={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const He=window.__AUTH_TOKEN__,ut=((_=window.localStorage)==null?void 0:_.getItem("authToken"))||null;let kt=null;try{const J=(Q=window.localStorage)==null?void 0:Q.getItem("chat-settings");J&&(kt=((V=JSON.parse(J))==null?void 0:V.apiKey)||null)}catch{}const qe=He||ut||kt||null;qe&&(Ue={Authorization:`Bearer ${qe}`})}}catch{}console.debug("[use-chat] POST",t+n,Z(M));let et={};if(typeof window<"u")try{const Ye=(H=window.localStorage)==null?void 0:H.getItem("authSessionId");Ye&&(et={"X-Session-Id":Ye})}catch{}const rt={...Ue,...et,...s.current},Ke={"Content-Type":"application/json",Accept:"text/event-stream",...rt},Ge=await fetch(t+n,{method:"POST",headers:Ke,body:JSON.stringify(M),signal:U.signal,credentials:i});if(C.current&&(C.current.headers=rt),!Ge.ok||!Ge.body){const Ye=await Ge.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ge.status,Ye==null?void 0:Ye.slice(0,500));const He=`stream ${Ge.status}${Ye?": "+Ye:""}`;throw(ne=I==null?void 0:I.onConnectionError)==null||ne.call(I,He),q=!0,$="error",P=He,new Error(He)}b(!0);const at=Ge.body.getReader(),bt=new TextDecoder;let ht="",Tt=[];S.current=0,y(0);let Ie=0,Fe=null;const pt=()=>{if(Tt.length){const Ye=Tt.join("");Tt=[],k.current&&h(He=>He+Ye)}Fe=null},wt=()=>{typeof window<"u"&&Fe==null&&(Fe=requestAnimationFrame(pt))};let Dt=Date.now();const Pe=setInterval(()=>{var Ye;if(Date.now()-Dt>18e5){const He="Stream idle timeout";d(He),$="error",P=He,U.abort(),(Ye=I==null?void 0:I.onError)==null||Ye.call(I,He)}},5e3),qt=1024*1024;try{const Ye=Ge.headers.get("X-Thread-Id")||Ge.headers.get("x-thread-id"),He=Ge.headers.get("X-Thread-Created")||Ge.headers.get("x-thread-created"),ut=Ye??null,kt=String(He??"").toLowerCase()==="true";for(C.current&&!C.current.threadId&&(C.current={...C.current,threadId:ut}),(W=I==null?void 0:I.onOpen)==null||W.call(I,{threadId:ut,created:kt});;){const{value:qe,done:J}=await at.read();if(J)break;ht+=bt.decode(qe,{stream:!0}),ht.length>qt&&(ht="",console.warn("Stream buffer reset: exceeded 1MB"));let L;for(;(L=ht.indexOf(`
35
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Kn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&_o.assertOptions(r,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),o!=null&&(F.isFunction(o)?n.paramsSerializer={serialize:o}:_o.assertOptions(o,{encode:hn.function,serialize:hn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),_o.assertOptions(n,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&F.merge(s.common,s[n.method]);s&&F.forEach(["delete","get","head","post","put","patch","common"],v=>{delete s[v]}),n.headers=Ut.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(l=l&&x.synchronous,a.unshift(x.fulfilled,x.rejected))});const c=[];this.interceptors.response.forEach(function(x){c.push(x.fulfilled,x.rejected)});let d,f=0,h;if(!l){const v=[ec.bind(this),void 0];for(v.unshift(...a),v.push(...c),h=v.length,d=Promise.resolve(n);f<h;)d=d.then(v[f++],v[f++]);return d}h=a.length;let p=n;for(;f<h;){const v=a[f++],x=a[f++];try{p=v(p)}catch(y){x.call(this,y);break}}try{d=ec.call(this,p)}catch(v){return Promise.reject(v)}for(f=0,h=c.length;f<h;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=Kn(this.defaults,t);const n=Hl(t.baseURL,t.url,t.allowAbsoluteUrls);return Pl(n,t.params,t.paramsSerializer)}};F.forEach(["delete","get","head","options"],function(t){qn.prototype[t]=function(n,r){return this.request(Kn(r||{},{method:t,url:n,data:(r||{}).data}))}}),F.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(Kn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}qn.prototype[t]=n(),qn.prototype[t+"Form"]=n(!0)});let ex=class jm{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 dr(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 jm(function(o){t=o}),cancel:t}}};function tx(e){return function(n){return e.apply(null,n)}}function nx(e){return F.isObject(e)&&e.isAxiosError===!0}const yi={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(yi).forEach(([e,t])=>{yi[t]=e});function rc(e){const t=new qn(e),n=vl(qn.prototype.request,t);return F.extend(n,qn.prototype,t,{allOwnKeys:!0}),F.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return rc(Kn(e,o))},n}const yt=rc(Dr);yt.Axios=qn,yt.CanceledError=dr,yt.CancelToken=ex,yt.isCancel=Fl,yt.VERSION=tc,yt.toFormData=Eo,yt.AxiosError=Re,yt.Cancel=yt.CanceledError,yt.all=function(t){return Promise.all(t)},yt.spread=tx,yt.isAxiosError=nx,yt.mergeConfig=Kn,yt.AxiosHeaders=Ut,yt.formToJSON=e=>Ll(F.isHTMLForm(e)?new FormData(e):e),yt.getAdapter=Ql.getAdapter,yt.HttpStatusCode=yi,yt.default=yt;const{Axios:aE,AxiosError:lE,CanceledError:cE,isCancel:uE,CancelToken:dE,VERSION:fE,all:hE,Cancel:pE,isAxiosError:mE,spread:gE,toFormData:xE,AxiosHeaders:yE,HttpStatusCode:vE,formToJSON:bE,getAdapter:wE,mergeConfig:SE}=yt,oc=typeof window<"u"?window.__API_BASE_URL__:void 0,sc=oc?Cn(oc):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 Mo=null;const vi=new Set;function ic(){return Mo}function Ro(e){Mo=e,vi.forEach(t=>t(e))}function ac(e){return vi.add(e),()=>vi.delete(e)}const rx=3e4,ox=9e4,Ht=yt.create({...sc?{baseURL:sc}:{},timeout:rx,withCredentials:!0});Ht.interceptors.request.use(e=>(Mo&&(e.headers.Authorization=`Bearer ${Mo}`),e)),Ht.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),Ro(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 Wt(e,t){return Ht.defaults.baseURL?(await Ht.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Po(e,t,n){return Ht.defaults.baseURL?(await Ht.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function lc(e,t,n){return Ht.defaults.baseURL?(await Ht.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function bi(e,t){return Ht.defaults.baseURL?(await Ht.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Mt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class cc{get baseUrl(){const t=Ht.defaults.baseURL;return t?Cn(String(t)):""}updateConfig(t){t.baseUrl&&(Ht.defaults.baseURL=Cn(String(t.baseUrl))),t.authToken!==void 0&&Ro(t.authToken)}getAuthToken(){return ic()}setAuthToken(t){Ro(t)}onTokenChange(t){return ac(t)}async listThreads(){const t=await Wt("/threads"),n=Mt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await Wt("/threads/shared"),n=Mt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSmartOrgUsers(){const t=Ht.defaults.baseURL?Ht.defaults.baseURL.replace(/\/chat\/?$/,""):"/api",n=await Wt("/auth/users",{baseURL:t}),r=Mt(n);return(r==null?void 0:r.users)??[]}async createThread(t){const r=await Po("/threads",t?{title:t}:void 0);return Mt(r)}async updateThread(t,n){const r=await lc(`/threads/${t}`,{title:n});return Mt(r)}async deleteThread(t){const n=await bi(`/threads/${t}`);return Mt(n)}async shareThread(t,n){const r=await Po(`/threads/${t}/share`,{shared_with_user_id:n});return Mt(r)}async threadInfo(t){const n=await Wt(`/threads/${t}/info`);return Mt(n)}async listAgents(){const t=await Wt("/agents"),n=Mt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await Wt(`/agents/${t}`);return Mt(n)}async getAgentSchema(t){const n=await Wt(`/agents/${t}/schema`);return Mt(n)}async getState(t){const n=await Wt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Mt(n)}async getStateHistory(t){const n=await Wt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:ox});return Mt(n)}async cancelRun(t){const n=await Po("/runs/cancel",{threadId:t});return Mt(n)}async listCheckpointSummaries(t){const n=await Wt(`/threads/${t}/state/checkpoints`,{params:{thread_id:t}}),r=Mt(n);return(r==null?void 0:r.items)??[]}async unshareThread(t,n){const r=await bi(`/threads/${t}/share/${n}`);return Mt(r)}}const Nn=new cc,uc=w.createContext(null);function sx({children:e,apiConfig:t}){const n=Nn;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(uc.Provider,{value:r,children:e})}function wi(){const e=w.useContext(uc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function ix(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 ax(e,t=[],n,r,o,s){const i=[],a=[];for(const l of t)try{const c=await ix(l);a.push({filename:l.name,data:c,mime_type:l.type||"application/octet-stream"})}catch{}return{contentParts:i,filesInfo:a}}const dc=120;function lx(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>dc?`${n.slice(0,dc-3)}…`:n:""}function fc(e){return lx(e.content)||""}function cx(e){const t=new Map;for(const n of e){if(!n.id||n.role!=="user")continue;const r=fc(n);r&&t.set(n.id,r)}return t}function ux(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=fc(o);s&&t.set(r.checkpointId,s)}}return t}const dx={human:"user",user:"user",ai:"assistant",assistant:"assistant",tool:"tool",function:"tool",system:"system"};function Si(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 fx(e,t){return`${e??""}::${t??""}`}function fr(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(!Si(r))return{threadId:n,latest:null,checkpoints:[],timeline:[],interrupt:null,snapshots:{}};const{orderedSnapshots:o,snapshotMap:s}=px(t),i=hc(r,0),a=mx(o);return{threadId:n,latest:i,checkpoints:o,timeline:a,interrupt:(i==null?void 0:i.interrupt)??null,snapshots:s}}function hc(e,t){if(!Si(e))return null;const n=e.values??{messages:[]},r=Array.isArray(n==null?void 0:n.messages)?n.messages:[],{messages:o,...s}=n,i=Object.keys(s).length?s:null,a=e.tasks,l=Array.isArray(a)?a.filter(R=>!!R&&typeof R=="object").map(R=>({...R})):a===null?null:void 0,c=r.map((R,D)=>Tx(R,D)).filter(R=>!!R),d=Lt(e.config),f=Lt(d==null?void 0:d.configurable),h=dt(f,["checkpoint_id","checkpointId"]),p=dt(f,["checkpoint_ns","checkpointNs"]),v=Lt(e==null?void 0:e.parentConfig),x=Lt(v==null?void 0:v.configurable),y=dt(x,["checkpoint_id","checkpointId"])??null,g=dt(x,["checkpoint_ns","checkpointNs"])??null,b=e==null?void 0:e.createdAt,T=typeof b=="string"&&b.trim()?b:new Date(Date.now()-t).toISOString(),k=c.slice().reverse().find(R=>R.role==="user")??null,S=Lt(e==null?void 0:e.metadata),C=dt(S,["branch_label","branchLabel"]),E=dt(x,["checkpoint_id","checkpointId"]),A=Array.isArray(e.next)?[...e.next]:(e==null?void 0:e.next)===null?null:void 0;return{messages:c,checkpointId:h??null,checkpointNs:p??null,nextCursor:y,nextCursorNs:g,interrupt:hx(a,c,t),createdAt:T,parentId:E??null,branchLabel:C??null,lastUserMessageId:(k==null?void 0:k.id)??null,hasMessages:c.length>0,messagesLen:c.length,metadata:S??null,config:d??null,parentConfig:v??null,next:A??null,tasks:l??null,values:i??null}}function hx(e,t,n){const r=Sx(e,n);return r||wx(t,n)}function px(e){const t=new Map;e.forEach((o,s)=>{if(!Si(o))return;const i=hc(o,s);if(!(i!=null&&i.checkpointId))return;const a=fx(i.checkpointId,i.checkpointNs??null),l=t.get(a);if(!l){t.set(a,i);return}t.set(a,yx(l,i))});const n=Array.from(t.values());n.sort((o,s)=>mc(s.createdAt??"")-mc(o.createdAt??""));const r={};for(const[o,s]of t.entries())r[o]=s;return{orderedSnapshots:n,snapshotMap:r}}function mx(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=xx(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,h=o.lastUserMessageId??f,p=gx(o.next);t.push({id:s,label:a,messageId:h,step:l,source:c??null,createdAt:d,next:p??void 0,parentConfig:o.parentConfig??null})}return t}function gx(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 xx(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 yx(e,t){return{...e,metadata:Oo(e.metadata,t.metadata)??null,config:Oo(e.config,t.config)??null,parentConfig:Oo(e.parentConfig,t.parentConfig)??null,next:vx(e.next,t.next)??null,tasks:bx(e.tasks,t.tasks)??null,values:Oo(e.values,t.values)??null}}function Oo(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 vx(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 bx(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 wx(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 Sx(e,t){if(!Array.isArray(e)||!e.length)return null;for(let n=e.length-1;n>=0;n--){const r=Cx(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=$r(r.interrupts[s],`${o}-interrupt-${s}`);if(i)return i}if(r.state!==void 0&&r.state!==null){const s=$r(r.state,`${o}-state`);if(s)return s}}return null}function Cx(e,t){if(!e)return null;if(Array.isArray(e)){const[a,l,c,,d,,f,...h]=e,p=typeof a=="string"&&a.trim()?a:t,v=typeof l=="string"&&l.trim()?l:Array.isArray(c)&&typeof c[0]=="string"?String(c[0]):"task",x=Array.isArray(d)?d:void 0,y=h.length?h[h.length-1]:void 0;return{id:p,name:v,interrupts:x,state:y!==void 0?y:f}}const n=Lt(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 $r(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=pc(e,t);if(o)return o;if(Array.isArray(e)){for(let s=e.length-1;s>=0;s--){const i=$r(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=$r(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=$r(l,t,n+1,r);if(c)return c}}return null}function pc(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=pc(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 mc(e){if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0}function Tx(e,t){if(!e||typeof e!="object")return null;const n=e,r=Lt(e)??{},o=Lt(n.data)??r,s=String(n.type??o.type??o.role??"").toLowerCase(),i=dx[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=Lt(o.additional_kwargs)??Lt(o.additionalKwargs),d=Lt(o.response_metadata)??Lt(o.responseMetadata),f=dt(c,["createdAt","created_at"])??dt(o,["created_at","createdAt"]),h=dt(c,["checkpointId","checkpoint_id"]),p=dt(c,["checkpointNs","checkpoint_ns"]),v=kx(o.content),x={id:l,role:i,content:v};f&&(x.createdAt=f),typeof o.name=="string"&&o.name.trim()&&(x.name=o.name),typeof(d==null?void 0:d.model_name)=="string"&&(x.model=String(d.model_name)),!x.model&&typeof o.model=="string"&&(x.model=o.model),h&&(x.checkpointId=h),p&&(x.checkpointNs=p);const y=Nx(Lt(o.artifact??r.artifact??o.artifacts??r.artifacts));y&&(x.artifact=y);const g=Mx(c,["createdAt","created_at","checkpointId","checkpoint_id","checkpointNs","checkpoint_ns","tool_calls"]),b=d?{...d}:void 0;g&&Object.keys(g).length&&(x.additionalKwargs=g),b&&Object.keys(b).length&&(x.responseMetadata=b);const T=Ex((c==null?void 0:c.tool_calls)??o.tool_calls);if(T.length&&(x.content=[...x.content,...T]),i==="tool"){const k=Ix(o,x.content);k&&(x.content=k)}return x}function kx(e){if(!e)return[];if(Array.isArray(e))return e.map(t=>gc(t)).filter(t=>!!t);if(typeof e=="string")return e.trim()?[{type:"text",text:e.trim()}]:[];if(typeof e=="object"){const t=gc(e);return t?[t]:[]}return[]}function gc(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 xc(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 xc(e,t){var s;const n=dt(e,["id","call_id"])??t,r=dt(e,["name"])??dt(Lt(e.function),["name"]);if(!n||!r)return null;const o=_x(e.args??e.arguments??((s=Lt(e.function))==null?void 0:s.arguments));return{type:"tool_call",id:n,name:r,args:o}}function Ex(e){return Array.isArray(e)?e.map((t,n)=>xc(t,`tool_call_${n}`)).filter(t=>!!t):[]}function Ix(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 Nx(e){return e?{plots:Ax(e.plots)}:void 0}function Ax(e){return Array.isArray(e)?e.map(t=>jx(t)).filter(t=>!!t):[]}function jx(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 _x(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 Lt(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 Mx(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 yc="aiNav:tool-progress";function Ci(){return typeof window<"u"&&typeof window.localStorage<"u"}function vc(e){return`${yc}:${e}`}function Rx(e,t,n){if(!Ci()||!e)return;const r=vc(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 Px(e){if(!Ci()||!e)return;const t=vc(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 bc(){if(!Ci())return;const e=[];for(let t=0;t<window.localStorage.length;t+=1){const n=window.localStorage.key(t);n!=null&&n.startsWith(yc)&&e.push(n)}for(const t of e)window.localStorage.removeItem(t)}const It=[];for(let e=0;e<256;++e)It.push((e+256).toString(16).slice(1));function Ox(e,t=0){return(It[e[t+0]]+It[e[t+1]]+It[e[t+2]]+It[e[t+3]]+"-"+It[e[t+4]]+It[e[t+5]]+"-"+It[e[t+6]]+It[e[t+7]]+"-"+It[e[t+8]]+It[e[t+9]]+"-"+It[e[t+10]]+It[e[t+11]]+It[e[t+12]]+It[e[t+13]]+It[e[t+14]]+It[e[t+15]]).toLowerCase()}let Ti;const Dx=new Uint8Array(16);function Lx(){if(!Ti){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ti=crypto.getRandomValues.bind(crypto)}return Ti(Dx)}const wc={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function $x(e,t,n){var o;e=e||{};const r=e.random??((o=e.rng)==null?void 0:o.call(e))??Lx();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,Ox(r)}function Fx(e,t,n){return wc.randomUUID&&!e?wc.randomUUID():$x(e)}function ki(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 Do(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function Sc(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 Cc(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 Bx(e,t){const n=new Set;for(const o of t)typeof o=="string"&&o.trim()&&n.add(o.trim());const r=qx(e);for(const o of r)n.add(o);return Array.from(n)}function kc(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 zx(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 Lo(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:Fx(),idx:a.length+1,timestamp:new Date().toISOString(),...n};return a.push(l),Rx(o.id,a,{checkpointId:o.checkpointId??null,checkpointNs:o.checkpointNs??null}),i.toolProgress=a,s[r]={...o,additionalKwargs:i},s}function Ec(e,t){return e.includes(t)?e:[...e,t]}function Ux(e,t){const n=[...e],r=n.lastIndexOf(t);return r!==-1&&n.splice(r,1),n}function hr(e,t){let n=!1;const r={},o=e.map(s=>{const i=Gx(s);if(i.length)return r[s.id]=i,s;const a=t[s.id]??Px(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 Hx(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=Wx(a,s);if(f===""?l="":f===s?l=s:l=f,l){const h=c[c.length-1];if((h==null?void 0:h.type)==="text"){const p=h.text??"",v={...h,text:p+l};c=[...c.slice(0,c.length-1),v]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function Nc(e){return e.replace(/\s+/g," ").trim()}function Wx(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=Nc(e),o=Nc(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function Vx(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 Do(e,r,s)}return e}function Kx(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}function qx(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 Gx(e){const t=e.additionalKwargs??{};return Array.isArray(t.toolProgress)?[...t.toolProgress]:[]}const Yx={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],messagesStreamMeta:{},pendingInterrupt:null,toolTimelines:{}};function Xx(e,t){var n;switch(t.type){case"reset":return{messages:ki(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,toolIndex:{},toolStreamingMessageId:null,toolStreamingStack:[],pendingInterrupt:null,toolTimelines:{}};case"user_message":{const{message:r}=t.payload;return{...e,messages:[...e.messages,r]}}case"seed":{const r=ki(t.payload.messages),{messages:o,toolTimelines:s}=hr(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=ki(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}=hr(i,e.toolTimelines);return{...e,messages:a,toolTimelines:l}}case"event":return jc(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>jc(o,s),e):e}case"interrupt_response":return{...e,messages:Sc(e.messages),pendingInterrupt:null};default:return e}}function Ac(e=[]){const[t,n]=w.useReducer(Xx,{...Yx,messages:e}),r=w.useRef([]),o=w.useRef(null),s=w.useRef(null),i=w.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=w.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=w.useCallback(d=>{r.current.push(d),a()},[a]);w.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=w.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,f)=>n({type:"seed",payload:{messages:d,...f??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:d=>n({type:"user_message",payload:{message:d}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function jc(e,t){var n,r,o,s;if(t.type==="message.start"&&t.role==="assistant"){const i=t.id,a=Kx(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??Cc(e.messages);if(!i)return e;const a=e.messages,l=a.findIndex(T=>T.id===i&&T.role==="assistant");if(l===-1)return e;const c=a[l],d=e.messagesStreamMeta??{},f=d[i]??{lastSeq:null,lastText:Ic(c.content)},h=t.seq??null;if(h!==null&&typeof h=="number"&&typeof f.lastSeq=="number"&&h<=f.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:h,lastSeq:f.lastSeq}),e;const{newParts:p,newMeta:v,changed:x}=Hx(c.content,t.delta,f,h);if(!x)return e;const y={...c,content:p},g=Do(a,l,y),b={...d,[i]:v};return{...e,messages:g,messagesStreamMeta:b}}if(t.type==="message.end"){const i=e.assemblingId??Cc(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 h;return(f==null?void 0:f.type)==="text"&&((h=f.text)==null?void 0:h.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:c.id,contentTypes:(r=c.content)==null?void 0:r.map(h=>h==null?void 0:h.type),contentPreview:(o=c.content)==null?void 0:o.map(h=>(h==null?void 0:h.type)==="text"?String(h.text).slice(0,100):h==null?void 0:h.type)});const 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},h={type:e.toolStreamingMessageId?"tool.call":"tool.start",toolId:a??d,toolName:l,metadata:{args:t.args}},p=e.toolStreamingMessageId;if(!p){const b={id:`tool-${d}`,role:"tool",name:l,createdAt:new Date().toISOString(),content:[f],additionalKwargs:{...zx(void 0,c.length?c:[d],l,t.args),toolStreaming:!0}},T=Bx(b,c.length?c:[d]),k=[...e.messages,b],S=Lo(k,b.id,h),{messages:C,toolTimelines:E}=hr(S,e.toolTimelines);return{...e,messages:C,toolIndex:kc(e.toolIndex,b.id,T),toolStreamingMessageId:b.id,toolStreamingStack:Ec(e.toolStreamingStack??[],a??d),toolTimelines:E}}const v=Lo(e.messages,p,h),{messages:x,toolTimelines:y}=hr(v,e.toolTimelines);return{...e,messages:x,toolIndex:kc(e.toolIndex,p,c),toolStreamingStack:Ec(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=Ux(l,a),f=d[0]?e.toolIndex[d[0]]:null,h=e.toolStreamingMessageId,p=c===a,v=t.name??((s=e.messages.find(S=>S.id===h))==null?void 0:s.name)??"tool",x=typeof t.output=="string"?t.output.trim():JSON.stringify(t.output??""),y={type:"tool.end",toolId:a,toolName:v,content:x==null?void 0:x.slice(0,200)};let g=e.messages;if(h&&(g=Lo(g,h,y)),p&&h){const S=g.findIndex(C=>C.id===h);if(S>=0){const C=g[S],A={type:"text",text:(()=>{if(typeof t.output=="string"){const D=t.output.trim();try{return D}catch{return D}}return JSON.stringify(t.output??"")})()},R={...C,content:[A],artifact:t.artifact??C.artifact,additionalKwargs:{...C.additionalKwargs??{}}};g=Do(g,S,R)}}const b=d,{messages:T,toolTimelines:k}=hr(g,e.toolTimelines);return{...e,messages:T,toolTimelines:k,toolStreamingMessageId:p?f:h,toolStreamingStack:b}}if(t.type==="tool.progress"){const i=e.toolStreamingMessageId;if(!i)return e;const a={type:"tool.progress",content:t.content??null},l=Lo(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},h={...d,additionalKwargs:f},p=Do(l,c,h),{messages:v,toolTimelines:x}=hr(p,e.toolTimelines);return{...e,messages:v,toolTimelines:x}}if(t.type==="checkpoint"){const i=t.checkpointNs??e.lastCheckpointNs??null,a=Vx(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=fr(t),a=i.interrupt,l=i.latest,c=a===null?Sc(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 _c(e={}){const t=w.useMemo(()=>Cn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=w.useState(e.token??null),s=w.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=w.useState(!1),[c,d]=w.useState(null),[f,h]=w.useState(""),[p,v]=w.useState(null),[x,y]=w.useState(0),[g,b]=w.useState(!1),T=w.useRef(null),k=w.useRef(!0),S=w.useRef(0),C=w.useRef(null),E=w.useRef(null),A=w.useRef(null),R=w.useRef(null),D=w.useCallback(M=>{o(M)},[]),B=w.useCallback(()=>{h(""),v(null),d(null),E.current=null,A.current=null,R.current=null},[]),Y=w.useCallback(()=>{var M;console.debug("[use-chat] stop() invoked - aborting stream"),(M=T.current)==null||M.abort(),T.current=null,C.current=null,l(!1),b(!1),S.current=0,y(0)},[]),G=w.useCallback((M,j,I)=>{T.current&&(T.current.abort(),T.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&h(""),v(null),E.current=null,A.current=null,R.current=null;const U=new AbortController;T.current=U;let $=null,P=null,q=!1;return C.current={threadId:M.threadId??null,headers:{}},(async()=>{var _,Q,V,H,ne,W,O,K,z,te,X,ge,le,oe,me,be,Me,Ce;const Z=Ue=>{var et;try{const rt=JSON.parse(JSON.stringify(Ue));return(et=rt==null?void 0:rt.payload)!=null&&et.files_info&&Array.isArray(rt.payload.files_info)&&(rt.payload.files_info=rt.payload.files_info.map(Ke=>({...Ke,data:Ke!=null&&Ke.data?`<base64 ${String(Ke.data).length} chars>`:Ke==null?void 0:Ke.data}))),rt}catch{return Ue}};try{let Ue={};try{if(r)Ue={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const He=window.__AUTH_TOKEN__,ut=((_=window.localStorage)==null?void 0:_.getItem("authToken"))||null;let kt=null;try{const J=(Q=window.localStorage)==null?void 0:Q.getItem("chat-settings");J&&(kt=((V=JSON.parse(J))==null?void 0:V.apiKey)||null)}catch{}const qe=He||ut||kt||null;qe&&(Ue={Authorization:`Bearer ${qe}`})}}catch{}console.debug("[use-chat] POST",t+n,Z(M));let et={};if(typeof window<"u")try{const Ye=(H=window.localStorage)==null?void 0:H.getItem("authSessionId");Ye&&(et={"X-Session-Id":Ye})}catch{}const rt={...Ue,...et,...s.current},Ke={"Content-Type":"application/json",Accept:"text/event-stream",...rt},Ge=await fetch(t+n,{method:"POST",headers:Ke,body:JSON.stringify(M),signal:U.signal,credentials:i});if(C.current&&(C.current.headers=rt),!Ge.ok||!Ge.body){const Ye=await Ge.text().catch(()=>"");console.debug("[use-chat] non-OK response",Ge.status,Ye==null?void 0:Ye.slice(0,500));const He=`stream ${Ge.status}${Ye?": "+Ye:""}`;throw(ne=I==null?void 0:I.onConnectionError)==null||ne.call(I,He),q=!0,$="error",P=He,new Error(He)}b(!0);const at=Ge.body.getReader(),bt=new TextDecoder;let ht="",Tt=[];S.current=0,y(0);let Ie=0,Fe=null;const pt=()=>{if(Tt.length){const Ye=Tt.join("");Tt=[],k.current&&h(He=>He+Ye)}Fe=null},wt=()=>{typeof window<"u"&&Fe==null&&(Fe=requestAnimationFrame(pt))};let Dt=Date.now();const Pe=setInterval(()=>{var Ye;if(Date.now()-Dt>18e5){const He="Stream idle timeout";d(He),$="error",P=He,U.abort(),(Ye=I==null?void 0:I.onError)==null||Ye.call(I,He)}},5e3),qt=1024*1024;try{const Ye=Ge.headers.get("X-Thread-Id")||Ge.headers.get("x-thread-id"),He=Ge.headers.get("X-Thread-Created")||Ge.headers.get("x-thread-created"),ut=Ye??null,kt=String(He??"").toLowerCase()==="true";for(C.current&&!C.current.threadId&&(C.current={...C.current,threadId:ut}),(W=I==null?void 0:I.onOpen)==null||W.call(I,{threadId:ut,created:kt});;){const{value:qe,done:J}=await at.read();if(J)break;ht+=bt.decode(qe,{stream:!0}),ht.length>qt&&(ht="",console.warn("Stream buffer reset: exceeded 1MB"));let L;for(;(L=ht.indexOf(`
36
36
 
37
37
  `))>=0;){const ce=ht.slice(0,L);ht=ht.slice(L+2);const xe=Zx(ce);if(!xe)continue;let Be;try{Be=JSON.parse(xe)}catch{console.debug("[use-chat] malformed SSE:",xe.slice(0,200));continue}const De=Jx(Be)?Be.data:Be;Dt=Date.now();const mt=De.seq;if(mt!==void 0){if(mt<=Ie){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:mt,lastProcessedSeq:Ie,type:De.type});continue}Ie>0&&mt>Ie+1&&((O=I==null?void 0:I.onGap)==null||O.call(I,{from:Ie,to:mt})),Ie=mt,S.current=mt,y(mt)}if(De.type==="checkpoint")E.current=De.checkpointId??null,A.current=De.checkpointNs??null,v(De.checkpointId??null);else if(De.type==="state_history"){R.current=De;try{const Et=fr(De).latest;Et&&(E.current=Et.checkpointId??null,A.current=Et.checkpointNs??null,v(Et.checkpointId??null))}catch(Xe){console.warn("[use-chat] Failed to hydrate state_history payload",Xe)}}try{j==null||j(De)}catch(Xe){console.error("[use-chat] Error in onEvent callback:",Xe,"for event:",De.type)}if(De.type==="message.delta"){const Xe=De.delta.filter(Et=>Et.type==="text").map(Et=>Et.text).join("");Xe&&e.autoAppendAssistant!==!1&&(Tt.push(Xe),wt())}else if(De.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(K=I==null?void 0:I.onHeartbeat)==null||K.call(I,De)}catch(Xe){console.warn("[use-chat] heartbeat callback failed",Xe)}}else if(Fe!==null&&cancelAnimationFrame(Fe),pt(),De.type==="checkpoint")v(De.checkpointId);else if(De.type==="error"){const Xe=De;if(d(Xe.message),$="error",P=Xe.message,Xe.error_type==="auth_error"||Xe.code==="TOKEN_EXPIRED"||((z=Xe.message)==null?void 0:z.includes("token"))||((te=Xe.message)==null?void 0:te.includes("401"))||((X=Xe.message)==null?void 0:X.includes("unauthorized"))||((ge=Xe.message)==null?void 0:ge.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Xe.message);try{(le=I==null?void 0:I.onAuthError)==null||le.call(I,Xe.message)}catch(yo){console.warn("[use-chat] onAuthError handler failed",yo)}U.abort()}}}}pt(),$===null&&!U.signal.aborted&&($="complete")}catch(Ye){if(Ye.name==="AbortError")$=$??"aborted";else{const He=Ye.message||String(Ye);$="error",P=He,d(He),(oe=I==null?void 0:I.onError)==null||oe.call(I,He)}}finally{try{await at.cancel()}catch{}finally{(me=at.releaseLock)==null||me.call(at)}Fe!==null&&typeof window<"u"&&window.cancelAnimationFrame(Fe),clearInterval(Pe)}}catch(Ue){if(Ue.name==="AbortError")$=$??"aborted";else{const et=Ue.message||String(Ue);$="error",P=et,d(et),(be=I==null?void 0:I.onError)==null||be.call(I,et),q||((Me=I==null?void 0:I.onConnectionError)==null||Me.call(I,et),q=!0)}}finally{const Ue=S.current,et=E.current,rt=A.current,Ke=R.current,Ge=$??(U.signal.aborted?"aborted":P?"error":"complete");try{(Ce=I==null?void 0:I.onClosed)==null||Ce.call(I,{reason:Ge,lastSeq:Ue,lastCheckpointId:et,lastCheckpointNs:rt,lastStateHistory:Ke,error:P})}catch(at){console.warn("[use-chat] onClosed callback failed",at)}l(!1),b(!1),T.current=null,S.current=0,y(0),C.current=null}})(),{close:()=>U.abort()}},[t,n,r,e.autoAppendAssistant]);return w.useEffect(()=>()=>{var M;k.current=!1,(M=T.current)==null||M.abort()},[]),{isStreaming:a,error:c,assistantText:f,lastCheckpointId:p,lastSeq:x,connected:g,stream:G,stop:Y,clear:B,setToken:D}}function Jx(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Zx(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
38
38
  `)}const Qx=["message.start","message.delta","message.end"],ey=["tool.start","tool.end","tool.progress"],ty=["thread_info","checkpoint"],ny=["error","interrupt","heartbeat","state_history","cancelled"],ry=[...Qx,...ey,...ty,...ny],oy=new Set(ry);function sy(e){if(typeof e!="object"||e===null||typeof e.type!="string")return!1;const t=e.type;return oy.has(t)}const Mc=200;function iy({baseUrl:e,onThreadInfo:t,onMessageEvent:n,onStateHistory:r,onUnhandledEvent:o,onSequenceGap:s,onStreamClosed:i,onConnectionError:a,onAuthError:l,onHeartbeat:c}){const d=w.useRef(null),f=w.useRef(null),h=w.useRef(new Map),p=w.useRef(null),v=w.useRef(null),x=w.useCallback(j=>{try{const I=globalThis.structuredClone;if(typeof I=="function")return I(j)}catch{}try{return JSON.parse(JSON.stringify(j))}catch{return j}},[]),y=w.useCallback((j,I)=>{if(!j)return;const U=h.current.get(j)??[],$=x(I),P=U.length>=Mc?[...U.slice(U.length-Mc+1),$]:[...U,$];h.current.set(j,P)},[x]),g=w.useCallback(j=>{j&&h.current.set(j,[])},[]),b=w.useCallback(j=>{const I=j??f.current;if(!I)return;const U=h.current.get(I);U!=null&&U.length&&U.forEach($=>{try{n($)}catch(P){console.error("[useChatStreamingService] Failed to replay buffered event",P)}})},[n]),T=w.useCallback(j=>{f.current=j.threadId,p.current&&(p.current.threadIdGuess=j.threadId),v.current=j,g(j.threadId),console.log("[useChatStreamingService] 🎯 Received thread_info event:",j);try{t(j)}catch(I){console.error("[useChatStreamingService] Error in onThreadInfo handler:",I)}},[g,t]),k=w.useCallback(j=>{try{c==null||c(j)}catch(I){console.error("[useChatStreamingService] Error in onHeartbeat handler:",I)}},[c]),S=w.useCallback(j=>{var $,P,q,Z;const I=j;if(I.error_type==="auth_error"||I.code==="TOKEN_EXPIRED"||(($=I.message)==null?void 0:$.includes("token"))||((P=I.message)==null?void 0:P.includes("401"))||((q=I.message)==null?void 0:q.includes("unauthorized"))||((Z=I.message)==null?void 0:Z.includes("Unauthorized"))){console.error("[useChatStreamingService] Auth error event detected:",I.message);try{l==null||l(I.message)}catch(_){console.warn("[useChatStreamingService] onAuthError handler failed",_)}}},[l]),C=w.useMemo(()=>({thread_info:j=>(T(j),!0),heartbeat:j=>(k(j),!0),error:j=>(S(j),!1)}),[T,k,S]),E=w.useCallback(j=>{var P;const I=j.seq??null;if(I!==null){const q=d.current;if(q!==null){if(I<=q)return;I>q+1&&(s==null||s({from:q,to:I}))}d.current=I}const U=C[j.type];if(U&&U(j))return;const $=j.threadId??(j.type==="state_history"?j.threadId:void 0)??f.current??((P=p.current)==null?void 0:P.threadIdGuess)??null;if(j.type==="state_history"){f.current=$??f.current;try{r==null||r(j)}catch(q){console.error("[useChatStreamingService] onStateHistory handler failed",q)}}if(sy(j)){j.type==="checkpoint"||j.type==="state_history"?g($??null):y($??null,j);try{n(j)}catch(q){console.error("[useChatStreamingService] Error in onMessageEvent handler:",q)}return}try{o==null||o(j)}catch(q){console.error("[useChatStreamingService] Error in onUnhandledEvent handler:",q)}},[y,g,n,s,r,o,C]),{stream:A,stop:R,isStreaming:D,error:B,setToken:Y}=_c({baseUrl:e,token:void 0}),G=w.useCallback((j,I)=>{d.current=null,v.current=null,f.current=j.threadId??null,p.current={request:j,callbacks:I,manualStop:!1,threadIdGuess:j.threadId??null},A(j,E,{onOpen:I==null?void 0:I.onOpen,onError:U=>{var $;($=I==null?void 0:I.onError)==null||$.call(I,U)},onGap:(I==null?void 0:I.onGap)??s,onConnectionError:U=>{var $;a==null||a(U),($=I==null?void 0:I.onConnectionError)==null||$.call(I,U)},onAuthError:U=>{var $;l==null||l(U),($=I==null?void 0:I.onAuthError)==null||$.call(I,U)},onHeartbeat:U=>{var $;try{c==null||c(U)}catch(P){console.warn("[useChatStreamingService] onHeartbeat handler failed",P)}try{($=I==null?void 0:I.onHeartbeat)==null||$.call(I,U)}catch(P){console.warn("[useChatStreamingService] downstream onHeartbeat handler failed",P)}},onClosed:U=>{var Z,_,Q,V;const $=((Z=p.current)==null?void 0:Z.manualStop)??!1,P=f.current??((_=p.current)==null?void 0:_.threadIdGuess)??((Q=U.lastStateHistory)==null?void 0:Q.threadId)??null;(U.reason==="complete"||U.reason==="aborted"&&$)&&g(P);const q={...U,threadId:P,threadInfo:v.current,manualStop:$};try{i==null||i(q)}catch(H){console.warn("[useChatStreamingService] onStreamClosed handler failed",H)}try{(V=I==null?void 0:I.onClosed)==null||V.call(I,q)}catch(H){console.warn("[useChatStreamingService] downstream onClosed handler failed",H)}p.current&&(p.current=null)}})},[g,E,l,a,c,s,i,A]),M=w.useCallback(()=>{p.current&&(p.current.manualStop=!0),R()},[R]);return w.useMemo(()=>({startStream:G,stop:M,isStreaming:D,error:B,setAuthToken:Y,replayBufferedEvents:b}),[G,M,D,B,Y,b])}function ay({api:e,seed:t,prepend:n,onError:r,currentThreadId:o,initialThreadId:s=null,initialCheckpointId:i=null,initialCheckpointNs:a=null,autoLoadInitial:l=!0,isStreaming:c,getMessages:d}){const[f,h]=w.useState([]),[p,v]=w.useState([]),[x,y]=w.useState(!1),[g,b]=w.useState(null),[T,k]=w.useState(!1),[S,C]=w.useState(!1),[E,A]=w.useState(!1),[R,D]=w.useState(null),B=w.useRef(o),Y=w.useRef(null),G=w.useRef(null),M=w.useRef(null),j=w.useRef(null),I=w.useRef(!1),U=w.useRef(null),$=w.useRef(new Map);w.useEffect(()=>{B.current=o},[o]);const P=w.useCallback(async z=>{var X,ge;if(!z.threadId)return;const te=z.threadId;(X=z.onStart)==null||X.call(z),z.setLoading(!0);try{await z.action(te)}catch(le){if(B.current===te){const oe=String(le);(ge=z.handleError)==null||ge.call(z,oe),r==null||r(oe)}throw le}finally{z.setLoading(!1)}},[r]),q=w.useCallback(async(z,te)=>{if(!z)return;const X=`${z}:${te??"latest"}`,ge=$.current.get(X);if(ge)return ge;const le=P({threadId:z,setLoading:k,onStart:()=>D(null),handleError:oe=>D(oe),action:async oe=>{const me=await e.getStateHistory({threadId:oe,checkpointId:te??void 0});if(B.current!==oe){console.log(`[useThreadHistoryState] Thread changed during load (was ${oe}, now ${B.current}), discarding stale data`);return}const{checkpoints:be,timeline:Me}=fr(me),Ce=be.find(Ue=>Ue.messages&&Ue.messages.length>0)??(te?be.find(Ue=>Ue.checkpointId===te):null)??be[0];t((Ce==null?void 0:Ce.messages)??[],{checkpointId:(Ce==null?void 0:Ce.checkpointId)??null,checkpointNs:(Ce==null?void 0:Ce.checkpointNs)??null}),v(Me),h(be),y(!!(Ce!=null&&Ce.nextCursor)),b((Ce==null?void 0:Ce.nextCursor)??null)}});$.current.set(X,le);try{await le}finally{$.current.delete(X)}return B.current===z&&(U.current=X),le},[e,t,P]),Z=w.useCallback(async(z,te,X)=>{X!=null&&X.clearProgress&&bc(),j.current=z;try{await q(z,te)}finally{j.current===z&&(j.current=null)}},[q]),_=w.useCallback(z=>{G.current=z},[]),Q=w.useCallback(z=>{M.current=z},[]),V=w.useCallback(z=>{const te=z.threadId??B.current;if(!te||B.current&&B.current!==te)return;const{checkpoints:X,timeline:ge}=fr(z);if(!X.length)return;const le=X.find(oe=>oe.messages&&oe.messages.length>0)??X.find(oe=>!!oe.checkpointId)??X[0];t((le==null?void 0:le.messages)??[],{checkpointId:(le==null?void 0:le.checkpointId)??null,checkpointNs:(le==null?void 0:le.checkpointNs)??null}),v(ge),h(X),y(!!(le!=null&&le.nextCursor)),b((le==null?void 0:le.nextCursor)??null),U.current=`${te}:latest`,G.current=null,M.current=null},[t]),H=w.useCallback(async(z,te)=>{bc();const X=B.current;await P({threadId:X,setLoading:A,action:async ge=>{const le=await e.getStateHistory({threadId:ge,checkpointId:z,checkpointNs:te??void 0});if(B.current!==ge){console.log(`[useThreadHistoryState] Thread changed during checkpoint navigation (was ${ge}, now ${B.current}), discarding stale data`);return}const{checkpoints:oe,timeline:me}=fr(le),be=oe.find(Me=>Me.checkpointId===z&&(te?Me.checkpointNs===te:!0));if(!be){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:z,checkpointNs:te});return}v(me),h(oe),t(be.messages??[],{checkpointId:be.checkpointId??null,checkpointNs:be.checkpointNs??null})}}).catch(()=>{})},[e,t,P]),ne=w.useCallback((z,te)=>{t(d(),{checkpointId:z??null,checkpointNs:te??null})},[d,t]),W=w.useCallback(async()=>{B.current&&await Z(B.current)},[Z]),O=w.useCallback(async()=>{const z=B.current;!z||!g||await P({threadId:z,setLoading:C,action:async te=>{const X=await e.getStateHistory({threadId:te,checkpointId:g});if(B.current!==te)return;const{checkpoints:ge}=fr(X);if(ge.length>0){const le=ge[ge.length-1];n((le==null?void 0:le.messages)??[]),y(!!(le!=null&&le.nextCursor)),b((le==null?void 0:le.nextCursor)??null)}}}).catch(()=>{})},[e,g,r,n,P]);w.useEffect(()=>{if(!l||!o||T||c)return;if(G.current===o){G.current=null,Y.current=o;return}if(M.current===o){Y.current=o;return}if(j.current===o){j.current=null,Y.current=o;return}if(Y.current===o)return;Y.current=o;const z=!I.current&&!!i&&o===s;let te;z&&i?(te=i,I.current=!0,console.log("[useThreadHistoryState] Loading thread with checkpoint:",te,a?`(ns: ${a})`:"")):console.log("[useThreadHistoryState] Loading thread with latest checkpoint");const X=`${o}:${te??"latest"}`;U.current!==X&&Z(o,te)},[l,o,i,a,s,T,c,Z]);const K=w.useCallback(()=>{h([]),v([]),y(!1),b(null),k(!1),C(!1),A(!1),D(null),G.current=null,M.current=null,Y.current=null,U.current=null,j.current=null},[]);return{threadCheckpoints:f,threadTimeline:p,isLoadingThread:T,isHistoryLoading:S,isLoadingCheckpoint:E,threadStateError:R,hasMoreHistory:x,loadThread:Z,navigateToCheckpoint:H,loadOlderMessages:O,setCurrentCheckpointId:ne,returnToLatest:W,handleStateHistoryEvent:V,markSkipNextLoad:_,markStreamPendingThread:Q,resetHistoryState:K}}const ly=["detail","message","error","description","title"];function $o(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=$o(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of ly){const r=$o(t[n]);if(r)return r}if("errors"in t){const n=$o(t.errors);if(n)return n}}return null}function cy(e){if(!e)return"Request failed";const t=e.response,n=$o(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function uy({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:o}){const[s,i]=w.useState([]),[a,l]=w.useState(t),[c,d]=w.useState(!1),[f,h]=w.useState(null),[p,v]=w.useState([]),[x,y]=w.useState(!1),[,g]=w.useState(null),[b,T]=w.useState([]),[k,S]=w.useState(!1),[,C]=w.useState(null),[E,A]=w.useState(null),[R,D]=w.useState(!1),B=w.useRef(a),Y=w.useRef(new Map);w.useEffect(()=>{B.current=a},[a]);const G=w.useCallback(async()=>{d(!0),h(null);try{const V=await e.listThreads();i(V??[])}catch(V){const H=String(V);h(H),n==null||n(H)}finally{d(!1)}},[e,n]),M=w.useCallback(async()=>{y(!0),g(null);try{const V=await e.listSharedThreads();v(V??[])}catch(V){const H=String(V);g(H),n==null||n(H)}finally{y(!1)}},[e,n]),j=w.useCallback(async()=>{S(!0),C(null);try{const V=await e.listSmartOrgUsers();T(V??[])}catch(V){const H=String(V);C(H),n==null||n(H)}finally{S(!1)}},[e,n]);w.useEffect(()=>{G(),j()},[j,G]),w.useEffect(()=>{M()},[M]),w.useEffect(()=>{r==null||r(a)},[a,r]);const I=w.useCallback(async V=>{try{const H=await e.createThread(V);return l(H.threadId),await G(),H.threadId}catch(H){const ne=String(H);return n==null||n(ne),null}},[e,n,G]),U=w.useCallback(async V=>{const H=s;i(W=>W.filter(O=>O.threadId!==V));const ne=new AbortController;Y.current.set(V,ne);try{await e.deleteThread(V),B.current===V&&(l(null),o==null||o())}catch(W){i(H);const O=String(W);n==null||n(O)}finally{Y.current.delete(V)}},[e,o,n,s]),$=w.useCallback(async(V,H)=>{try{await e.updateThread(V,H),await G()}catch(ne){n==null||n(String(ne))}},[e,n,G]),P=w.useCallback(async(V,H)=>{D(!0),A("Sharing thread…");try{await e.shareThread(V,H),await M(),A("Shared successfully")}catch(ne){const W=cy(ne);throw n==null||n(W),A(`Failed to share: ${W}`),new Error(W)}finally{D(!1)}},[e,n,M]),q=w.useCallback(async(V,H)=>{try{await e.unshareThread(V,H),await M()}catch(ne){const W=String(ne);throw n==null||n(W),ne}},[e,n,M]),Z=w.useMemo(()=>({createThread:I,deleteThread:U,renameThread:$,refreshThreads:G,refreshSharedThreads:M,refreshSmartOrgUsers:j,shareThread:P,unshareThread:q}),[I,U,$,G,M,j,P,q]),_=w.useCallback(V=>{if(!(V!=null&&V.threadId))return;const H={threadId:V.threadId,title:V.title||`Thread ${V.threadId.slice(0,8)}`,createdAt:V.createdAt||new Date().toISOString(),updatedAt:V.updatedAt||new Date().toISOString(),messageCount:V.messageCount??1};i(ne=>{let W=!1;const O=ne.map(K=>K.threadId===H.threadId?(W=!0,console.debug("[useThreadsState] thread_info: updating existing thread",H.threadId),{...K,title:H.title??K.title,updatedAt:H.updatedAt??K.updatedAt,messageCount:H.messageCount??K.messageCount}):K);return W?O:(console.debug("[useThreadsState] thread_info: adding thread to list",H.threadId),[H,...ne])})},[]),Q=w.useCallback(()=>A(null),[]);return{threads:s,currentThreadId:a,currentThreadIdRef:B,setCurrentThreadId:l,isLoadingThreads:c,threadsError:f,sharedThreads:p,isLoadingSharedThreads:x,smartOrgUsers:b,isLoadingSmartOrgUsers:k,actions:Z,addThreadFromEvent:_,shareInFlight:R,shareStatus:E,clearShareStatus:Q}}const Rc=w.createContext(null),Pc=w.createContext(null),Oc=w.createContext(null);w.createContext(!1);function dy({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}=wi(),f=w.useMemo(()=>Cn(d),[d]),{state:h,seed:p,prepend:v,pushUser:x,onEvent:y}=Ac(),{threads:g,currentThreadId:b,setCurrentThreadId:T,currentThreadIdRef:k,isLoadingThreads:S,threadsError:C,sharedThreads:E,isLoadingSharedThreads:A,smartOrgUsers:R,isLoadingSmartOrgUsers:D,actions:B,addThreadFromEvent:Y,shareInFlight:G,shareStatus:M,clearShareStatus:j}=uy({api:c,initialThreadId:t,onError:s,onThreadChange:a,onCurrentThreadDeleted:()=>p([],{})}),[I,U]=w.useState(!1),$=w.useCallback(()=>h.messages,[h.messages]),{threadCheckpoints:P,threadTimeline:q,isLoadingThread:Z,isHistoryLoading:_,isLoadingCheckpoint:Q,threadStateError:V,hasMoreHistory:H,loadThread:ne,navigateToCheckpoint:W,loadOlderMessages:O,setCurrentCheckpointId:K,returnToLatest:z,handleStateHistoryEvent:te,markSkipNextLoad:X,markStreamPendingThread:ge,resetHistoryState:le}=ay({api:c,seed:p,prepend:v,onError:s,currentThreadId:b,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:I,getMessages:$}),oe=w.useMemo(()=>ux(P),[P]),me=w.useCallback(Ie=>{console.log("[ChatSessionProvider] 🎯 Received thread_info:",Ie.threadId),Y(Ie),k.current!==Ie.threadId&&((Ie.created??!k.current)&&X(Ie.threadId),ge(Ie.threadId),console.log("[ChatSessionProvider] thread_info: marking to skip auto-load for new thread"),T(Ie.threadId))},[Y,X,ge]),{startStream:be,stop:Me,isStreaming:Ce,error:Ue,setAuthToken:et}=iy({baseUrl:f,onThreadInfo:me,onMessageEvent:y,onStateHistory:te,onUnhandledEvent:Ie=>{console.warn("[ChatSessionProvider] Unhandled event:",Ie.type)},onAuthError:i,onConnectionError:l});w.useEffect(()=>{U(Ce)},[Ce]);const rt=w.useCallback(async()=>{p([],{}),T(null),Me(),le();try{await c.getAgent("default")}catch(Ie){console.warn("[ChatSessionProvider] Failed to refetch agent after clearing thread:",Ie)}},[p,Me,c,le]),Ke=w.useCallback(async(Ie,Fe,pt)=>{const wt=k.current;if(!wt)throw new Error("No active thread to handle interrupt");const Dt=Fe?pt??!0:!1;try{const Pe={threadId:wt,checkpointId:h.lastCheckpointId??void 0,checkpointNs:h.lastCheckpointNs??void 0,command:{kind:"resume",value:Dt}};be(Pe)}catch(Pe){throw console.error(`[ChatSessionProvider] Failed to handle interrupt ${Ie}:`,Pe),Pe}},[h.lastCheckpointId,h.lastCheckpointNs,be]),Ge=w.useCallback(async(Ie,Fe)=>{let pt=k.current;const wt=(Ie==null?void 0:Ie.text)??"",Dt=(Ie==null?void 0:Ie.attachments)??[],Pe=(wt==null?void 0:wt.trim())??"",qt={...(Ie==null?void 0:Ie.payload)??{}},Ye=Array.isArray(qt.messages)?qt.messages:void 0;Ye&&delete qt.messages;const He=!!(Ye&&Ye.length);if(!pt&&!Pe&&Dt.length===0&&!He)return;if(!pt){const Xe=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),Et=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);pt=`${Xe}${Et}`,X(pt),T(pt)}const{contentParts:ut,filesInfo:kt}=await ax(c,Dt),qe=[...ut];Pe&&qe.push({type:"text",text:wt});const J=Fe==null?void 0:Fe.originalMessageId,L=!!(Fe!=null&&Fe.edit&&J),ce=!He&&qe.length>0;let xe=null;ce&&(xe={id:L?J:`msg-${Date.now()}`,role:"user",content:qe,createdAt:new Date().toISOString()},L||x(xe));const Be=He?Ye:xe?[xe]:[],De={...qt,...kt.length?{files_info:kt}:{}};Be.length?De.messages=Be:"messages"in De||(De.messages=[]);const mt={threadId:pt,payload:De,checkpointId:(Fe==null?void 0:Fe.checkpointId)??h.lastCheckpointId??void 0,checkpointNs:(Fe==null?void 0:Fe.checkpointNs)??h.lastCheckpointNs??void 0,edit:!!(Fe!=null&&Fe.edit),timelineCheckpoints:q};be(mt)},[c,x,h,be,q]),at=w.useMemo(()=>({threads:g,currentThreadId:b,setCurrentThreadId:T,isLoading:S,error:C,sharedThreads:E,isLoadingSharedThreads:A,smartOrgUsers:R,isLoadingSmartOrgUsers:D,actions:B,shareInFlight:G,shareStatus:M,clearShareStatus:j}),[g,b,T,S,C,E,A,R,D,B,G,M,j]),bt=w.useMemo(()=>{const Ie=h.assemblingId??null;return Ie?{assemblingMessageId:Ie}:null},[h.assemblingId]),ht=w.useMemo(()=>({threadId:b,messages:h.messages,interrupt:null,checkpoint:{id:h.lastCheckpointId??null,namespace:h.lastCheckpointNs??null},checkpoints:P,timelineCheckpoints:q,metadata:bt,isLoading:Z,isHistoryLoading:_,isLoadingCheckpoint:Q,error:V,hasMore:H,loadOlder:O,clearState:rt,navigateToCheckpoint:W,setCurrentCheckpointId:K,returnToLatest:z,loadThread:ne,clearThread:rt,respondToInterrupt:Ke,messagePreviews:oe}),[b,h,P,q,Z,_,Q,V,H,O,rt,W,K,z,ne,Ke,oe,bt]),Tt=w.useMemo(()=>({isStreaming:Ce,error:Ue,connectionState:Ce?"connected":"idle",submit:Ge,send:Ge,stop:Me,setAuthToken:et}),[Ce,Ue,Ge,Me,et]);return u.jsx(Rc.Provider,{value:at,children:u.jsx(Pc.Provider,{value:ht,children:u.jsx(Oc.Provider,{value:Tt,children:e})})})}function Fo(){const e=w.useContext(Rc);if(!e)throw new Error("useThreads must be used within ChatSessionProvider");return e}function Bo(){const e=w.useContext(Pc);if(!e)throw new Error("useThreadState must be used within ChatSessionProvider");return e}function Dc(){const e=w.useContext(Oc);if(!e)throw new Error("useStream must be used within ChatSessionProvider");return e}function zo({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(sx,{apiConfig:t,children:u.jsx(dy,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,children:e})})}function se(...e){return Mm.twMerge(_m.clsx(e))}const fy=bo.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"}}),tt=m.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Wn.Slot:"button";return u.jsx(i,{className:se(fy({variant:t,size:n,className:e})),ref:s,...o})});tt.displayName="Button";const Lc=m.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{className:se("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));Lc.displayName="Textarea";function $c({initialValue:e="",editingMessageId:t=null,placeholder:n="Type your message...",isStreaming:r=!1,disabled:o=!1,maxLength:s=2e4,value:i,onValueChange:a,onSend:l,onCancelEdit:c,onStop:d,className:f="",textareaClassName:h="",allowEmptySend:p=!1}){const v=i!==void 0,[x,y]=w.useState(e),g=(v?i:x)??"",[b,T]=w.useTransition(),k=w.useRef(null),S=w.useRef(0),C=w.useRef(null);w.useEffect(()=>{v||(y(e??""),C.current=null,k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`))},[e,t,v]);const E=w.useCallback(()=>{const j=k.current;j&&(j.style.height="auto",j.style.height=`${j.scrollHeight}px`)},[]);w.useEffect(()=>{E()},[E,g]);const A=w.useCallback((j,{fromUser:I})=>{v||y(j),I&&(a==null||a(j))},[v,a]),R=w.useCallback(async j=>{j&&j.preventDefault();const I=(g??"").trim();if(!I&&!p)return;const U=++S.current;C.current={id:U,shouldClear:!0},T(()=>{var $,P,q;try{const Z=l(I);Z&&typeof Z.then=="function"?Z.then(()=>{var _,Q;((_=C.current)==null?void 0:_.id)===U&&C.current.shouldClear&&(v||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((Q=C.current)==null?void 0:Q.id)===U&&(C.current=null)}).catch(()=>{var _;((_=C.current)==null?void 0:_.id)===U&&(C.current=null)}):((($=C.current)==null?void 0:$.id)===U&&C.current.shouldClear&&(v||(y(""),k.current&&(k.current.style.height="auto"),a==null||a(""))),((P=C.current)==null?void 0:P.id)===U&&(C.current=null))}catch{((q=C.current)==null?void 0:q.id)===U&&(C.current=null)}})},[g,l,p,v,a]),D=w.useCallback(j=>{const I=j.target.value;A(I,{fromUser:!0}),C.current&&(C.current.shouldClear=!1),k.current&&(k.current.style.height="auto",k.current.style.height=`${k.current.scrollHeight}px`)},[A]),B=w.useCallback(j=>{j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),R()):j.key==="Escape"&&t&&(j.preventDefault(),c==null||c())},[R,t,c]),M=`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${t?"border-[hsl(var(--ring))] bg-[hsl(var(--card))] text-[hsl(var(--card-foreground))] dark:bg-[hsl(var(--card))] dark:text-[hsl(var(--card-foreground))]":""} ${h}`;return u.jsx("form",{onSubmit:j=>void R(j),className:`w-full ${f}`,children:u.jsxs("div",{className:"flex items-end gap-2",children:[u.jsx("div",{className:"flex-1",children:u.jsx(Lc,{ref:k,value:g,onChange:D,onKeyDown:B,placeholder:t?"Edit your message...":n,className:M,disabled:o,maxLength:s,rows:1,spellCheck:!1,autoCorrect:"off"})}),u.jsx("div",{children:r?u.jsx(tt,{type:"button",onClick:()=>{d==null||d()},size:"icon",variant:"outline",className:"shrink-0",title:"Stop generating",disabled:o||!d,children:u.jsx(ae.Square,{size:16})}):u.jsx(tt,{type:"submit",size:"icon",className:"shrink-0",title:t?"Save changes":"Send message",disabled:o||!g.trim()&&!p||b,children:u.jsx(ae.Send,{size:16})})})]})})}const hy=w.memo($c);function he(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 Fc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function An(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Fc(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():Fc(e[o],null)}}}}function We(...e){return m.useCallback(An(...e),e)}function py(e,t){const n=m.createContext(t),r=s=>{const{children:i,...a}=s,l=m.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=m.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function Tn(e,t=[]){let n=[];function r(s,i){const a=m.createContext(i),l=n.length;n=[...n,i];const c=f=>{var g;const{scope:h,children:p,...v}=f,x=((g=h==null?void 0:h[e])==null?void 0:g[l])||a,y=m.useMemo(()=>v,Object.values(v));return u.jsx(x.Provider,{value:y,children:p})};c.displayName=s+"Provider";function d(f,h){var x;const p=((x=h==null?void 0:h[e])==null?void 0:x[l])||a,v=m.useContext(p);if(v)return v;if(i!==void 0)return i;throw new Error(`\`${f}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>m.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return m.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,my(o,...t)]}function my(...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 m.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Nt=globalThis!=null&&globalThis.document?m.useLayoutEffect:()=>{},gy=m[" useInsertionEffect ".trim().toString()]||Nt;function pr({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=xy({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=m.useRef(e!==void 0);m.useEffect(()=>{const f=d.current;f!==a&&console.warn(`${r} is changing from ${f?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=m.useCallback(d=>{var f;if(a){const h=yy(d)?d(e):d;h!==e&&((f=i.current)==null||f.call(i,h))}else s(d)},[a,e,s,i]);return[l,c]}function xy({defaultProp:e,onChange:t}){const[n,r]=m.useState(e),o=m.useRef(n),s=m.useRef(t);return gy(()=>{s.current=t},[t]),m.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function yy(e){return typeof e=="function"}var vy=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Se=vy.reduce((e,t)=>{const n=Wn.createSlot(`Primitive.${t}`),r=m.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 Bc(e,t){e&&wo.flushSync(()=>e.dispatchEvent(t))}function Ei(e){const t=e+"CollectionProvider",[n,r]=Tn(t),[o,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),i=x=>{const{scope:y,children:g}=x,b=w.useRef(null),T=w.useRef(new Map).current;return u.jsx(o,{scope:y,itemMap:T,collectionRef:b,children:g})};i.displayName=t;const a=e+"CollectionSlot",l=Wn.createSlot(a),c=w.forwardRef((x,y)=>{const{scope:g,children:b}=x,T=s(a,g),k=We(y,T.collectionRef);return u.jsx(l,{ref:k,children:b})});c.displayName=a;const d=e+"CollectionItemSlot",f="data-radix-collection-item",h=Wn.createSlot(d),p=w.forwardRef((x,y)=>{const{scope:g,children:b,...T}=x,k=w.useRef(null),S=We(y,k),C=s(d,g);return w.useEffect(()=>(C.itemMap.set(k,{ref:k,...T}),()=>void C.itemMap.delete(k))),u.jsx(h,{[f]:"",ref:S,children:b})});p.displayName=d;function v(x){const y=s(e+"CollectionConsumer",x);return w.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const T=Array.from(b.querySelectorAll(`[${f}]`));return Array.from(y.itemMap.values()).sort((C,E)=>T.indexOf(C.ref.current)-T.indexOf(E.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:p},v,r]}var by=m.createContext(void 0);function Uo(e){const t=m.useContext(by);return e||t||"ltr"}function At(e){const t=m.useRef(e);return m.useEffect(()=>{t.current=e}),m.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function wy(e,t=globalThis==null?void 0:globalThis.document){const n=At(e);m.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var Sy="DismissableLayer",Ii="dismissableLayer.update",Cy="dismissableLayer.pointerDownOutside",Ty="dismissableLayer.focusOutside",zc,Uc=m.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ho=m.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=m.useContext(Uc),[d,f]=m.useState(null),h=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=m.useState({}),v=We(t,E=>f(E)),x=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),g=x.indexOf(y),b=d?x.indexOf(d):-1,T=c.layersWithOutsidePointerEventsDisabled.size>0,k=b>=g,S=Iy(E=>{const A=E.target,R=[...c.branches].some(D=>D.contains(A));!k||R||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},h),C=Ny(E=>{const A=E.target;[...c.branches].some(D=>D.contains(A))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},h);return wy(E=>{b===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},h),m.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(zc=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),Hc(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=zc)}},[d,h,n,c]),m.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),Hc())},[d,c]),m.useEffect(()=>{const E=()=>p({});return document.addEventListener(Ii,E),()=>document.removeEventListener(Ii,E)},[]),u.jsx(Se.div,{...l,ref:v,style:{pointerEvents:T?k?"auto":"none":void 0,...e.style},onFocusCapture:he(e.onFocusCapture,C.onFocusCapture),onBlurCapture:he(e.onBlurCapture,C.onBlurCapture),onPointerDownCapture:he(e.onPointerDownCapture,S.onPointerDownCapture)})});Ho.displayName=Sy;var ky="DismissableLayerBranch",Ey=m.forwardRef((e,t)=>{const n=m.useContext(Uc),r=m.useRef(null),o=We(t,r);return m.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(Se.div,{...e,ref:o})});Ey.displayName=ky;function Iy(e,t=globalThis==null?void 0:globalThis.document){const n=At(e),r=m.useRef(!1),o=m.useRef(()=>{});return m.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){Wc(Cy,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 Ny(e,t=globalThis==null?void 0:globalThis.document){const n=At(e),r=m.useRef(!1);return m.useEffect(()=>{const o=s=>{s.target&&!r.current&&Wc(Ty,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function Hc(){const e=new CustomEvent(Ii);document.dispatchEvent(e)}function Wc(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?Bc(o,s):o.dispatchEvent(s)}var Ni=0;function Ai(){m.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Vc()),document.body.insertAdjacentElement("beforeend",e[1]??Vc()),Ni++,()=>{Ni===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ni--}},[])}function Vc(){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 ji="focusScope.autoFocusOnMount",_i="focusScope.autoFocusOnUnmount",Kc={bubbles:!1,cancelable:!0},Ay="FocusScope",Wo=m.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=m.useState(null),c=At(o),d=At(s),f=m.useRef(null),h=We(t,x=>l(x)),p=m.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;m.useEffect(()=>{if(r){let x=function(T){if(p.paused||!a)return;const k=T.target;a.contains(k)?f.current=k:jn(f.current,{select:!0})},y=function(T){if(p.paused||!a)return;const k=T.relatedTarget;k!==null&&(a.contains(k)||jn(f.current,{select:!0}))},g=function(T){if(document.activeElement===document.body)for(const S of T)S.removedNodes.length>0&&jn(a)};document.addEventListener("focusin",x),document.addEventListener("focusout",y);const b=new MutationObserver(g);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",y),b.disconnect()}}},[r,a,p.paused]),m.useEffect(()=>{if(a){Yc.add(p);const x=document.activeElement;if(!a.contains(x)){const g=new CustomEvent(ji,Kc);a.addEventListener(ji,c),a.dispatchEvent(g),g.defaultPrevented||(jy(Oy(qc(a)),{select:!0}),document.activeElement===x&&jn(a))}return()=>{a.removeEventListener(ji,c),setTimeout(()=>{const g=new CustomEvent(_i,Kc);a.addEventListener(_i,d),a.dispatchEvent(g),g.defaultPrevented||jn(x??document.body,{select:!0}),a.removeEventListener(_i,d),Yc.remove(p)},0)}}},[a,c,d,p]);const v=m.useCallback(x=>{if(!n&&!r||p.paused)return;const y=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,g=document.activeElement;if(y&&g){const b=x.currentTarget,[T,k]=_y(b);T&&k?!x.shiftKey&&g===k?(x.preventDefault(),n&&jn(T,{select:!0})):x.shiftKey&&g===T&&(x.preventDefault(),n&&jn(k,{select:!0})):g===b&&x.preventDefault()}},[n,r,p.paused]);return u.jsx(Se.div,{tabIndex:-1,...i,ref:h,onKeyDown:v})});Wo.displayName=Ay;function jy(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(jn(r,{select:t}),document.activeElement!==n)return}function _y(e){const t=qc(e),n=Gc(t,e),r=Gc(t.reverse(),e);return[n,r]}function qc(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 Gc(e,t){for(const n of e)if(!My(n,{upTo:t}))return n}function My(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 Ry(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&&Ry(e)&&t&&e.select()}}var Yc=Py();function Py(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Xc(e,t),e.unshift(t)},remove(t){var n;e=Xc(e,t),(n=e[0])==null||n.resume()}}}function Xc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Oy(e){return e.filter(t=>t.tagName!=="A")}var Dy=m[" useId ".trim().toString()]||(()=>{}),Ly=0;function $t(e){const[t,n]=m.useState(Dy());return Nt(()=>{n(r=>r??String(Ly++))},[e]),t?`radix-${t}`:""}const $y=["top","right","bottom","left"],_n=Math.min,Gt=Math.max,Vo=Math.round,Ko=Math.floor,pn=e=>({x:e,y:e}),Fy={left:"right",right:"left",bottom:"top",top:"bottom"},By={start:"end",end:"start"};function Mi(e,t,n){return Gt(e,_n(t,n))}function kn(e,t){return typeof e=="function"?e(t):e}function En(e){return e.split("-")[0]}function mr(e){return e.split("-")[1]}function Ri(e){return e==="x"?"y":"x"}function Pi(e){return e==="y"?"height":"width"}const zy=new Set(["top","bottom"]);function mn(e){return zy.has(En(e))?"y":"x"}function Oi(e){return Ri(mn(e))}function Uy(e,t,n){n===void 0&&(n=!1);const r=mr(e),o=Oi(e),s=Pi(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=qo(i)),[i,qo(i)]}function Hy(e){const t=qo(e);return[Di(e),t,Di(t)]}function Di(e){return e.replace(/start|end/g,t=>By[t])}const Jc=["left","right"],Zc=["right","left"],Wy=["top","bottom"],Vy=["bottom","top"];function Ky(e,t,n){switch(e){case"top":case"bottom":return n?t?Zc:Jc:t?Jc:Zc;case"left":case"right":return t?Wy:Vy;default:return[]}}function qy(e,t,n,r){const o=mr(e);let s=Ky(En(e),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),t&&(s=s.concat(s.map(Di)))),s}function qo(e){return e.replace(/left|right|bottom|top/g,t=>Fy[t])}function Gy(e){return{top:0,right:0,bottom:0,left:0,...e}}function Qc(e){return typeof e!="number"?Gy(e):{top:e,right:e,bottom:e,left:e}}function Go(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 eu(e,t,n){let{reference:r,floating:o}=e;const s=mn(t),i=Oi(t),a=Pi(i),l=En(t),c=s==="y",d=r.x+r.width/2-o.width/2,f=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:f};break;case"left":p={x:r.x-o.width,y:f};break;default:p={x:r.x,y:r.y}}switch(mr(t)){case"start":p[i]-=h*(n&&c?-1:1);break;case"end":p[i]+=h*(n&&c?-1:1);break}return p}const Yy=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}=eu(c,r,l),h=r,p={},v=0;for(let x=0;x<a.length;x++){const{name:y,fn:g}=a[x],{x:b,y:T,data:k,reset:S}=await g({x:d,y:f,initialPlacement:r,placement:h,strategy:o,middlewareData:p,rects:c,platform:i,elements:{reference:e,floating:t}});d=b??d,f=T??f,p={...p,[y]:{...p[y],...k}},S&&v<=50&&(v++,typeof S=="object"&&(S.placement&&(h=S.placement),S.rects&&(c=S.rects===!0?await i.getElementRects({reference:e,floating:t,strategy:o}):S.rects),{x:d,y:f}=eu(c,h,l)),x=-1)}return{x:d,y:f,placement:h,strategy:o,middlewareData:p}};async function Fr(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:h=!1,padding:p=0}=kn(t,e),v=Qc(p),y=a[h?f==="floating"?"reference":"floating":f],g=Go(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(y)))==null||n?y:y.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),b=f==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),k=await(s.isElement==null?void 0:s.isElement(T))?await(s.getScale==null?void 0:s.getScale(T))||{x:1,y:1}:{x:1,y:1},S=Go(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:T,strategy:l}):b);return{top:(g.top-S.top+v.top)/k.y,bottom:(S.bottom-g.bottom+v.bottom)/k.y,left:(g.left-S.left+v.left)/k.x,right:(S.right-g.right+v.right)/k.x}}const Xy=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}=kn(e,t)||{};if(c==null)return{};const f=Qc(d),h={x:n,y:r},p=Oi(o),v=Pi(p),x=await i.getDimensions(c),y=p==="y",g=y?"top":"left",b=y?"bottom":"right",T=y?"clientHeight":"clientWidth",k=s.reference[v]+s.reference[p]-h[p]-s.floating[v],S=h[p]-s.reference[p],C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=C?C[T]:0;(!E||!await(i.isElement==null?void 0:i.isElement(C)))&&(E=a.floating[T]||s.floating[v]);const A=k/2-S/2,R=E/2-x[v]/2-1,D=_n(f[g],R),B=_n(f[b],R),Y=D,G=E-x[v]-B,M=E/2-x[v]/2+A,j=Mi(Y,M,G),I=!l.arrow&&mr(o)!=null&&M!==j&&s.reference[v]/2-(M<Y?D:B)-x[v]/2<0,U=I?M<Y?M-Y:M-G:0;return{[p]:h[p]+U,data:{[p]:j,centerOffset:M-j-U,...I&&{alignmentOffset:U}},reset:I}}}),Jy=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:f=!0,fallbackPlacements:h,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:x=!0,...y}=kn(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const g=En(o),b=mn(a),T=En(a)===a,k=await(l.isRTL==null?void 0:l.isRTL(c.floating)),S=h||(T||!x?[qo(a)]:Hy(a)),C=v!=="none";!h&&C&&S.push(...qy(a,x,v,k));const E=[a,...S],A=await Fr(t,y),R=[];let D=((r=s.flip)==null?void 0:r.overflows)||[];if(d&&R.push(A[g]),f){const M=Uy(o,i,k);R.push(A[M[0]],A[M[1]])}if(D=[...D,{placement:o,overflows:R}],!R.every(M=>M<=0)){var B,Y;const M=(((B=s.flip)==null?void 0:B.index)||0)+1,j=E[M];if(j&&(!(f==="alignment"?b!==mn(j):!1)||D.every($=>mn($.placement)===b?$.overflows[0]>0:!0)))return{data:{index:M,overflows:D},reset:{placement:j}};let I=(Y=D.filter(U=>U.overflows[0]<=0).sort((U,$)=>U.overflows[1]-$.overflows[1])[0])==null?void 0:Y.placement;if(!I)switch(p){case"bestFit":{var G;const U=(G=D.filter($=>{if(C){const P=mn($.placement);return P===b||P==="y"}return!0}).map($=>[$.placement,$.overflows.filter(P=>P>0).reduce((P,q)=>P+q,0)]).sort(($,P)=>$[1]-P[1])[0])==null?void 0:G[0];U&&(I=U);break}case"initialPlacement":I=a;break}if(o!==I)return{reset:{placement:I}}}return{}}}};function tu(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function nu(e){return $y.some(t=>e[t]>=0)}const Zy=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=kn(e,t);switch(r){case"referenceHidden":{const s=await Fr(t,{...o,elementContext:"reference"}),i=tu(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:nu(i)}}}case"escaped":{const s=await Fr(t,{...o,altBoundary:!0}),i=tu(s,n.floating);return{data:{escapedOffsets:i,escaped:nu(i)}}}default:return{}}}}},ru=new Set(["left","top"]);async function Qy(e,t){const{placement:n,platform:r,elements:o}=e,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=En(n),a=mr(n),l=mn(n)==="y",c=ru.has(i)?-1:1,d=s&&l?-1:1,f=kn(t,e);let{mainAxis:h,crossAxis:p,alignmentAxis:v}=typeof f=="number"?{mainAxis:f,crossAxis:0,alignmentAxis:null}:{mainAxis:f.mainAxis||0,crossAxis:f.crossAxis||0,alignmentAxis:f.alignmentAxis};return a&&typeof v=="number"&&(p=a==="end"?v*-1:v),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}const ev=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 Qy(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}}}}},tv=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:y=>{let{x:g,y:b}=y;return{x:g,y:b}}},...l}=kn(e,t),c={x:n,y:r},d=await Fr(t,l),f=mn(En(o)),h=Ri(f);let p=c[h],v=c[f];if(s){const y=h==="y"?"top":"left",g=h==="y"?"bottom":"right",b=p+d[y],T=p-d[g];p=Mi(b,p,T)}if(i){const y=f==="y"?"top":"left",g=f==="y"?"bottom":"right",b=v+d[y],T=v-d[g];v=Mi(b,v,T)}const x=a.fn({...t,[h]:p,[f]:v});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[h]:s,[f]:i}}}}}},nv=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}=kn(e,t),d={x:n,y:r},f=mn(o),h=Ri(f);let p=d[h],v=d[f];const x=kn(a,t),y=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(l){const T=h==="y"?"height":"width",k=s.reference[h]-s.floating[T]+y.mainAxis,S=s.reference[h]+s.reference[T]-y.mainAxis;p<k?p=k:p>S&&(p=S)}if(c){var g,b;const T=h==="y"?"width":"height",k=ru.has(En(o)),S=s.reference[f]-s.floating[T]+(k&&((g=i.offset)==null?void 0:g[f])||0)+(k?0:y.crossAxis),C=s.reference[f]+s.reference[T]+(k?0:((b=i.offset)==null?void 0:b[f])||0)-(k?y.crossAxis:0);v<S?v=S:v>C&&(v=C)}return{[h]:p,[f]:v}}}},rv=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}=kn(e,t),d=await Fr(t,c),f=En(o),h=mr(o),p=mn(o)==="y",{width:v,height:x}=s.floating;let y,g;f==="top"||f==="bottom"?(y=f,g=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(g=f,y=h==="end"?"top":"bottom");const b=x-d.top-d.bottom,T=v-d.left-d.right,k=_n(x-d[y],b),S=_n(v-d[g],T),C=!t.middlewareData.shift;let E=k,A=S;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(A=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(E=b),C&&!h){const D=Gt(d.left,0),B=Gt(d.right,0),Y=Gt(d.top,0),G=Gt(d.bottom,0);p?A=v-2*(D!==0||B!==0?D+B:Gt(d.left,d.right)):E=x-2*(Y!==0||G!==0?Y+G:Gt(d.top,d.bottom))}await l({...t,availableWidth:A,availableHeight:E});const R=await i.getDimensions(a.floating);return v!==R.width||x!==R.height?{reset:{rects:!0}}:{}}}};function Yo(){return typeof window<"u"}function gr(e){return ou(e)?(e.nodeName||"").toLowerCase():"#document"}function Yt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function gn(e){var t;return(t=(ou(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function ou(e){return Yo()?e instanceof Node||e instanceof Yt(e).Node:!1}function an(e){return Yo()?e instanceof Element||e instanceof Yt(e).Element:!1}function xn(e){return Yo()?e instanceof HTMLElement||e instanceof Yt(e).HTMLElement:!1}function su(e){return!Yo()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Yt(e).ShadowRoot}const ov=new Set(["inline","contents"]);function Br(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=ln(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!ov.has(o)}const sv=new Set(["table","td","th"]);function iv(e){return sv.has(gr(e))}const av=[":popover-open",":modal"];function Xo(e){return av.some(t=>{try{return e.matches(t)}catch{return!1}})}const lv=["transform","translate","scale","rotate","perspective"],cv=["transform","translate","scale","rotate","perspective","filter"],uv=["paint","layout","strict","content"];function Li(e){const t=$i(),n=an(e)?ln(e):e;return lv.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)||cv.some(r=>(n.willChange||"").includes(r))||uv.some(r=>(n.contain||"").includes(r))}function dv(e){let t=Mn(e);for(;xn(t)&&!xr(t);){if(Li(t))return t;if(Xo(t))return null;t=Mn(t)}return null}function $i(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const fv=new Set(["html","body","#document"]);function xr(e){return fv.has(gr(e))}function ln(e){return Yt(e).getComputedStyle(e)}function Jo(e){return an(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Mn(e){if(gr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||su(e)&&e.host||gn(e);return su(t)?t.host:t}function iu(e){const t=Mn(e);return xr(t)?e.ownerDocument?e.ownerDocument.body:e.body:xn(t)&&Br(t)?t:iu(t)}function zr(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=iu(e),s=o===((r=e.ownerDocument)==null?void 0:r.body),i=Yt(o);if(s){const a=Fi(i);return t.concat(i,i.visualViewport||[],Br(o)?o:[],a&&n?zr(a):[])}return t.concat(o,zr(o,[],n))}function Fi(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function au(e){const t=ln(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=xn(e),s=o?e.offsetWidth:n,i=o?e.offsetHeight:r,a=Vo(n)!==s||Vo(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function Bi(e){return an(e)?e:e.contextElement}function yr(e){const t=Bi(e);if(!xn(t))return pn(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=au(t);let i=(s?Vo(n.width):n.width)/r,a=(s?Vo(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const hv=pn(0);function lu(e){const t=Yt(e);return!$i()||!t.visualViewport?hv:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function pv(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Yt(e)?!1:t}function Gn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=Bi(e);let i=pn(1);t&&(r?an(r)&&(i=yr(r)):i=yr(e));const a=pv(s,n,r)?lu(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 h=Yt(s),p=r&&an(r)?Yt(r):r;let v=h,x=Fi(v);for(;x&&r&&p!==v;){const y=yr(x),g=x.getBoundingClientRect(),b=ln(x),T=g.left+(x.clientLeft+parseFloat(b.paddingLeft))*y.x,k=g.top+(x.clientTop+parseFloat(b.paddingTop))*y.y;l*=y.x,c*=y.y,d*=y.x,f*=y.y,l+=T,c+=k,v=Yt(x),x=Fi(v)}}return Go({width:d,height:f,x:l,y:c})}function Zo(e,t){const n=Jo(e).scrollLeft;return t?t.left+n:Gn(gn(e)).left+n}function cu(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Zo(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function mv(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const s=o==="fixed",i=gn(r),a=t?Xo(t.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=pn(1);const d=pn(0),f=xn(r);if((f||!f&&!s)&&((gr(r)!=="body"||Br(i))&&(l=Jo(r)),xn(r))){const p=Gn(r);c=yr(r),d.x=p.x+r.clientLeft,d.y=p.y+r.clientTop}const h=i&&!f&&!s?cu(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+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}}function gv(e){return Array.from(e.getClientRects())}function xv(e){const t=gn(e),n=Jo(e),r=e.ownerDocument.body,o=Gt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Gt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+Zo(e);const a=-n.scrollTop;return ln(r).direction==="rtl"&&(i+=Gt(t.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}const uu=25;function yv(e,t){const n=Yt(e),r=gn(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=$i();(!d||d&&t==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}const c=Zo(r);if(c<=0){const d=r.ownerDocument,f=d.body,h=getComputedStyle(f),p=d.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,v=Math.abs(r.clientWidth-f.clientWidth-p);v<=uu&&(s-=v)}else c<=uu&&(s+=c);return{width:s,height:i,x:a,y:l}}const vv=new Set(["absolute","fixed"]);function bv(e,t){const n=Gn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,s=xn(e)?yr(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 du(e,t,n){let r;if(t==="viewport")r=yv(e,n);else if(t==="document")r=xv(gn(e));else if(an(t))r=bv(t,n);else{const o=lu(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return Go(r)}function fu(e,t){const n=Mn(e);return n===t||!an(n)||xr(n)?!1:ln(n).position==="fixed"||fu(n,t)}function wv(e,t){const n=t.get(e);if(n)return n;let r=zr(e,[],!1).filter(a=>an(a)&&gr(a)!=="body"),o=null;const s=ln(e).position==="fixed";let i=s?Mn(e):e;for(;an(i)&&!xr(i);){const a=ln(i),l=Li(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&vv.has(o.position)||Br(i)&&!l&&fu(e,i))?r=r.filter(d=>d!==i):o=a,i=Mn(i)}return t.set(e,r),r}function Sv(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[...n==="clippingAncestors"?Xo(t)?[]:wv(t,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,d)=>{const f=du(t,d,o);return c.top=Gt(f.top,c.top),c.right=_n(f.right,c.right),c.bottom=_n(f.bottom,c.bottom),c.left=Gt(f.left,c.left),c},du(t,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Cv(e){const{width:t,height:n}=au(e);return{width:t,height:n}}function Tv(e,t,n){const r=xn(t),o=gn(t),s=n==="fixed",i=Gn(e,!0,s,t);let a={scrollLeft:0,scrollTop:0};const l=pn(0);function c(){l.x=Zo(o)}if(r||!r&&!s)if((gr(t)!=="body"||Br(o))&&(a=Jo(t)),r){const p=Gn(t,!0,s,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else o&&c();s&&!r&&o&&c();const d=o&&!r&&!s?cu(o,a):pn(0),f=i.left+a.scrollLeft-l.x-d.x,h=i.top+a.scrollTop-l.y-d.y;return{x:f,y:h,width:i.width,height:i.height}}function zi(e){return ln(e).position==="static"}function hu(e,t){if(!xn(e)||ln(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return gn(e)===n&&(n=n.ownerDocument.body),n}function pu(e,t){const n=Yt(e);if(Xo(e))return n;if(!xn(e)){let o=Mn(e);for(;o&&!xr(o);){if(an(o)&&!zi(o))return o;o=Mn(o)}return n}let r=hu(e,t);for(;r&&iv(r)&&zi(r);)r=hu(r,t);return r&&xr(r)&&zi(r)&&!Li(r)?n:r||dv(e)||n}const kv=async function(e){const t=this.getOffsetParent||pu,n=this.getDimensions,r=await n(e.floating);return{reference:Tv(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Ev(e){return ln(e).direction==="rtl"}const Iv={convertOffsetParentRelativeRectToViewportRelativeRect:mv,getDocumentElement:gn,getClippingRect:Sv,getOffsetParent:pu,getElementRects:kv,getClientRects:gv,getDimensions:Cv,getScale:yr,isElement:an,isRTL:Ev};function mu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Nv(e,t){let n=null,r;const o=gn(e);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:f,width:h,height:p}=c;if(a||t(),!h||!p)return;const v=Ko(f),x=Ko(o.clientWidth-(d+h)),y=Ko(o.clientHeight-(f+p)),g=Ko(d),T={rootMargin:-v+"px "+-x+"px "+-y+"px "+-g+"px",threshold:Gt(0,_n(1,l))||1};let k=!0;function S(C){const E=C[0].intersectionRatio;if(E!==l){if(!k)return i();E?i(!1,E):r=setTimeout(()=>{i(!1,1e-7)},1e3)}E===1&&!mu(c,e.getBoundingClientRect())&&i(),k=!1}try{n=new IntersectionObserver(S,{...T,root:o.ownerDocument})}catch{n=new IntersectionObserver(S,T)}n.observe(e)}return i(!0),s}function Av(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=Bi(e),d=o||s?[...c?zr(c):[],...zr(t)]:[];d.forEach(g=>{o&&g.addEventListener("scroll",n,{passive:!0}),s&&g.addEventListener("resize",n)});const f=c&&a?Nv(c,n):null;let h=-1,p=null;i&&(p=new ResizeObserver(g=>{let[b]=g;b&&b.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var T;(T=p)==null||T.observe(t)})),n()}),c&&!l&&p.observe(c),p.observe(t));let v,x=l?Gn(e):null;l&&y();function y(){const g=Gn(e);x&&!mu(x,g)&&n(),x=g,v=requestAnimationFrame(y)}return n(),()=>{var g;d.forEach(b=>{o&&b.removeEventListener("scroll",n),s&&b.removeEventListener("resize",n)}),f==null||f(),(g=p)==null||g.disconnect(),p=null,l&&cancelAnimationFrame(v)}}const jv=ev,_v=tv,Mv=Jy,Rv=rv,Pv=Zy,gu=Xy,Ov=nv,Dv=(e,t,n)=>{const r=new Map,o={platform:Iv,...n},s={...o.platform,_c:r};return Yy(e,t,{...o,platform:s})};var Lv=typeof document<"u",$v=function(){},Qo=Lv?w.useLayoutEffect:$v;function es(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(!es(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)&&!es(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function xu(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function yu(e,t){const n=xu(e);return Math.round(t*n)/n}function Ui(e){const t=m.useRef(e);return Qo(()=>{t.current=e}),t}function Fv(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]=m.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=m.useState(r);es(h,r)||p(r);const[v,x]=m.useState(null),[y,g]=m.useState(null),b=m.useCallback($=>{$!==C.current&&(C.current=$,x($))},[]),T=m.useCallback($=>{$!==E.current&&(E.current=$,g($))},[]),k=s||v,S=i||y,C=m.useRef(null),E=m.useRef(null),A=m.useRef(d),R=l!=null,D=Ui(l),B=Ui(o),Y=Ui(c),G=m.useCallback(()=>{if(!C.current||!E.current)return;const $={placement:t,strategy:n,middleware:h};B.current&&($.platform=B.current),Dv(C.current,E.current,$).then(P=>{const q={...P,isPositioned:Y.current!==!1};M.current&&!es(A.current,q)&&(A.current=q,wo.flushSync(()=>{f(q)}))})},[h,t,n,B,Y]);Qo(()=>{c===!1&&A.current.isPositioned&&(A.current.isPositioned=!1,f($=>({...$,isPositioned:!1})))},[c]);const M=m.useRef(!1);Qo(()=>(M.current=!0,()=>{M.current=!1}),[]),Qo(()=>{if(k&&(C.current=k),S&&(E.current=S),k&&S){if(D.current)return D.current(k,S,G);G()}},[k,S,G,D,R]);const j=m.useMemo(()=>({reference:C,floating:E,setReference:b,setFloating:T}),[b,T]),I=m.useMemo(()=>({reference:k,floating:S}),[k,S]),U=m.useMemo(()=>{const $={position:n,left:0,top:0};if(!I.floating)return $;const P=yu(I.floating,d.x),q=yu(I.floating,d.y);return a?{...$,transform:"translate("+P+"px, "+q+"px)",...xu(I.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:P,top:q}},[n,a,I.floating,d.x,d.y]);return m.useMemo(()=>({...d,update:G,refs:j,elements:I,floatingStyles:U}),[d,G,j,I,U])}const Bv=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?gu({element:r.current,padding:o}).fn(n):{}:r?gu({element:r,padding:o}).fn(n):{}}}},zv=(e,t)=>({...jv(e),options:[e,t]}),Uv=(e,t)=>({..._v(e),options:[e,t]}),Hv=(e,t)=>({...Ov(e),options:[e,t]}),Wv=(e,t)=>({...Mv(e),options:[e,t]}),Vv=(e,t)=>({...Rv(e),options:[e,t]}),Kv=(e,t)=>({...Pv(e),options:[e,t]}),qv=(e,t)=>({...Bv(e),options:[e,t]});var Gv="Arrow",vu=m.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...s}=e;return u.jsx(Se.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"})})});vu.displayName=Gv;var Yv=vu;function bu(e){const[t,n]=m.useState(void 0);return Nt(()=>{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 Hi="Popper",[wu,ts]=Tn(Hi),[Xv,Su]=wu(Hi),Cu=e=>{const{__scopePopper:t,children:n}=e,[r,o]=m.useState(null);return u.jsx(Xv,{scope:t,anchor:r,onAnchorChange:o,children:n})};Cu.displayName=Hi;var Tu="PopperAnchor",ku=m.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,s=Su(Tu,n),i=m.useRef(null),a=We(t,i),l=m.useRef(null);return m.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(Se.div,{...o,ref:a})});ku.displayName=Tu;var Wi="PopperContent",[Jv,Zv]=wu(Wi),Eu=m.forwardRef((e,t)=>{var W,O,K,z,te,X;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:d=0,sticky:f="partial",hideWhenDetached:h=!1,updatePositionStrategy:p="optimized",onPlaced:v,...x}=e,y=Su(Wi,n),[g,b]=m.useState(null),T=We(t,ge=>b(ge)),[k,S]=m.useState(null),C=bu(k),E=(C==null?void 0:C.width)??0,A=(C==null?void 0:C.height)??0,R=r+(s!=="center"?"-"+s:""),D=typeof d=="number"?d:{top:0,right:0,bottom:0,left:0,...d},B=Array.isArray(c)?c:[c],Y=B.length>0,G={padding:D,boundary:B.filter(eb),altBoundary:Y},{refs:M,floatingStyles:j,placement:I,isPositioned:U,middlewareData:$}=Fv({strategy:"fixed",placement:R,whileElementsMounted:(...ge)=>Av(...ge,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[zv({mainAxis:o+A,alignmentAxis:i}),l&&Uv({mainAxis:!0,crossAxis:!1,limiter:f==="partial"?Hv():void 0,...G}),l&&Wv({...G}),Vv({...G,apply:({elements:ge,rects:le,availableWidth:oe,availableHeight:me})=>{const{width:be,height:Me}=le.reference,Ce=ge.floating.style;Ce.setProperty("--radix-popper-available-width",`${oe}px`),Ce.setProperty("--radix-popper-available-height",`${me}px`),Ce.setProperty("--radix-popper-anchor-width",`${be}px`),Ce.setProperty("--radix-popper-anchor-height",`${Me}px`)}}),k&&qv({element:k,padding:a}),tb({arrowWidth:E,arrowHeight:A}),h&&Kv({strategy:"referenceHidden",...G})]}),[P,q]=Au(I),Z=At(v);Nt(()=>{U&&(Z==null||Z())},[U,Z]);const _=(W=$.arrow)==null?void 0:W.x,Q=(O=$.arrow)==null?void 0:O.y,V=((K=$.arrow)==null?void 0:K.centerOffset)!==0,[H,ne]=m.useState();return Nt(()=>{g&&ne(window.getComputedStyle(g).zIndex)},[g]),u.jsx("div",{ref:M.setFloating,"data-radix-popper-content-wrapper":"",style:{...j,transform:U?j.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:H,"--radix-popper-transform-origin":[(z=$.transformOrigin)==null?void 0:z.x,(te=$.transformOrigin)==null?void 0:te.y].join(" "),...((X=$.hide)==null?void 0:X.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:u.jsx(Jv,{scope:n,placedSide:P,onArrowChange:S,arrowX:_,arrowY:Q,shouldHideArrow:V,children:u.jsx(Se.div,{"data-side":P,"data-align":q,...x,ref:T,style:{...x.style,animation:U?void 0:"none"}})})})});Eu.displayName=Wi;var Iu="PopperArrow",Qv={top:"bottom",right:"left",bottom:"top",left:"right"},Nu=m.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,s=Zv(Iu,r),i=Qv[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(Yv,{...o,ref:n,style:{...o.style,display:"block"}})})});Nu.displayName=Iu;function eb(e){return e!==null}var tb=e=>({name:"transformOrigin",options:e,fn(t){var y,g,b;const{placement:n,rects:r,middlewareData:o}=t,i=((y=o.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,d]=Au(n),f={start:"0%",center:"50%",end:"100%"}[d],h=(((g=o.arrow)==null?void 0:g.x)??0)+a/2,p=(((b=o.arrow)==null?void 0:b.y)??0)+l/2;let v="",x="";return c==="bottom"?(v=i?f:`${h}px`,x=`${-l}px`):c==="top"?(v=i?f:`${h}px`,x=`${r.floating.height+l}px`):c==="right"?(v=`${-l}px`,x=i?f:`${p}px`):c==="left"&&(v=`${r.floating.width+l}px`,x=i?f:`${p}px`),{data:{x:v,y:x}}}});function Au(e){const[t,n="center"]=e.split("-");return[t,n]}var ju=Cu,_u=ku,Mu=Eu,Ru=Nu,nb="Portal",ns=m.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=m.useState(!1);Nt(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?si.createPortal(u.jsx(Se.div,{...r,ref:t}),i):null});ns.displayName=nb;function rb(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Zt=e=>{const{present:t,children:n}=e,r=ob(t),o=typeof n=="function"?n({present:r.isPresent}):m.Children.only(n),s=We(r.ref,sb(o));return typeof n=="function"||r.isPresent?m.cloneElement(o,{ref:s}):null};Zt.displayName="Presence";function ob(e){const[t,n]=m.useState(),r=m.useRef(null),o=m.useRef(e),s=m.useRef("none"),i=e?"mounted":"unmounted",[a,l]=rb(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return m.useEffect(()=>{const c=rs(r.current);s.current=a==="mounted"?c:"none"},[a]),Nt(()=>{const c=r.current,d=o.current;if(d!==e){const h=s.current,p=rs(c);e?l("MOUNT"):p==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&h!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Nt(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,f=p=>{const x=rs(r.current).includes(CSS.escape(p.animationName));if(p.target===t&&x&&(l("ANIMATION_END"),!o.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},h=p=>{p.target===t&&(s.current=rs(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:m.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function rs(e){return(e==null?void 0:e.animationName)||"none"}function sb(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 Vi="rovingFocusGroup.onEntryFocus",ib={bubbles:!1,cancelable:!0},Ur="RovingFocusGroup",[Ki,Pu,ab]=Ei(Ur),[lb,Ou]=Tn(Ur,[ab]),[cb,ub]=lb(Ur),Du=m.forwardRef((e,t)=>u.jsx(Ki.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Ki.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(db,{...e,ref:t})})}));Du.displayName=Ur;var db=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:d=!1,...f}=e,h=m.useRef(null),p=We(t,h),v=Uo(s),[x,y]=pr({prop:i,defaultProp:a??null,onChange:l,caller:Ur}),[g,b]=m.useState(!1),T=At(c),k=Pu(n),S=m.useRef(!1),[C,E]=m.useState(0);return m.useEffect(()=>{const A=h.current;if(A)return A.addEventListener(Vi,T),()=>A.removeEventListener(Vi,T)},[T]),u.jsx(cb,{scope:n,orientation:r,dir:v,loop:o,currentTabStopId:x,onItemFocus:m.useCallback(A=>y(A),[y]),onItemShiftTab:m.useCallback(()=>b(!0),[]),onFocusableItemAdd:m.useCallback(()=>E(A=>A+1),[]),onFocusableItemRemove:m.useCallback(()=>E(A=>A-1),[]),children:u.jsx(Se.div,{tabIndex:g||C===0?-1:0,"data-orientation":r,...f,ref:p,style:{outline:"none",...e.style},onMouseDown:he(e.onMouseDown,()=>{S.current=!0}),onFocus:he(e.onFocus,A=>{const R=!S.current;if(A.target===A.currentTarget&&R&&!g){const D=new CustomEvent(Vi,ib);if(A.currentTarget.dispatchEvent(D),!D.defaultPrevented){const B=k().filter(I=>I.focusable),Y=B.find(I=>I.active),G=B.find(I=>I.id===x),j=[Y,G,...B].filter(Boolean).map(I=>I.ref.current);Fu(j,d)}}S.current=!1}),onBlur:he(e.onBlur,()=>b(!1))})})}),Lu="RovingFocusGroupItem",$u=m.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,children:i,...a}=e,l=$t(),c=s||l,d=ub(Lu,n),f=d.currentTabStopId===c,h=Pu(n),{onFocusableItemAdd:p,onFocusableItemRemove:v,currentTabStopId:x}=d;return m.useEffect(()=>{if(r)return p(),()=>v()},[r,p,v]),u.jsx(Ki.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:u.jsx(Se.span,{tabIndex:f?0:-1,"data-orientation":d.orientation,...a,ref:t,onMouseDown:he(e.onMouseDown,y=>{r?d.onItemFocus(c):y.preventDefault()}),onFocus:he(e.onFocus,()=>d.onItemFocus(c)),onKeyDown:he(e.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){d.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const g=pb(y,d.orientation,d.dir);if(g!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let T=h().filter(k=>k.focusable).map(k=>k.ref.current);if(g==="last")T.reverse();else if(g==="prev"||g==="next"){g==="prev"&&T.reverse();const k=T.indexOf(y.currentTarget);T=d.loop?mb(T,k+1):T.slice(k+1)}setTimeout(()=>Fu(T))}}),children:typeof i=="function"?i({isCurrentTabStop:f,hasTabStop:x!=null}):i})})});$u.displayName=Lu;var fb={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function hb(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function pb(e,t,n){const r=hb(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return fb[r]}function Fu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function mb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var gb=Du,xb=$u,yb=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},vr=new WeakMap,os=new WeakMap,ss={},qi=0,Bu=function(e){return e&&(e.host||Bu(e.parentNode))},vb=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Bu(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})},bb=function(e,t,n,r){var o=vb(t,Array.isArray(e)?e:[e]);ss[n]||(ss[n]=new WeakMap);var s=ss[n],i=[],a=new Set,l=new Set(o),c=function(f){!f||a.has(f)||(a.add(f),c(f.parentNode))};o.forEach(c);var d=function(f){!f||l.has(f)||Array.prototype.forEach.call(f.children,function(h){if(a.has(h))d(h);else try{var p=h.getAttribute(r),v=p!==null&&p!=="false",x=(vr.get(h)||0)+1,y=(s.get(h)||0)+1;vr.set(h,x),s.set(h,y),i.push(h),x===1&&v&&os.set(h,!0),y===1&&h.setAttribute(n,"true"),v||h.setAttribute(r,"true")}catch(g){console.error("aria-hidden: cannot operate on ",h,g)}})};return d(t),a.clear(),qi++,function(){i.forEach(function(f){var h=vr.get(f)-1,p=s.get(f)-1;vr.set(f,h),s.set(f,p),h||(os.has(f)||f.removeAttribute(r),os.delete(f)),p||f.removeAttribute(n)}),qi--,qi||(vr=new WeakMap,vr=new WeakMap,os=new WeakMap,ss={})}},Gi=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=yb(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),bb(r,o,n,"aria-hidden")):function(){return null}},yn=function(){return yn=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},yn.apply(this,arguments)};function zu(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 wb(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 is="right-scroll-bar-position",as="width-before-scroll-bar",Sb="with-scroll-bars-hidden",Cb="--removed-body-scroll-bar-size";function Yi(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Tb(e,t){var n=w.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var kb=typeof window<"u"?m.useLayoutEffect:m.useEffect,Uu=new WeakMap;function Eb(e,t){var n=Tb(null,function(r){return e.forEach(function(o){return Yi(o,r)})});return kb(function(){var r=Uu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Yi(a,null)}),s.forEach(function(a){o.has(a)||Yi(a,i)})}Uu.set(n,e)},[e]),n}function Ib(e){return e}function Nb(e,t){t===void 0&&(t=Ib);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 Ab(e){e===void 0&&(e={});var t=Nb(null);return t.options=yn({async:!0,ssr:!1},e),t}var Hu=function(e){var t=e.sideCar,n=zu(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return m.createElement(r,yn({},n))};Hu.isSideCarExport=!0;function jb(e,t){return e.useMedium(t),Hu}var Wu=Ab(),Xi=function(){},ls=m.forwardRef(function(e,t){var n=m.useRef(null),r=m.useState({onScrollCapture:Xi,onWheelCapture:Xi,onTouchMoveCapture:Xi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,f=e.shards,h=e.sideCar,p=e.noRelative,v=e.noIsolation,x=e.inert,y=e.allowPinchZoom,g=e.as,b=g===void 0?"div":g,T=e.gapMode,k=zu(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,C=Eb([n,t]),E=yn(yn({},k),o);return m.createElement(m.Fragment,null,d&&m.createElement(S,{sideCar:Wu,removeScrollBar:c,shards:f,noRelative:p,noIsolation:v,inert:x,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:T}),i?m.cloneElement(m.Children.only(a),yn(yn({},E),{ref:C})):m.createElement(b,yn({},E,{className:l,ref:C}),a))});ls.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},ls.classNames={fullWidth:as,zeroRight:is};var _b=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Mb(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=_b();return t&&e.setAttribute("nonce",t),e}function Rb(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Pb(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Ob=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Mb())&&(Rb(t,n),Pb(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Db=function(){var e=Ob();return function(t,n){m.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Vu=function(){var e=Db(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Lb={left:0,top:0,right:0,gap:0},Ji=function(e){return parseInt(e||"",10)||0},$b=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[Ji(n),Ji(r),Ji(o)]},Fb=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Lb;var t=$b(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])}},Bb=Vu(),br="data-scroll-locked",zb=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
@@ -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=Ch(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=Ch(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 Nh{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 Ah{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 $n{constructor(t){this.options=t||or,this.options.renderer=this.options.renderer||new Va,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new Nh,this.slugger=new Ah}static parse(t,n){return new $n(n).parse(t)}static parseInline(t,n){return new $n(n).parseInline(t)}parse(t,n=!0){let r="",o,s,i,a,l,c,d,f,h,p,v,x,y,g,b,T,k,S,C;const E=t.length;for(o=0;o<E;o++){if(p=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[p.type]&&(C=this.options.extensions.renderers[p.type].call({parser:this},p),C!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(p.type))){r+=C||"";continue}switch(p.type){case"space":continue;case"hr":{r+=this.renderer.hr();continue}case"heading":{r+=this.renderer.heading(this.parseInline(p.tokens),p.depth,Sh(this.parseInline(p.tokens,this.textRenderer)),this.slugger);continue}case"code":{r+=this.renderer.code(p.text,p.lang,p.escaped);continue}case"table":{for(f="",d="",a=p.header.length,s=0;s<a;s++)d+=this.renderer.tablecell(this.parseInline(p.header[s].tokens),{header:!0,align:p.align[s]});for(f+=this.renderer.tablerow(d),h="",a=p.rows.length,s=0;s<a;s++){for(c=p.rows[s],d="",l=c.length,i=0;i<l;i++)d+=this.renderer.tablecell(this.parseInline(c[i].tokens),{header:!1,align:p.align[i]});h+=this.renderer.tablerow(d)}r+=this.renderer.table(f,h);continue}case"blockquote":{h=this.parse(p.tokens),r+=this.renderer.blockquote(h);continue}case"list":{for(v=p.ordered,x=p.start,y=p.loose,a=p.items.length,h="",s=0;s<a;s++)b=p.items[s],T=b.checked,k=b.task,g="",b.task&&(S=this.renderer.checkbox(T),y?b.tokens.length>0&&b.tokens[0].type==="paragraph"?(b.tokens[0].text=S+" "+b.tokens[0].text,b.tokens[0].tokens&&b.tokens[0].tokens.length>0&&b.tokens[0].tokens[0].type==="text"&&(b.tokens[0].tokens[0].text=S+" "+b.tokens[0].tokens[0].text)):b.tokens.unshift({type:"text",text:S}):g+=S),g+=this.parse(b.tokens,y),h+=this.renderer.listitem(g,k,T);r+=this.renderer.list(h,v,x);continue}case"html":{r+=this.renderer.html(p.text);continue}case"paragraph":{r+=this.renderer.paragraph(this.parseInline(p.tokens));continue}case"text":{for(h=p.tokens?this.parseInline(p.tokens):p.text;o+1<E&&t[o+1].type==="text";)p=t[++o],h+=`
135
135
  `+(p.tokens?this.parseInline(p.tokens):p.text);r+=n?this.renderer.paragraph(h):h;continue}default:{const A='Token with "'+p.type+'" type was not found.';if(this.options.silent){console.error(A);return}else throw new Error(A)}}}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 Hs{constructor(t){this.options=t||or}preprocess(t){return t}postprocess(t){return t}}Am(Hs,"passThroughHooks",new Set(["preprocess","postprocess"]));function WC(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>"+Ot(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 jh(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...ve.defaults,...s};const i=WC(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(zC(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 h;if(!f)try{r.walkTokens&&ve.walkTokens(l,r.walkTokens),h=t(l,r),r.hooks&&(h=r.hooks.postprocess(h))}catch(p){f=p}return r.highlight=a,f?i(f):o(null,h)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;ve.walkTokens(l,function(f){f.type==="code"&&(d++,setTimeout(()=>{a(f.text,f.lang,function(h,p){if(h)return c(h);p!=null&&p!==f.text&&(f.text=p,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(ve.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&&ve.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function ve(e,t,n){return jh(Ln.lex,$n.parse)(e,t,n)}ve.options=ve.setOptions=function(e){return ve.defaults={...ve.defaults,...e},NC(ve.defaults),ve},ve.getDefaults=yh,ve.defaults=or,ve.use=function(...e){const t=ve.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=ve.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=ve.defaults.renderer||new Va;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=ve.defaults.tokenizer||new Wa;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=ve.defaults.hooks||new Hs;for(const s in n.hooks){const i=o[s];Hs.passThroughHooks.has(s)?o[s]=a=>{if(ve.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=ve.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}}ve.setOptions(r)})},ve.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(ve,r)),r.type){case"table":{for(const o of r.header)n=n.concat(ve.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(ve.walkTokens(s.tokens,t));break}case"list":{n=n.concat(ve.walkTokens(r.items,t));break}default:ve.defaults.extensions&&ve.defaults.extensions.childTokens&&ve.defaults.extensions.childTokens[r.type]?ve.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(ve.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(ve.walkTokens(r.tokens,t)))}return n},ve.parseInline=jh(Ln.lexInline,$n.parseInline),ve.Parser=$n,ve.parser=$n.parse,ve.Renderer=Va,ve.TextRenderer=Nh,ve.Lexer=Ln,ve.lexer=Ln.lex,ve.Tokenizer=Wa,ve.Slugger=Ah,ve.Hooks=Hs,ve.parse=ve,ve.options,ve.setOptions,ve.use,ve.walkTokens,ve.parseInline,$n.parse,Ln.lex;function co({content:e,className:t="",allowHtml:n=!1,style:r}){const o=w.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 ve.parse=="function"?ve.parse(i):ve(i)}return typeof ve.parse=="function"?ve.parse(e):ve(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=w.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:se("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 VC={MODE:"library"};function KC(){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:ii&&ii.tagName.toUpperCase()==="SCRIPT"&&ii.src||new URL("index.umd.js",document.baseURI).href}<"u"?VC: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 qC(){return!KC()}function GC(){return typeof window>"u"?!1:window.__ARTIFACT_DEBUG__===!0}function YC(){return qC()||GC()}function XC({preview:e,idx:t}){return w.useEffect(()=>{YC()&&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 uo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));uo.displayName="Card";const fo=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex flex-col space-y-1.5 p-6",e),...t}));fo.displayName="CardHeader";const ho=m.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:se("text-2xl font-semibold leading-none tracking-tight",e),...t}));ho.displayName="CardTitle";const _h=m.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:se("text-sm text-muted-foreground",e),...t}));_h.displayName="CardDescription";const po=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("p-6 pt-0",e),...t}));po.displayName="CardContent";const Mh=m.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:se("flex items-center p-6 pt-0",e),...t}));Mh.displayName="CardFooter";function JC({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=so(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(uo,{className:se("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(fo,{className:"pb-3",children:[u.jsx(ho,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(_h,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(po,{className:"pt-0 pb-3",children:a}),u.jsx(Mh,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(tt,{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(tt,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}const ZC="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 Rh({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:ZC,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:so(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:so(e)})}function QC({message:e,isStreaming:t=!1}){const n=e.name??"tool",r=w.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(ae.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 eT({message:e,viewMode:t,isStreaming:n=!1}){const o=Gf(e).name||"tool",s=l=>{if(l==null)return null;const c=typeof l=="string"?Ma(l)??l:l;if(c&&typeof c=="object")return u.jsx(Rh,{data:c});const d=typeof c=="string"?c:(()=>{try{return so(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}=eC(l);return d?u.jsx(co,{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 h=(l.text??"").trim();if(!h)return null;const p=Rs(h);return i(p)}const c=oo(l),d=Rs(c);return i(d)};return u.jsxs("div",{className:"space-y-2",children:[u.jsx(QC,{message:e,isStreaming:n}),t==="expanded"&&a()]})}function tT(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=Ha(),[o,s]=w.useState({}),[i,a]=w.useState(null),[l,c]=w.useState(!1),d=w.useCallback(()=>{c(!1),a(null)},[]),f=w.useCallback(p=>{a(p),c(!0)},[]),h=w.useCallback(async(p,v,x)=>{var y,g;if(!t){p.preventDefault();return}if(o[x]){p.preventDefault();return}try{const b=String(v.url??""),T=b.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(T){p.preventDefault();const k=T[1],S=v.name||`file_${k}`,C=v.mimeType||"application/octet-stream";f({id:k,name:S,mimeType:C});return}if(b.startsWith("data:")){p.preventDefault(),s(S=>({...S,[x]:!0}));const k=r({title:"Fetching file...",description:"",open:!0});try{const S=await cC(n??void 0);if(!S||!Array.isArray(S))throw new Error("Invalid file list response");const C=S.find(E=>!E||typeof E!="object"||!((E.filename??"")===(v.name??""))?!1:typeof v.size=="number"&&typeof E.size=="number"?E.size===v.size:!0);if(!(C!=null&&C.id))throw new Error(`File "${v.name}" is not yet available on the server`);if(!C.id||!C.filename)throw new Error("Invalid file data received from server");f({id:C.id,name:v.name||C.filename||`file_${C.id}`,mimeType:v.mimeType||C.mime_type||"application/octet-stream"}),(y=k.update)==null||y.call(k,{id:k.id,title:"Success",description:`Opened ${v.name}`,open:!0})}catch(S){console.error("Failed to fetch server file:",S);const C=S instanceof Error?S.message:"Unknown error occurred";(g=k.update)==null||g.call(k,{id:k.id,title:"Failed",description:C}),r({title:"Failed to fetch file",description:C,open:!0})}finally{s(S=>({...S,[x]:!1}))}}}catch(b){console.error("File click error:",b),s(T=>({...T,[x]:!1}))}},[t,o,r,n,f]);return{uploadingFiles:o,handleFileClick:h,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function nT({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:se("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(co,{content:e,allowHtml:!1}):u.jsxs("pre",{className:se("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(tt,{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(ae.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(ae.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function rT({className:e}){const[t,n]=w.useState(0);return w.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:se("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}function Ph(e){var n;const t=(n=e.additionalKwargs)==null?void 0:n.toolProgress;return Array.isArray(t)?t:[]}const Ws=w.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:h=!0,customStyles:p={},onEdit:v,onRegenerate:x,onCancelEdit:y,onCopy:g,activeInterrupt:b,disableInterruptActions:T=!1,onInterruptActionStart:k,onInterruptActionEnd:S,checkpointCandidates:C=[],activeCheckpointId:E=null,onSelectCheckpoint:A,defaultCheckpointId:R=null,messageParentCheckpointId:D=null}){const[B,Y]=w.useState(!1),[G,M]=w.useState("preview"),[j,I]=w.useState(!1),{currentThreadId:U}=Fo(),{respondToInterrupt:$}=Bo(),P=l==="phone"||l==="half-screen",q=t.role,Z=q==="tool",_=w.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),Q=!!_,V=!(r&&q!=="user"),{uploadingFiles:H,handleFileClick:ne,fileViewerOpen:W,currentFileInfo:O,closeFileViewer:K}=tT({allowFileOpen:V,currentThreadId:U}),z=w.useMemo(()=>{switch(q){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))]"}},[q]),te=w.useMemo(()=>{if(_)return"";const L=t.content;return Array.isArray(L)?tC(L):""},[_,t]),X=w.useMemo(()=>{if(_)return{};const L=t.content;return Array.isArray(L)?Gf(t):{}},[_,t]),ge=w.useMemo(()=>Z?!!(t.additionalKwargs??{}).toolStreaming:!1,[Z,t]),le=w.useMemo(()=>{if(_)return[];const L=t.content;return Array.isArray(L)?L.filter(ce=>ce.type==="image_url"):[]},[_,t]),oe=w.useMemo(()=>{if(_)return[];const L=t.content;return Array.isArray(L)?L.filter(ce=>ce.type==="file"):[]},[_,t]),me=w.useMemo(()=>{if(_)return[];const L=t.content;return Array.isArray(L)?L.filter(ce=>ce.type==="interrupt"):[]},[_,t]),be=(b==null?void 0:b.id)??(b==null?void 0:b.interrupt_id),Me=Ps(be),Ce=b==null?void 0:b.value,Ue=w.useMemo(()=>{if(_)return"";const L=t.content;return Array.isArray(L)?nC(L):""},[_,t]),et=w.useMemo(()=>{if(_||!h)return[];const ce=t.artifact;if(!ce)return[];const xe=[],Be=[...Array.isArray(ce.plots)?ce.plots:[]];for(const De of Be){const mt=aC(De);mt&&xe.push(mt)}return xe},[_,t,h]),rt=w.useCallback(async()=>{const L=Z?Ue:te;async function ce(xe){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(xe);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const Be=new Blob([xe],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":Be})]);return}throw new Error("Clipboard API not supported in this context.")}try{await ce(L),Y(!0),setTimeout(()=>Y(!1),2e3),g==null||g(L)}catch(xe){console.error("Failed to copy:",xe)}},[Z,Ue,te,g]),Ke=w.useCallback(()=>{if(!v)return;const L=Z?Ue:te,ce="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};v(t.id,L,ce)},[v,t.id,Z,Ue,te,t]),Ge=w.useCallback(()=>{x==null||x(n)},[x,n]),at=w.useCallback(()=>{const ce=se(P?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",z);switch(q){case"user":return u.jsx(ae.User,{className:ce});case"assistant":return u.jsx(ae.Bot,{className:ce});case"tool":return u.jsx(ae.Wrench,{className:ce});default:return u.jsx(ae.Bot,{className:ce})}},[P,z,q]),bt=w.useCallback(()=>{const L="group relative mb-4 flex w-full";switch(q){case"user":return se(L,"justify-end");case"assistant":case"tool":case"system":return se(L,"justify-start");default:return L}},[q]),ht=w.useCallback(()=>{const L=se("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",P&&"px-3 py-2 text-sm");if(Q)return se(L,"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(q){case"user":return se(L,"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 se(L,"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 se(L,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return se(L,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return se(L,"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")}},[P,Q,q]),Tt=w.useCallback(async L=>{if(T)return;const ce=Ps((L==null?void 0:L.id)??(L==null?void 0:L.interrupt_id));if(!ce){console.warn("Interrupt part missing id",L);return}try{k==null||k(),await $(ce,!0)}catch(xe){console.error("Failed to approve interrupt:",xe)}finally{S==null||S()}},[T,S,k,$]),Ie=w.useCallback(async L=>{if(T)return;const ce=Ps((L==null?void 0:L.id)??(L==null?void 0:L.interrupt_id));if(!ce){console.warn("Interrupt part missing id",L);return}try{k==null||k(),await $(ce,!1)}catch(xe){console.error("Failed to reject interrupt:",xe)}finally{S==null||S()}},[T,S,k,$]),Fe=w.useCallback(({part:L,i:ce})=>{if(L.type==="text"){const xe=L.text??"",Be=xe.trim(),De=Ma(Be);return De&&q!=="tool"?u.jsx(Rh,{data:De},ce):q==="user"&&c&&Be.length>d?u.jsx(nT,{text:Be,expanded:j,onExpandedChange:I,previewLength:d,isCompact:P},ce):u.jsx(co,{content:xe,allowHtml:!1},ce)}if(L.type==="image_url"){const xe=L;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:xe.url,alt:xe.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},ce)}if(L.type==="file"){const xe=L,Be=xe.name||"file";return u.jsxs("a",{href:xe.url,onClick:De=>ne(De.nativeEvent,xe,ce),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:[H[ce]?u.jsx(ae.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[Be,H[ce]?" (processing)":""]})]},ce)}if(L.type==="interrupt"){const xe=L,Be=Ps((xe==null?void 0:xe.id)??(xe==null?void 0:xe.interrupt_id)),De=!!(Me&&Be&&Be===Me),mt=De?Ce??(xe==null?void 0:xe.value):xe==null?void 0:xe.value,Xe=Be?{...xe,id:Be,interrupt_id:Be}:xe;return u.jsx(JC,{interruptPart:Xe,onApprove:Tt,onReject:Ie,disabled:T,isActive:De,payload:mt},ce)}return null},[ne,H,Tt,Ie,q,c,d,j,P,Me,Ce,b,T,me]),pt=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(ae.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),wt=w.useCallback(()=>{const L=te.trim().length>0||le.length>0||oe.length>0||me.length>0;if(!Z&&oe.length>0&&!r)return pt();if(!Z&&!L&&!r)return null;if(Z)return!f&&et.length>0?null:f?u.jsx(eT,{message:t,viewMode:G,isStreaming:ge},t.id):null;if(!Z&&!_){const ce=t,xe=u.jsx("div",{className:"space-y-2",children:ce.content.map((Be,De)=>u.jsx(Fe,{part:Be,i:De},De))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[xe,u.jsx(rT,{className:z})]}):xe}},[te,le.length,oe.length,me.length,r,Z,G,f,et.length,pt,z]),Dt=w.useMemo(()=>_?"Assistant":rC(t),[_,t]),Pe=w.useMemo(()=>_?[]:Array.isArray(C)?C:[],[C,_]),qt=w.useMemo(()=>{var L;return Pe.length?R&&Pe.some(ce=>ce.id===R)?R:((L=Pe[0])==null?void 0:L.id)??null:null},[R,Pe]),He=w.useMemo(()=>!Pe.length||!E?null:Pe.some(L=>L.id===E)?E:null,[E,Pe])??qt,ut=q==="user"&&Pe.length>0&&typeof A=="function",kt=w.useCallback((L,ce=!1)=>{if(!A)return;const xe=(L==null?void 0:L.id)??null,Be=(L==null?void 0:L.parentId)??D??null;A(xe,Be,ce)},[D,A]),qe=w.useMemo(()=>He?Pe.findIndex(L=>L.id===He):-1,[He,Pe]),J=w.useMemo(()=>qe<0?null:Pe[qe]??null,[qe,Pe]);return Z&&!f&&et.length===0?null:Q&&_?u.jsx("div",{className:se(bt(),p.container),children:u.jsxs("div",{className:se(ht(),p.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(ae.Bot,{className:se("h-4 w-4",z)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(co,{content:_.content,className:"text-current"})]})}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:se(bt(),p.container),children:u.jsxs("div",{className:se(ht(),p.content),children:[(i||a||Z)&&u.jsxs("div",{className:se("flex items-center justify-between mb-2 pb-2 border-b border-current/10",P&&"mb-1 pb-1",z,p.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[at(),a&&Dt&&u.jsx("span",{className:se("font-medium",P?"text-xs":"text-sm"),children:Dt}),Z&&u.jsxs(Kf,{variant:"outline",className:se("text-xs flex items-center gap-1 cursor-pointer select-none",z,"border border-current/40",P&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":G==="expanded",onClick:()=>M(L=>L==="expanded"?"preview":"expanded"),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),M(ce=>ce==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:X.name??"Tool Output"}),X.toolCallId&&u.jsx("span",{className:"opacity-70",children:X.toolCallId.slice(0,8)}),G==="expanded"?u.jsx(ae.ChevronUp,{className:"h-3 w-3"}):u.jsx(ae.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[ut&&J&&qe>=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:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",qe<Pe.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(qe>=Pe.length-1)return;const L=Pe[qe+1];L&&kt(L)},"aria-label":"Older checkpoint (back in time)",disabled:qe>=Pe.length-1,children:u.jsx(ae.ChevronLeft,{className:"h-3 w-3"})}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"whitespace-nowrap",children:[Pe.length-qe," / ",Pe.length]})}),u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",qe>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(!(qe<=0))if(qe===1)kt(null,!0);else{const L=Pe[qe-1];L&&kt(L,!1)}},"aria-label":"Newer checkpoint (forward in time)",disabled:qe<=0,children:u.jsx(ae.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:se("text-xs opacity-60",z,P&&"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:se("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",p.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>rt(),className:se("h-6 w-6 p-0 hover:bg-foreground/10",z,P&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(ae.Copy,{className:se(B?"text-success":z,P?"h-3 w-3":"h-4 w-4")})})}),q==="user"&&v&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ke,className:se("h-6 w-6 p-0 hover:bg-foreground/10",z,P&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(ae.Edit,{className:se(z,P?"h-3 w-3":"h-4 w-4")})}),q==="assistant"&&x&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ge,className:se("h-6 w-6 p-0 hover:bg-foreground/10",z,P&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(ae.RotateCcw,{className:se(z,P?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[wt(),h&&et.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:et.map((L,ce)=>u.jsx(XC,{preview:L,idx:ce},`artifact-${ce}`))})]}),Z&&G==="expanded"&&(X.toolCallId||X.name)&&u.jsxs("div",{className:se("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",P&&"text-xs"),children:[X.name&&u.jsxs("div",{children:["Function: ",X.name]}),X.toolCallId&&u.jsxs("div",{children:["Call ID: ",X.toolCallId]})]}),!(i||a||Z)&&s&&!o&&u.jsxs("div",{className:se("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",p.actions),children:[u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>rt(),className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ae.Copy,{className:se(B?"text-success":"text-current",P?"h-3 w-3":"h-4 w-4")})}),q==="user"&&v&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ke,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ae.Edit,{className:se("text-current",P?"h-3 w-3":"h-4 w-4")})}),q==="assistant"&&x&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ge,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ae.RotateCcw,{className:se("text-current",P?"h-3 w-3":"h-4 w-4")})})]})]})}),O&&u.jsx(IC,{isOpen:W,onClose:K,fileId:O.id,fileName:O.name,mimeType:O.mimeType})]})},(e,t)=>{var l,c,d,f,h,p,v,x;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&Yf(e.message)===Yf(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)&&((h=e.customStyles)==null?void 0:h.actions)===((p=t.customStyles)==null?void 0:p.actions)&&((v=e.customStyles)==null?void 0:v.header)===((x=t.customStyles)==null?void 0:x.header);if(!o||!s)return!1;const i=Ph(e.message),a=Ph(t.message);return i.length===a.length});Ws.displayName="MessageComponent";function oT(e,t){return w.useMemo(()=>{var d,f,h,p,v;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 x=e,y=x.checkpointId??null;s=x.additionalKwargs??{},i=x.responseMetadata??{};const g=y&&t.checkpointMetaById?t.checkpointMetaById.get(y)??null:null;a=typeof s.step=="number"?s.step:typeof i.step=="number"?i.step:(g==null?void 0:g.step)??null;const b=typeof s.source=="string"?s.source:typeof i.source=="string"?i.source:(g==null?void 0:g.source)??null;l=b?String(b):null;const T=a!==null&&l?`${a}:${l}`:null;if(T&&((d=t.checkpointIndexByKey)!=null&&d.has(T))?r=t.checkpointIndexByKey.get(T)??[]:y&&g&&(r=[g]),o=y??((f=r[0])==null?void 0:f.id)??null,c=y?((h=t.attemptMetaById)==null?void 0:h.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 S=k[0].checkpointId;c=((p=t.attemptMetaById)==null?void 0:p.get(S))??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 S=[];for(const[C,E]of t.attemptMetaById.entries())if(E.baseUserMessageId===k){const A=(v=t.checkpointMetaById)==null?void 0:v.get(C);A&&S.push(A)}S.length>0&&(r=S)}}if(c&&c.attemptCount>1&&t.checkpointMetaById&&t.attemptMetaById){const k=[];for(const[S,C]of t.checkpointMetaById.entries()){const E=t.attemptMetaById.get(S);E&&E.attemptCount===c.attemptCount&&E.baseUserMessageId===c.baseUserMessageId&&k.push(C)}k.sort((S,C)=>{const E=S.createdAt?Date.parse(S.createdAt):0;return(C.createdAt?Date.parse(C.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(S=>S.id)}))}}return{checkpointCandidates:r,defaultCheckpointId:o,attemptMeta:c,resolvedStep:a,resolvedSource:l}},[e,t.checkpointMetaById,t.checkpointIndexByKey,t.attemptMetaById,t.userMessageIdToAttempts])}const Oh=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Dh=w.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:h,disableInterruptActions:p,onInterruptActionStart:v,onInterruptActionEnd:x,showToolMessages:y,showArtifactPreviews:g,checkpointMetaById:b,checkpointIndexByKey:T,attemptMetaById:k,userMessageIdToAttempts:S,activeCheckpointId:C,onSelectCheckpoint:E}){const A=Oh(t,n),R="type"in t&&t.type==="default_message",B=!!t.__syntheticStreaming,{checkpointCandidates:Y,defaultCheckpointId:G,attemptMeta:M}=oT(t,{checkpointMetaById:b,checkpointIndexByKey:T,attemptMetaById:k,userMessageIdToAttempts:S}),j=t&&!R?t.additionalKwargs??{}:{},I=t&&!R?t.responseMetadata??{}:{},U=(()=>{if(typeof j.parentCheckpointId=="string")return j.parentCheckpointId;if(typeof I.parentCheckpointId=="string")return I.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":A,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ws,{message:t,messageIndex:n,isStreamingMessage:B||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:h,disableInterruptActions:p,onInterruptActionStart:v,onInterruptActionEnd:x,showToolMessages:y,showArtifactPreviews:g,checkpointCandidates:Y,activeCheckpointId:C??null,onSelectCheckpoint:E,defaultCheckpointId:G,messageParentCheckpointId:U,attemptMeta:M})})});Dh.displayName="MessageRow";const Ka=w.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:h,emptyMessage:p,followNewMessages:v=!0,isNavigatingCheckpoint:x=!1,onScrollAway:y,onAtBottom:g,activeInterrupt:b,disableInterruptActions:T=!1,onInterruptActionStart:k,onInterruptActionEnd:S,showToolMessages:C=!0,showArtifactPreviews:E=!0,checkpointMetaById:A,checkpointIndexByKey:R,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:Y,onSelectCheckpoint:G,createSyntheticThinkingMessage:M=!0},j)=>{const I=w.useRef(null),U=w.useRef(null),$=w.useRef(!1),P=w.useRef(!1),[q,Z]=w.useState(!0),_=w.useMemo(()=>b?e.some(oe=>"type"in oe&&oe.type==="default_message"?!1:Array.isArray(oe==null?void 0:oe.content)&&oe.content.some(me=>me&&me.type==="interrupt"&&(me.id??me.interrupt_id)===b.id)):!1,[b,e]),Q=w.useMemo(()=>{if(!b||_)return null;const oe=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let me;const be=b.value;if(be&&typeof be=="object"&&!Array.isArray(be)){const Me=be.title;typeof Me=="string"&&Me.trim()&&(me=Me.trim())}return{id:`interrupt-${oe}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:oe,value:be,title:me}]}},[b,_]),V=w.useMemo(()=>Q?[...e,Q]:e,[e,Q]),H=w.useMemo(()=>!M||!t?V:!V.some(me=>me.role==="assistant")&&V.length>0?[...V,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString(),__syntheticStreaming:!0}]:V,[V,t,M]),ne=w.useMemo(()=>C?H:H.filter(oe=>(oe==null?void 0:oe.role)!=="tool"),[H,C]),W=w.useCallback(oe=>{Z(oe),y&&y(!oe),g&&g(oe)},[y,g]),O=w.useMemo(()=>{if(a)return async()=>{if(!$.current){$.current=!0;try{await a()}finally{$.current=!1}}}},[a]),K=w.useMemo(()=>!v||x?!1:q?"auto":!1,[q,v,x]),z=w.useMemo(()=>{if(typeof p!="string")return null;const oe=p.trim();return oe?{id:"default-message",role:"assistant",type:"default_message",content:oe,createdAt:new Date().toISOString()}:null},[p]),te=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),X=()=>z?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Ws,{message:z,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:p??"No messages yet. Start a conversation!"}),ge=ne.length,le=ge>0;return w.useEffect(()=>{var oe,me;if(ge===0){P.current=!1;return}if(!P.current)if(P.current=!0,I.current&&ne.length>0){const be=ne.length-1;(me=(oe=I.current).scrollToIndex)==null||me.call(oe,{index:be,align:"end",behavior:"auto"})}else U.current&&(U.current.scrollTop=U.current.scrollHeight)},[ge,ne.length]),w.useImperativeHandle(j,()=>({scrollToLatest:()=>{var oe,me;if(I.current&&ne.length>0){const be=ne.length-1;(me=(oe=I.current).scrollToIndex)==null||me.call(oe,{index:be,align:"end",behavior:"auto"})}else U.current&&(U.current.scrollTop=U.current.scrollHeight)},scrollToTop:()=>{var oe,me;I.current&&ne.length>0?(me=(oe=I.current).scrollToIndex)==null||me.call(oe,{index:0,align:"start",behavior:"auto"}):U.current&&(U.current.scrollTop=0)}}),[ne]),u.jsx("div",{className:te,style:h,children:u.jsx("div",{className:"relative flex-1 min-h-0",children:le?u.jsx(LS,{ref:oe=>{I.current=oe},scrollerRef:oe=>{U.current=oe instanceof HTMLDivElement?oe:null},data:ne,followOutput:K,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{O&&O()},atBottomStateChange:W,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(oe,me)=>Oh(me,oe),itemContent:(oe,me)=>u.jsx(Dh,{message:me,index:oe,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:l,onRegenerate:c,onCancelEdit:d,activeInterrupt:b,disableInterruptActions:T,onInterruptActionStart:k,onInterruptActionEnd:S,showToolMessages:C,showArtifactPreviews:E,checkpointMetaById:A,checkpointIndexByKey:R,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:Y,onSelectCheckpoint:G})}):X()})})});Ka.displayName="MessageList";const Lh={value:""};function Vs({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:h={},onMessageSent:p,onExcelUploadSuccess:v,onError:x}){const{api:y}=wi(),{currentThreadId:g}=Fo(),{threadId:b,messages:T,isHistoryLoading:k,isLoading:S,navigateToCheckpoint:C,returnToLatest:E,checkpoint:A,checkpoints:R,interrupt:D,metadata:B,timelineCheckpoints:Y,messagePreviews:G}=Bo(),{isStreaming:M,error:j,connectionState:I,submit:U,stop:$}=Dc(),P=b??g??null,q=(A==null?void 0:A.id)??null,Z=(A==null?void 0:A.namespace)??null,_=(B==null?void 0:B.assemblingMessageId)??null,Q=D,[V,H]=w.useState(!1);w.useEffect(()=>{Q||H(!1)},[Q]);const ne=w.useCallback(()=>{H(!0)},[]),W=w.useCallback(()=>{H(!1)},[]),O=!!Q||V,[K,z]=w.useState(null),[te,X]=w.useState(""),[ge,le]=w.useState(null),[oe,me]=w.useState(null),[be,Me]=w.useState([]),[Ce,Ue]=w.useState(0),[et,rt]=w.useState(0),[Ke,Ge]=w.useState(!1),[at,bt]=w.useState(null),[ht,Tt]=w.useState(null),[Ie,Fe]=w.useState(!1),[pt,wt]=w.useState(null),Dt=w.useRef(!1),[Pe,qt]=w.useState(()=>Lh.value),Ye=w.useRef(Pe),He=w.useRef(null),ut=w.useCallback(pe=>{Lh.value=pe,qt(pe)},[]),[kt,qe]=w.useState(!1),J=w.useRef(null),{checkpointMetaById:L,checkpointIndexByKey:ce,attemptMetaById:xe,userMessageIdToAttempts:Be}=T0(R),De=Y??[],mt=w.useRef(null),Xe=w.useRef(null),Et=w.useCallback(()=>{mt.current&&(mt.current.value=""),Xe.current&&(Xe.current.value=""),Ue(pe=>pe+1),rt(pe=>pe+1)},[]),yo=w.useCallback(pe=>{ut(pe)},[ut]),vo=w.useRef(!1);w.useEffect(()=>{vo.current&&!M&&(Me([]),Et()),vo.current=M},[M,Et]);const[ri,hl]=w.useState("desktop");w.useEffect(()=>{const pe=()=>{const Te=window.innerWidth;hl(Te<640?"phone":Te<1024?"tablet":"desktop")};return pe(),window.addEventListener("resize",pe),()=>window.removeEventListener("resize",pe)},[]),w.useEffect(()=>{Dt.current=!1},[P]),w.useEffect(()=>{Ye.current=Pe},[Pe]),w.useEffect(()=>{if(!K){He.current=null;return}He.current===null&&(He.current=Ye.current),ut(te??"")},[te,K,ut]),w.useEffect(()=>{(async()=>{if(!y.baseUrl){wt(null);return}try{const je=(await y.getAgent("default")).uiDefaultMessage||"";wt(je||null)}catch(Te){console.warn("Failed to fetch default message:",Te),wt(null)}})()},[y.baseUrl]),w.useEffect(()=>{j&&!Ie&&(x==null||x(j))},[j,Ie,x]);const pl=pe=>{if(pe.length>vs)return`Message too long (${pe.length}/${vs} characters)`;try{return I0(pe),null}catch(Te){return(Te==null?void 0:Te.message)||"Invalid message"}},ml=async pe=>{const Te=pe.trim();if(!(!Te&&be.length===0)){if(Te){const je=pl(Te);if(je){me(je);return}}try{const je=K?(ge==null?void 0:ge.checkpointId)??q??void 0:q??void 0,Je=K?(ge==null?void 0:ge.checkpointNs)??Z??void 0:Z??void 0;await U({text:Te||"",attachments:be},{checkpointId:je,checkpointNs:Je,edit:!!K,originalMessageId:K??void 0}),p==null||p(Te),ut(""),me(null),Me([]),Et(),z(null),X(""),le(null)}catch(je){const Je=(je==null?void 0:je.message)||"Failed to send message";me(Je),x==null||x(Je)}}},oi=w.useCallback((pe,Te,je)=>{c&&(He.current=Pe,z(pe),X(Te),ut(Te),me(null),le({checkpointId:(je==null?void 0:je.checkpointId)??null,checkpointNs:(je==null?void 0:je.checkpointNs)??null}))},[Pe,c,ut]),N=w.useCallback(()=>{z(null),X(""),le(null),me(null),ut(He.current??Pe),He.current=null},[Pe,ut]),re=w.useCallback((pe,Te,je)=>{oi(pe,Te,je)},[oi]),ue=w.useCallback(pe=>{let Te=null;for(let on=pe-1;on>=0;on--)if(T[on].role==="user"){Te=T[on];break}if(!Te)return;const je=Array.isArray(Te.content)?Te.content:[],Hn=je.filter(on=>(on==null?void 0:on.type)==="text").map(on=>on.text).join("")||(()=>{try{return JSON.stringify(je,null,2)}catch{return String(je)}})();Hn&&U({text:Hn},{checkpointId:q??void 0,checkpointNs:Z??void 0,edit:!0,originalMessageId:Te.id})},[T,U,q,Z]),Ne=pe=>{const Te=Array.from(pe.target.files||[]);Me(je=>[...je,...Te]),pe.target.value=""},Qe=pe=>{Me(Te=>{const je=Te.filter((Je,Hn)=>pe!==Hn);return je.length===0&&Et(),je})},ot=async pe=>{const Te=(pe.target.files||[])[0];if(Te){bt(null),Tt(null),Ge(!0);try{await U({attachments:[Te]},{checkpointId:q??void 0,checkpointNs:Z??void 0});const je=`Uploaded ${Te.name} - processing through chat stream`;Tt(je)}catch(je){const Je=je instanceof Error?je.message:"Failed to upload Excel file";console.error("Excel upload failed",je),bt(Je),x==null||x(Je)}finally{Ge(!1),pe.target.value="",Et()}}},ze=async pe=>{if(g){qe(!0);try{if(!pe){await E(),requestAnimationFrame(()=>{var Je;(Je=J.current)==null||Je.scrollToLatest()});return}const Te=R.find(Je=>Je.checkpointId===pe),je=(Te==null?void 0:Te.checkpointNs)??null;await C(pe,je),requestAnimationFrame(()=>{var Je;(Je=J.current)==null||Je.scrollToTop()})}finally{qe(!1)}}},$e=w.useCallback(async(pe,Te,je)=>{await ze(je?null:pe)},[ze]),jt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${h.container||""}`,gt=`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 ${h.messagesArea||""}`,xt=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${h.inputArea||""}`;return u.jsxs("div",{className:jt,children:[!!j&&!Ie&&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:j}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>Fe(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(ae.X,{size:16})})]}),u.jsxs("div",{className:`relative ${gt}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Ka,{ref:J,className:"h-full",style:{height:"100%"},messages:T,isStreaming:M,streamingAssistantId:_,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:ri,enableMessageEditing:c,editingMessageId:K,onEdit:re,onRegenerate:ue,onCancelEdit:N,emptyMessage:pt??void 0,isNavigatingCheckpoint:kt,activeInterrupt:Q,disableInterruptActions:V,onInterruptActionStart:ne,onInterruptActionEnd:W,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:L,checkpointIndexByKey:ce,attemptMetaById:xe,userMessageIdToAttempts:Be,activeCheckpointId:q,onSelectCheckpoint:$e,timelineCheckpoints:De,messagePreviews:G}),(I==="reconnecting"||I==="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(ae.Loader2,{className:"h-3 w-3 animate-spin"}),I==="reconnecting"?"Reconnecting…":"Connecting…"]})}),I==="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"}),S&&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(ae.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||kt)&&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(ae.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:[K&&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(ae.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:N,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(ae.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:mt,type:"file",multiple:!0,onChange:pe=>Ne(pe),className:"hidden"},Ce),be.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:be.map((pe,Te)=>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(ae.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:pe.name}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>Qe(Te),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 ${pe.name}`,children:u.jsx(ae.X,{size:12})})]},Te))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Xe,type:"file",accept:".xls,.xlsx,.xlsm",onChange:ot,className:"hidden"},et),Ke&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ae.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),ht&&!Ke&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:ht}),at&&!Ke&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:at})]})]}),oe&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:oe}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(aa,{children:[u.jsx(la,{asChild:!0,children:u.jsx(tt,{type:"button",size:"icon",variant:"outline",disabled:M||O,title:"More input actions",className:h.moreButton||"",children:u.jsx(ae.Plus,{size:16})})}),u.jsxs(xs,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Jn,{onClick:()=>{var pe;return(pe=mt.current)==null?void 0:pe.click()},className:"cursor-pointer",children:[u.jsx(ae.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Jn,{onClick:()=>{var pe;Ke||(pe=Xe.current)==null||pe.click()},className:`cursor-pointer ${Ke?"opacity-60 pointer-events-none":""}`,children:[u.jsx(ae.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(hy,{initialValue:te,editingMessageId:K,value:Pe,onValueChange:yo,placeholder:K?"Edit your message...":t,isStreaming:M,disabled:O,maxLength:vs,onSend:ml,onCancelEdit:N,onStop:$,allowEmptySend:be.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${K?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${oe?"border-red-400":""} ${h.textarea||""}`})})]})]})]})}function qa(e,[t,n]){return Math.min(n,Math.max(t,e))}function sT(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Ga="ScrollArea",[$h,AE]=Tn(Ga),[iT,nn]=$h(Ga),Fh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=m.useState(null),[c,d]=m.useState(null),[f,h]=m.useState(null),[p,v]=m.useState(null),[x,y]=m.useState(null),[g,b]=m.useState(0),[T,k]=m.useState(0),[S,C]=m.useState(!1),[E,A]=m.useState(!1),R=We(t,B=>l(B)),D=Uo(o);return u.jsx(iT,{scope:n,type:r,dir:D,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:v,scrollbarXEnabled:S,onScrollbarXEnabledChange:C,scrollbarY:x,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:A,onCornerWidthChange:b,onCornerHeightChange:k,children:u.jsx(Se.div,{dir:D,...i,ref:R,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":T+"px",...e.style}})})});Fh.displayName=Ga;var Bh="ScrollAreaViewport",zh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=nn(Bh,n),a=m.useRef(null),l=We(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(Se.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})})]})});zh.displayName=Bh;var Sn="ScrollAreaScrollbar",Ya=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=nn(Sn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return m.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(aT,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(lT,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(Uh,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Xa,{...r,ref:t}):null});Ya.displayName=Sn;var aT=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=nn(Sn,e.__scopeScrollArea),[s,i]=m.useState(!1);return m.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(Zt,{present:n||s,children:u.jsx(Uh,{"data-state":s?"visible":"hidden",...r,ref:t})})}),lT=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=nn(Sn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Ys(()=>l("SCROLL_END"),100),[a,l]=sT("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 m.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),m.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const h=()=>{const p=c[d];f!==p&&(l("SCROLL"),i()),f=p};return c.addEventListener("scroll",h),()=>c.removeEventListener("scroll",h)}},[o.viewport,s,l,i]),u.jsx(Zt,{present:n||a!=="hidden",children:u.jsx(Xa,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:he(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:he(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Uh=m.forwardRef((e,t)=>{const n=nn(Sn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=m.useState(!1),a=e.orientation==="horizontal",l=Ys(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return Er(n.viewport,l),Er(n.content,l),u.jsx(Zt,{present:r||s,children:u.jsx(Xa,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Xa=m.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=nn(Sn,e.__scopeScrollArea),s=m.useRef(null),i=m.useRef(0),[a,l]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=qh(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return pT(h,i.current,a,p)}return n==="horizontal"?u.jsx(cT,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=Gh(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?u.jsx(uT,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=Gh(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),cT=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=nn(Sn,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),c=We(t,l,s.onScrollbarXChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Wh,{"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":Gs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),Xh(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:qs(i.paddingLeft),paddingEnd:qs(i.paddingRight)}})}})}),uT=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=nn(Sn,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),c=We(t,l,s.onScrollbarYChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Wh,{"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":Gs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),Xh(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:qs(i.paddingTop),paddingEnd:qs(i.paddingBottom)}})}})}),[dT,Hh]=$h(Sn),Wh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...h}=e,p=nn(Sn,n),[v,x]=m.useState(null),y=We(t,R=>x(R)),g=m.useRef(null),b=m.useRef(""),T=p.viewport,k=r.content-r.viewport,S=At(d),C=At(l),E=Ys(f,10);function A(R){if(g.current){const D=R.clientX-g.current.left,B=R.clientY-g.current.top;c({x:D,y:B})}}return m.useEffect(()=>{const R=D=>{const B=D.target;(v==null?void 0:v.contains(B))&&S(D,k)};return document.addEventListener("wheel",R,{passive:!1}),()=>document.removeEventListener("wheel",R,{passive:!1})},[T,v,k,S]),m.useEffect(C,[r,C]),Er(v,E),Er(p.content,E),u.jsx(dT,{scope:n,scrollbar:v,hasThumb:o,onThumbChange:At(s),onThumbPointerUp:At(i),onThumbPositionChange:C,onThumbPointerDown:At(a),children:u.jsx(Se.div,{...h,ref:y,style:{position:"absolute",...h.style},onPointerDown:he(e.onPointerDown,R=>{R.button===0&&(R.target.setPointerCapture(R.pointerId),g.current=v.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),A(R))}),onPointerMove:he(e.onPointerMove,A),onPointerUp:he(e.onPointerUp,R=>{const D=R.target;D.hasPointerCapture(R.pointerId)&&D.releasePointerCapture(R.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),g.current=null})})})}),Ks="ScrollAreaThumb",Vh=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Hh(Ks,e.__scopeScrollArea);return u.jsx(Zt,{present:n||o.hasThumb,children:u.jsx(fT,{ref:t,...r})})}),fT=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=nn(Ks,n),i=Hh(Ks,n),{onThumbPositionChange:a}=i,l=We(t,f=>i.onThumbChange(f)),c=m.useRef(void 0),d=Ys(()=>{c.current&&(c.current(),c.current=void 0)},100);return m.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(d(),!c.current){const p=mT(f,a);c.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),u.jsx(Se.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:he(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),v=f.clientX-p.left,x=f.clientY-p.top;i.onThumbPointerDown({x:v,y:x})}),onPointerUp:he(e.onPointerUp,i.onThumbPointerUp)})});Vh.displayName=Ks;var Ja="ScrollAreaCorner",Kh=m.forwardRef((e,t)=>{const n=nn(Ja,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(hT,{...e,ref:t}):null});Kh.displayName=Ja;var hT=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=nn(Ja,n),[s,i]=m.useState(0),[a,l]=m.useState(0),c=!!(s&&a);return Er(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Er(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(Se.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 qs(e){return e?parseInt(e,10):0}function qh(e,t){const n=e/t;return isNaN(n)?0:n}function Gs(e){const t=qh(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function pT(e,t,n,r="ltr"){const o=Gs(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 Yh([l,c],f)(e)}function Gh(e,t,n="ltr"){const r=Gs(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=qa(e,l);return Yh([0,i],[0,a])(c)}function Yh(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 Xh(e,t){return e>0&&e<t}var mT=(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 Ys(e,t){const n=At(e),r=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),m.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Er(e,t){const n=At(t);Nt(()=>{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 Jh=Fh,gT=zh,xT=Kh;const Zh=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Jh,{ref:r,className:se("relative overflow-hidden",e),...n,children:[u.jsx(gT,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Qh,{}),u.jsx(xT,{})]}));Zh.displayName=Jh.displayName;const Qh=m.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Ya,{ref:r,orientation:t,className:se("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(Vh,{className:"relative flex-1 rounded-full bg-border"})}));Qh.displayName=Ya.displayName;var ep=1,yT=.9,vT=.8,bT=.17,Za=.1,Qa=.999,wT=.9999,ST=.99,CT=/[\\\/_+.#"@\[\(\{&]/,TT=/[\\\/_+.#"@\[\(\{&]/g,kT=/[\s-]/,tp=/[\s-]/g;function el(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?ep:ST;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(s),c=n.indexOf(l,o),d=0,f,h,p,v;c>=0;)f=el(e,t,n,r,c+1,s+1,i),f>d&&(c===o?f*=ep:CT.test(e.charAt(c-1))?(f*=vT,p=e.slice(o,c-1).match(TT),p&&o>0&&(f*=Math.pow(Qa,p.length))):kT.test(e.charAt(c-1))?(f*=yT,v=e.slice(o,c-1).match(tp),v&&o>0&&(f*=Math.pow(Qa,v.length))):(f*=bT,o>0&&(f*=Math.pow(Qa,c-o))),e.charAt(c)!==t.charAt(s)&&(f*=wT)),(f<Za&&n.charAt(c-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(c-1)!==r.charAt(s))&&(h=el(e,t,n,r,c+1,s+2,i),h*Za>f&&(f=h*Za)),f>d&&(d=f),c=n.indexOf(l,c+1);return i[a]=d,d}function np(e){return e.toLowerCase().replace(tp," ")}function ET(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,el(e,t,np(e),np(t),0,0,{})}var mo='[cmdk-group=""]',tl='[cmdk-group-items=""]',IT='[cmdk-group-heading=""]',rp='[cmdk-item=""]',op=`${rp}:not([aria-disabled="true"])`,nl="cmdk-item-select",Ir="data-value",NT=(e,t,n)=>ET(e,t,n),sp=m.createContext(void 0),go=()=>m.useContext(sp),ip=m.createContext(void 0),rl=()=>m.useContext(ip),ap=m.createContext(void 0),lp=m.forwardRef((e,t)=>{let n=Nr(()=>{var _,Q;return{search:"",value:(Q=(_=e.value)!=null?_:e.defaultValue)!=null?Q:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Nr(()=>new Set),o=Nr(()=>new Map),s=Nr(()=>new Map),i=Nr(()=>new Set),a=cp(e),{label:l,children:c,value:d,onValueChange:f,filter:h,shouldFilter:p,loop:v,disablePointerSelection:x=!1,vimBindings:y=!0,...g}=e,b=$t(),T=$t(),k=$t(),S=m.useRef(null),C=FT();sr(()=>{if(d!==void 0){let _=d.trim();n.current.value=_,E.emit()}},[d]),sr(()=>{C(6,G)},[]);let E=m.useMemo(()=>({subscribe:_=>(i.current.add(_),()=>i.current.delete(_)),snapshot:()=>n.current,setState:(_,Q,V)=>{var H,ne,W,O;if(!Object.is(n.current[_],Q)){if(n.current[_]=Q,_==="search")Y(),D(),C(1,B);else if(_==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let K=document.getElementById(k);K?K.focus():(H=document.getElementById(b))==null||H.focus()}if(C(7,()=>{var K;n.current.selectedItemId=(K=M())==null?void 0:K.id,E.emit()}),V||C(5,G),((ne=a.current)==null?void 0:ne.value)!==void 0){let K=Q??"";(O=(W=a.current).onValueChange)==null||O.call(W,K);return}}E.emit()}},emit:()=>{i.current.forEach(_=>_())}}),[]),A=m.useMemo(()=>({value:(_,Q,V)=>{var H;Q!==((H=s.current.get(_))==null?void 0:H.value)&&(s.current.set(_,{value:Q,keywords:V}),n.current.filtered.items.set(_,R(Q,V)),C(2,()=>{D(),E.emit()}))},item:(_,Q)=>(r.current.add(_),Q&&(o.current.has(Q)?o.current.get(Q).add(_):o.current.set(Q,new Set([_]))),C(3,()=>{Y(),D(),n.current.value||B(),E.emit()}),()=>{s.current.delete(_),r.current.delete(_),n.current.filtered.items.delete(_);let V=M();C(4,()=>{Y(),(V==null?void 0:V.getAttribute("id"))===_&&B(),E.emit()})}),group:_=>(o.current.has(_)||o.current.set(_,new Set),()=>{s.current.delete(_),o.current.delete(_)}),filter:()=>a.current.shouldFilter,label:l||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:b,inputId:k,labelId:T,listInnerRef:S}),[]);function R(_,Q){var V,H;let ne=(H=(V=a.current)==null?void 0:V.filter)!=null?H:NT;return _?ne(_,n.current.search,Q):0}function D(){if(!n.current.search||a.current.shouldFilter===!1)return;let _=n.current.filtered.items,Q=[];n.current.filtered.groups.forEach(H=>{let ne=o.current.get(H),W=0;ne.forEach(O=>{let K=_.get(O);W=Math.max(K,W)}),Q.push([H,W])});let V=S.current;j().sort((H,ne)=>{var W,O;let K=H.getAttribute("id"),z=ne.getAttribute("id");return((W=_.get(z))!=null?W:0)-((O=_.get(K))!=null?O:0)}).forEach(H=>{let ne=H.closest(tl);ne?ne.appendChild(H.parentElement===ne?H:H.closest(`${tl} > *`)):V.appendChild(H.parentElement===V?H:H.closest(`${tl} > *`))}),Q.sort((H,ne)=>ne[1]-H[1]).forEach(H=>{var ne;let W=(ne=S.current)==null?void 0:ne.querySelector(`${mo}[${Ir}="${encodeURIComponent(H[0])}"]`);W==null||W.parentElement.appendChild(W)})}function B(){let _=j().find(V=>V.getAttribute("aria-disabled")!=="true"),Q=_==null?void 0:_.getAttribute(Ir);E.setState("value",Q||void 0)}function Y(){var _,Q,V,H;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let ne=0;for(let W of r.current){let O=(Q=(_=s.current.get(W))==null?void 0:_.value)!=null?Q:"",K=(H=(V=s.current.get(W))==null?void 0:V.keywords)!=null?H:[],z=R(O,K);n.current.filtered.items.set(W,z),z>0&&ne++}for(let[W,O]of o.current)for(let K of O)if(n.current.filtered.items.get(K)>0){n.current.filtered.groups.add(W);break}n.current.filtered.count=ne}function G(){var _,Q,V;let H=M();H&&(((_=H.parentElement)==null?void 0:_.firstChild)===H&&((V=(Q=H.closest(mo))==null?void 0:Q.querySelector(IT))==null||V.scrollIntoView({block:"nearest"})),H.scrollIntoView({block:"nearest"}))}function M(){var _;return(_=S.current)==null?void 0:_.querySelector(`${rp}[aria-selected="true"]`)}function j(){var _;return Array.from(((_=S.current)==null?void 0:_.querySelectorAll(op))||[])}function I(_){let Q=j()[_];Q&&E.setState("value",Q.getAttribute(Ir))}function U(_){var Q;let V=M(),H=j(),ne=H.findIndex(O=>O===V),W=H[ne+_];(Q=a.current)!=null&&Q.loop&&(W=ne+_<0?H[H.length-1]:ne+_===H.length?H[0]:H[ne+_]),W&&E.setState("value",W.getAttribute(Ir))}function $(_){let Q=M(),V=Q==null?void 0:Q.closest(mo),H;for(;V&&!H;)V=_>0?LT(V,mo):$T(V,mo),H=V==null?void 0:V.querySelector(op);H?E.setState("value",H.getAttribute(Ir)):U(_)}let P=()=>I(j().length-1),q=_=>{_.preventDefault(),_.metaKey?P():_.altKey?$(1):U(1)},Z=_=>{_.preventDefault(),_.metaKey?I(0):_.altKey?$(-1):U(-1)};return m.createElement(Se.div,{ref:t,tabIndex:-1,...g,"cmdk-root":"",onKeyDown:_=>{var Q;(Q=g.onKeyDown)==null||Q.call(g,_);let V=_.nativeEvent.isComposing||_.keyCode===229;if(!(_.defaultPrevented||V))switch(_.key){case"n":case"j":{y&&_.ctrlKey&&q(_);break}case"ArrowDown":{q(_);break}case"p":case"k":{y&&_.ctrlKey&&Z(_);break}case"ArrowUp":{Z(_);break}case"Home":{_.preventDefault(),I(0);break}case"End":{_.preventDefault(),P();break}case"Enter":{_.preventDefault();let H=M();if(H){let ne=new Event(nl);H.dispatchEvent(ne)}}}}},m.createElement("label",{"cmdk-label":"",htmlFor:A.inputId,id:A.labelId,style:zT},l),Xs(e,_=>m.createElement(ip.Provider,{value:E},m.createElement(sp.Provider,{value:A},_))))}),AT=m.forwardRef((e,t)=>{var n,r;let o=$t(),s=m.useRef(null),i=m.useContext(ap),a=go(),l=cp(e),c=(r=(n=l.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;sr(()=>{if(!c)return a.item(o,i==null?void 0:i.id)},[c]);let d=up(o,s,[e.value,e.children,s],e.keywords),f=rl(),h=Fn(C=>C.value&&C.value===d.current),p=Fn(C=>c||a.filter()===!1?!0:C.search?C.filtered.items.get(o)>0:!0);m.useEffect(()=>{let C=s.current;if(!(!C||e.disabled))return C.addEventListener(nl,v),()=>C.removeEventListener(nl,v)},[p,e.onSelect,e.disabled]);function v(){var C,E;x(),(E=(C=l.current).onSelect)==null||E.call(C,d.current)}function x(){f.setState("value",d.current,!0)}if(!p)return null;let{disabled:y,value:g,onSelect:b,forceMount:T,keywords:k,...S}=e;return m.createElement(Se.div,{ref:An(s,t),...S,id:o,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!h,"data-disabled":!!y,"data-selected":!!h,onPointerMove:y||a.getDisablePointerSelection()?void 0:x,onClick:y?void 0:v},e.children)}),jT=m.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:o,...s}=e,i=$t(),a=m.useRef(null),l=m.useRef(null),c=$t(),d=go(),f=Fn(p=>o||d.filter()===!1?!0:p.search?p.filtered.groups.has(i):!0);sr(()=>d.group(i),[]),up(i,a,[e.value,e.heading,l]);let h=m.useMemo(()=>({id:i,forceMount:o}),[o]);return m.createElement(Se.div,{ref:An(a,t),...s,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&m.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:c},n),Xs(e,p=>m.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?c:void 0},m.createElement(ap.Provider,{value:h},p))))}),_T=m.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,o=m.useRef(null),s=Fn(i=>!i.search);return!n&&!s?null:m.createElement(Se.div,{ref:An(o,t),...r,"cmdk-separator":"",role:"separator"})}),MT=m.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,o=e.value!=null,s=rl(),i=Fn(c=>c.search),a=Fn(c=>c.selectedItemId),l=go();return m.useEffect(()=>{e.value!=null&&s.setState("search",e.value)},[e.value]),m.createElement(Se.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:o?e.value:i,onChange:c=>{o||s.setState("search",c.target.value),n==null||n(c.target.value)}})}),RT=m.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...o}=e,s=m.useRef(null),i=m.useRef(null),a=Fn(c=>c.selectedItemId),l=go();return m.useEffect(()=>{if(i.current&&s.current){let c=i.current,d=s.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let p=c.offsetHeight;d.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return h.observe(c),()=>{cancelAnimationFrame(f),h.unobserve(c)}}},[]),m.createElement(Se.div,{ref:An(s,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:l.listId},Xs(e,c=>m.createElement("div",{ref:An(i,l.listInnerRef),"cmdk-list-sizer":""},c)))}),PT=m.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:o,contentClassName:s,container:i,...a}=e;return m.createElement(Da,{open:n,onOpenChange:r},m.createElement(La,{container:i},m.createElement(io,{"cmdk-overlay":"",className:o}),m.createElement(ao,{"aria-label":e.label,"cmdk-dialog":"",className:s},m.createElement(lp,{ref:t,...a}))))}),OT=m.forwardRef((e,t)=>Fn(n=>n.filtered.count===0)?m.createElement(Se.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),DT=m.forwardRef((e,t)=>{let{progress:n,children:r,label:o="Loading...",...s}=e;return m.createElement(Se.div,{ref:t,...s,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},Xs(e,i=>m.createElement("div",{"aria-hidden":!0},i)))}),Kt=Object.assign(lp,{List:RT,Item:AT,Input:MT,Group:jT,Separator:_T,Dialog:PT,Empty:OT,Loading:DT});function LT(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function $T(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function cp(e){let t=m.useRef(e);return sr(()=>{t.current=e}),t}var sr=typeof window>"u"?m.useEffect:m.useLayoutEffect;function Nr(e){let t=m.useRef();return t.current===void 0&&(t.current=e()),t}function Fn(e){let t=rl(),n=()=>e(t.snapshot());return m.useSyncExternalStore(t.subscribe,n,n)}function up(e,t,n,r=[]){let o=m.useRef(),s=go();return sr(()=>{var i;let a=(()=>{var c;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(c=d.current.textContent)==null?void 0:c.trim():o.current}})(),l=r.map(c=>c.trim());s.value(e,a,l),(i=t.current)==null||i.setAttribute(Ir,a),o.current=a}),o}var FT=()=>{let[e,t]=m.useState(),n=Nr(()=>new Map);return sr(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,o)=>{n.current.set(r,o),t({})}};function BT(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Xs({asChild:e,children:t},n){return e&&m.isValidElement(t)?m.cloneElement(BT(t),{ref:t.ref},n(t.props.children)):n(t)}var zT={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const dp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt,{ref:n,className:se("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));dp.displayName=Kt.displayName;const fp=m.forwardRef(({className:e,...t},n)=>u.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[u.jsx(ae.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),u.jsx(Kt.Input,{ref:n,className:se("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));fp.displayName=Kt.Input.displayName;const hp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.List,{ref:n,className:se("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));hp.displayName=Kt.List.displayName;const pp=m.forwardRef((e,t)=>u.jsx(Kt.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));pp.displayName=Kt.Empty.displayName;const mp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.Group,{ref:n,className:se("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));mp.displayName=Kt.Group.displayName;const UT=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.Separator,{ref:n,className:se("-mx-1 h-px bg-border",e),...t}));UT.displayName=Kt.Separator.displayName;const gp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.Item,{ref:n,className:se("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),...t}));gp.displayName=Kt.Item.displayName;const Js=m.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:se("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}));Js.displayName="Input";const HT="group relative p-3 rounded-lg cursor-pointer transition-colors border text-gray-900 dark:text-slate-100",WT="bg-slate-700 border-slate-600 hover:bg-slate-600",VT="bg-slate-600 border-slate-500";function KT({thread:e,isActive:t,editingThreadId:n,editingTitle:r,onSelect:o,onStartEditing:s,onEditingTitleChange:i,onSaveEditing:a,onCancelEditing:l,onShare:c,onDelete:d,showEditTitle:f,showDeleteButton:h,formatDate:p,getDisplayThreadTitle:v,secondaryLine:x,itemClassName:y,activeItemClassName:g}){const b=n===e.threadId,T=t?`${g??VT}`:`${y??WT}`,k=S=>{S.stopPropagation(),o(e.threadId)};return u.jsxs("div",{onClick:k,className:`${HT} ${T}`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:b?u.jsxs("div",{className:"flex items-center gap-2",onClick:S=>S.stopPropagation(),children:[u.jsx(Js,{value:r,onChange:S=>i(S.target.value),onKeyDown:S=>{S.key==="Enter"?a(e.threadId):S.key==="Escape"&&l()},className:"h-6 text-sm",autoFocus:!0}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>a(e.threadId),className:"h-6 w-6 p-0",children:u.jsx(ae.Check,{size:12})}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:l,className:"h-6 w-6 p-0",children:u.jsx(ae.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:v(e)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(ae.Calendar,{size:10}),u.jsx("span",{children:p(e.updatedAt||e.createdAt)})]}),x&&u.jsx("div",{className:"text-[11px] text-muted-foreground mt-1",children:x})]})}),u.jsx("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:u.jsxs(aa,{children:[u.jsx(la,{asChild:!0,children:u.jsx(tt,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:u.jsx(ae.MoreHorizontal,{size:12})})}),u.jsxs(xs,{align:"end",sideOffset:6,className:"w-44",children:[u.jsxs(Jn,{onClick:S=>{S.preventDefault(),c(e.threadId)},children:[u.jsx(ae.Share2,{className:"mr-2 h-4 w-4"}),"Share thread"]}),f&&n!==e.threadId&&u.jsxs(Jn,{onClick:S=>{S.preventDefault(),s(e,S)},children:[u.jsx(ae.Edit3,{className:"mr-2 h-4 w-4"}),"Rename"]}),h&&d&&u.jsxs(Jn,{className:"text-red-400 hover:text-red-300",onClick:S=>{S.preventDefault(),d(e.threadId,S)},children:[u.jsx(ae.Trash2,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})})]}),t&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]})}const xp=25,yp="thread-manager-view",qT=e=>e==="default"||e==="shared",GT=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(yp);if(qT(e))return e}catch{}return null};function YT({defaultView:e}={}){const[t,n]=w.useState(()=>GT()??e??"default");w.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(yp,t)}catch{}},[t]);const r=w.useCallback(o=>{n(o)},[]);return{view:t,setView:r}}const XT=[{key:"default",label:"My chats"},{key:"shared",label:"Shared with you"}];function ol({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,view:f,defaultView:h,onViewChange:p,viewOptions:v,viewState:x,showHeader:y=!0}){const{threads:g,sharedThreads:b,currentThreadId:T,setCurrentThreadId:k,isLoading:S,isLoadingSharedThreads:C,smartOrgUsers:E,isLoadingSmartOrgUsers:A,actions:R,shareInFlight:D,shareStatus:B,clearShareStatus:Y}=Fo(),{createThread:G,deleteThread:M,renameThread:j,shareThread:I}=R,{loadThread:U}=Bo(),$=i??T,[P,q]=w.useState(Array.isArray(g)?g:[]),Z=w.useRef(P.length>0),_=w.useRef(null),Q=w.useRef(0),[V,H]=w.useState(null),[ne,W]=w.useState(""),[O,K]=w.useState(!1),[z,te]=w.useState(!1),[X,ge]=w.useState(null),[le,oe]=w.useState(""),me=v&&v.length>0?v:XT,be=YT({defaultView:h}),Me=x??be,Ce=f??Me.view,Ue=w.useCallback(J=>{f||Me.setView(J),p==null||p(J)},[f,p,Me]),et=me.find(J=>J.key===Ce)??me[0],rt=J=>{ge(J),oe(""),te(!0)},Ke=()=>{te(!1),ge(null),oe(""),Y()},Ge=w.useCallback(async J=>{if(!X||D)return;const L=J.user_id??J.id??J.username??J.email;if(L)try{await I(X,L),setTimeout(()=>Ke(),600)}catch(ce){console.error("Failed to share thread:",ce)}},[Ke,D,X,I]),at=w.useMemo(()=>{const J=le.trim().toLowerCase();return J?E.filter(L=>`${L.username??""} ${L.user_id??""} ${L.email??""} ${L.name??""}`.toLowerCase().includes(J)):E},[E,le]),bt=Ce==="shared",ht=bt?b:P,Tt=bt?C:S,Ie=bt?"No shared conversations yet":"No conversations yet",Fe=J=>{const L=J.sharedAt?` • ${ut(J.sharedAt)}`:"";return`Shared by ${J.sharedByUserId}${L}`},pt=J=>"sharedByUserId"in J;w.useEffect(()=>{const J=Array.isArray(g)?g:[];if(J.length>0){Z.current=!0,q(J);return}S||(Z.current=!1,q(J))},[g,S]),w.useEffect(()=>{if(!_.current)return;const J=_.current.querySelector("[data-radix-scroll-area-viewport]");if(!J)return;let L=null,ce=null;return L=requestAnimationFrame(()=>{ce=requestAnimationFrame(()=>{J.scrollTop=Q.current})}),()=>{L!==null&&cancelAnimationFrame(L),ce!==null&&cancelAnimationFrame(ce)}},[P]);const wt=async J=>{try{k(J),await U(J,void 0,{clearProgress:!0}),a==null||a(J),l==null||l(J)}catch(L){console.error("Failed to select thread:",L)}},Dt=async()=>{try{K(!0);const J=await G();J&&(c==null||c(J),a==null||a(J))}catch(J){console.error("Failed to create thread:",J)}finally{K(!1)}},Pe=async(J,L)=>{if(L.stopPropagation(),!!confirm("Delete this thread?")){if(_.current){const ce=_.current.querySelector("[data-radix-scroll-area-viewport]");ce&&(Q.current=ce.scrollTop)}try{await M(J),d==null||d(J)}catch(ce){console.error("Failed to delete thread:",ce)}}},qt=(J,L)=>{L.stopPropagation(),H(J.threadId),W(J.title||`Thread ${J.threadId.slice(0,8)}`)},Ye=async J=>{if(ne.trim())try{await j(J,ne.trim()),H(null),W("")}catch(L){console.error("Failed to update title:",L)}},He=()=>{H(null),W("")},ut=J=>{if(!J)return"";try{const L=new Date(J),xe=new Date().getTime()-L.getTime(),Be=Math.floor(xe/(1e3*60*60*24));return Be===0?L.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):Be===1?"Yesterday":Be<7?`${Be} days ago`:L.toLocaleDateString()}catch{return""}},kt=J=>J.title||`Thread ${J.threadId.slice(0,8)}`,qe=J=>{const L=kt(J);return L.length<=xp?L:`${L.slice(0,xp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[y&&u.jsxs("div",{className:s.header||"flex flex-col gap-2 px-1 py-0 border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900 shadow-sm",children:[t&&u.jsx("div",{className:"flex justify-end",children:u.jsxs(tt,{onClick:Dt,disabled:O||S,className:s.createButton||"px-3 py-2 gap-1",size:"sm",variant:"ghost",title:O?"Creating...":"New Chat",children:[u.jsx(ae.Edit3,{size:16}),u.jsx("span",{children:"New chat"})]})}),u.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-200 uppercase tracking-wide leading-tight",children:[u.jsx("span",{children:"Current View"}),u.jsxs(aa,{children:[u.jsx(la,{asChild:!0,children:u.jsx(tt,{variant:"outline",size:"sm",className:"text-[11px] text-slate-700 dark:text-slate-200 border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 hover:bg-slate-50 dark:hover:bg-slate-800 px-2 py-0",children:et.label})}),u.jsx(xs,{align:"start",sideOffset:6,className:"w-40",children:me.map(J=>u.jsxs(Jn,{className:"justify-between text-[12px]",onClick:L=>{L.preventDefault(),Ue(J.key)},children:[u.jsx("span",{children:J.label}),Ce===J.key&&u.jsx(ae.Check,{className:"h-3 w-3"})]},J.key))})]})]})]}),u.jsx(Zh,{ref:_,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:Tt?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(ae.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):ht.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(ae.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:Ie})]}):ht.slice().sort((J,L)=>new Date(L.updatedAt||L.createdAt||"").getTime()-new Date(J.updatedAt||J.createdAt||"").getTime()).map(J=>u.jsx(KT,{thread:J,isActive:$===J.threadId,editingThreadId:V,editingTitle:ne,onSelect:wt,onStartEditing:qt,onEditingTitleChange:L=>W(L),onSaveEditing:Ye,onCancelEditing:He,onShare:()=>rt(J.threadId),onDelete:Pe,showEditTitle:r,showDeleteButton:n,formatDate:ut,getDisplayThreadTitle:qe,secondaryLine:bt&&pt(J)?Fe(J):void 0,itemClassName:s.threadItem,activeItemClassName:s.activeThread},J.threadId))})}),u.jsx(mh,{open:z,onOpenChange:J=>!J&&Ke(),children:u.jsxs($a,{className:"max-w-md p-0",children:[u.jsx(Fa,{children:u.jsx(Ba,{children:"Share thread"})}),u.jsxs(dp,{children:[u.jsx(fp,{autoFocus:!0,value:le,onValueChange:J=>oe(J),placeholder:"Search for users (name, email, id)..."}),u.jsxs(hp,{children:[B&&u.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-xs text-muted-foreground",children:[D&&u.jsx(ae.Loader2,{className:"h-3 w-3 animate-spin"}),u.jsx("span",{className:B.startsWith("Failed")?"text-red-500":B.startsWith("Shared")?"text-emerald-500":"text-slate-600 dark:text-slate-400",children:B})]}),u.jsx(pp,{children:A?u.jsxs("span",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ae.Loader2,{className:"h-4 w-4 animate-spin"}),"Loading users…"]}):"No matching users found"}),u.jsx(mp,{heading:"Users",children:at.map(J=>{const L=J.username??J.user_id??J.email??"Unknown user",ce=[J.email,J.user_id].filter(Boolean).join(" • "),xe=J.user_id??J.id??J.username??J.email??L;return u.jsx(gp,{onSelect:()=>Ge(J),children:u.jsxs("div",{className:"flex flex-col items-start text-sm",children:[u.jsx("span",{className:"font-medium",children:L}),ce&&u.jsx("span",{className:"text-xs text-muted-foreground",children:ce})]})},xe)})})]})]})]})})]})}const JT=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r,className:o,onHoverStart:s,onHoverEnd:i})=>{const a=e??[],l=a.length>0,c=w.useMemo(()=>l?[...a].reverse():[],[a,l]),d=t??(a.length?a[a.length-1].id:null);if(!l)return null;const h=["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:h,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(p=>{const v=d===p.id,x=(r==null?void 0:r.get(p.id))??null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(p.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${v?"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 ${v?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${v?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:p.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[p.step!==null?`STEP ${p.step}`:"STEP —",p.next?` - ${p.next}`:""]}),x&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:x,children:x})]})]},p.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 Ar(e){if(!(typeof globalThis>"u"))return globalThis[e]}function ZT(e){if(typeof e!="string")return;const t=e.trim();if(t)return Cn(t)}function vp(){const e=[Ar("__API_BASE_URL__"),Ar("__CHAT_API_BASE_URL__"),Ar("__CHAT_API_URL__")];for(const t of e){const n=ZT(t);if(n)return n}}function bp(){const e=[Ar("__API_AUTH_TOKEN__"),Ar("__CHAT_API_KEY__"),Ar("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function wp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Cn(t);return Cn()}function Sp(){const e={},t=vp(),n=bp();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Cp(){const e=Sp(),t=Nn.getAuthToken(),n=vp();return{apiBaseUrl:wp(e.baseUrl,Nn.baseUrl,n),apiKey:t||e.apiKey||bp()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Tp="chat-settings";function QT(){try{const e=localStorage.getItem(Tp);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function ek(e){try{const t={...e,apiBaseUrl:Cn(e.apiBaseUrl)};localStorage.setItem(Tp,JSON.stringify(t)),t.apiKey&&Nn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function tk(){const e=Cp(),t=QT(),n=Nn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:wp(Nn.baseUrl,r,e.apiBaseUrl)}}function nk(e){Nn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),ek(e)}var rk="Label",kp=m.forwardRef((e,t)=>u.jsx(Se.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())}}));kp.displayName=rk;var Ep=kp;const ok=bo.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),rn=m.forwardRef(({className:e,...t},n)=>u.jsx(Ep,{ref:n,className:se(ok(),e),...t}));rn.displayName=Ep.displayName;function Ip(e){const t=m.useRef({value:e,previous:e});return m.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Np=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"}),sk="VisuallyHidden",ik=m.forwardRef((e,t)=>u.jsx(Se.span,{...e,ref:t,style:{...Np,...e.style}}));ik.displayName=sk;var ak=[" ","Enter","ArrowUp","ArrowDown"],lk=[" ","Enter"],ir="Select",[Zs,Qs,ck]=Ei(ir),[jr,jE]=Tn(ir,[ck,ts]),ei=ts(),[uk,Bn]=jr(ir),[dk,fk]=jr(ir),Ap=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:h,required:p,form:v}=e,x=ei(t),[y,g]=m.useState(null),[b,T]=m.useState(null),[k,S]=m.useState(!1),C=Uo(c),[E,A]=pr({prop:r,defaultProp:o??!1,onChange:s,caller:ir}),[R,D]=pr({prop:i,defaultProp:a,onChange:l,caller:ir}),B=m.useRef(null),Y=y?v||!!y.closest("form"):!0,[G,M]=m.useState(new Set),j=Array.from(G).map(I=>I.props.value).join(";");return u.jsx(ju,{...x,children:u.jsxs(uk,{required:p,scope:t,trigger:y,onTriggerChange:g,valueNode:b,onValueNodeChange:T,valueNodeHasChildren:k,onValueNodeHasChildrenChange:S,contentId:$t(),value:R,onValueChange:D,open:E,onOpenChange:A,dir:C,triggerPointerDownPosRef:B,disabled:h,children:[u.jsx(Zs.Provider,{scope:t,children:u.jsx(dk,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(I=>{M(U=>new Set(U).add(I))},[]),onNativeOptionRemove:m.useCallback(I=>{M(U=>{const $=new Set(U);return $.delete(I),$})},[]),children:n})}),Y?u.jsxs(Qp,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:R,onChange:I=>D(I.target.value),disabled:h,form:v,children:[R===void 0?u.jsx("option",{value:""}):null,Array.from(G)]},j):null]})})};Ap.displayName=ir;var jp="SelectTrigger",_p=m.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=ei(n),i=Bn(jp,n),a=i.disabled||r,l=We(t,i.onTriggerChange),c=Qs(n),d=m.useRef("touch"),[f,h,p]=tm(x=>{const y=c().filter(T=>!T.disabled),g=y.find(T=>T.value===i.value),b=nm(y,x,g);b!==void 0&&i.onValueChange(b.value)}),v=x=>{a||(i.onOpenChange(!0),p()),x&&(i.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return u.jsx(_u,{asChild:!0,...s,children:u.jsx(Se.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":em(i.value)?"":void 0,...o,ref:l,onClick:he(o.onClick,x=>{x.currentTarget.focus(),d.current!=="mouse"&&v(x)}),onPointerDown:he(o.onPointerDown,x=>{d.current=x.pointerType;const y=x.target;y.hasPointerCapture(x.pointerId)&&y.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(v(x),x.preventDefault())}),onKeyDown:he(o.onKeyDown,x=>{const y=f.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&h(x.key),!(y&&x.key===" ")&&ak.includes(x.key)&&(v(),x.preventDefault())})})})});_p.displayName=jp;var Mp="SelectValue",Rp=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Bn(Mp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=We(t,l.onValueNodeChange);return Nt(()=>{c(d)},[c,d]),u.jsx(Se.span,{...a,ref:f,style:{pointerEvents:"none"},children:em(l.value)?u.jsx(u.Fragment,{children:i}):s})});Rp.displayName=Mp;var hk="SelectIcon",Pp=m.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(Se.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Pp.displayName=hk;var pk="SelectPortal",Op=e=>u.jsx(ns,{asChild:!0,...e});Op.displayName=pk;var ar="SelectContent",Dp=m.forwardRef((e,t)=>{const n=Bn(ar,e.__scopeSelect),[r,o]=m.useState();if(Nt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?wo.createPortal(u.jsx(Lp,{scope:e.__scopeSelect,children:u.jsx(Zs.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx($p,{...e,ref:t})});Dp.displayName=ar;var fn=10,[Lp,zn]=jr(ar),mk="SelectContentImpl",gk=Wn.createSlot("SelectContent.RemoveScroll"),$p=m.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:h,collisionPadding:p,sticky:v,hideWhenDetached:x,avoidCollisions:y,...g}=e,b=Bn(ar,n),[T,k]=m.useState(null),[S,C]=m.useState(null),E=We(t,W=>k(W)),[A,R]=m.useState(null),[D,B]=m.useState(null),Y=Qs(n),[G,M]=m.useState(!1),j=m.useRef(!1);m.useEffect(()=>{if(T)return Gi(T)},[T]),Ai();const I=m.useCallback(W=>{const[O,...K]=Y().map(X=>X.ref.current),[z]=K.slice(-1),te=document.activeElement;for(const X of W)if(X===te||(X==null||X.scrollIntoView({block:"nearest"}),X===O&&S&&(S.scrollTop=0),X===z&&S&&(S.scrollTop=S.scrollHeight),X==null||X.focus(),document.activeElement!==te))return},[Y,S]),U=m.useCallback(()=>I([A,T]),[I,A,T]);m.useEffect(()=>{G&&U()},[G,U]);const{onOpenChange:$,triggerPointerDownPosRef:P}=b;m.useEffect(()=>{if(T){let W={x:0,y:0};const O=z=>{var te,X;W={x:Math.abs(Math.round(z.pageX)-(((te=P.current)==null?void 0:te.x)??0)),y:Math.abs(Math.round(z.pageY)-(((X=P.current)==null?void 0:X.y)??0))}},K=z=>{W.x<=10&&W.y<=10?z.preventDefault():T.contains(z.target)||$(!1),document.removeEventListener("pointermove",O),P.current=null};return P.current!==null&&(document.addEventListener("pointermove",O),document.addEventListener("pointerup",K,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",O),document.removeEventListener("pointerup",K,{capture:!0})}}},[T,$,P]),m.useEffect(()=>{const W=()=>$(!1);return window.addEventListener("blur",W),window.addEventListener("resize",W),()=>{window.removeEventListener("blur",W),window.removeEventListener("resize",W)}},[$]);const[q,Z]=tm(W=>{const O=Y().filter(te=>!te.disabled),K=O.find(te=>te.ref.current===document.activeElement),z=nm(O,W,K);z&&setTimeout(()=>z.ref.current.focus())}),_=m.useCallback((W,O,K)=>{const z=!j.current&&!K;(b.value!==void 0&&b.value===O||z)&&(R(W),z&&(j.current=!0))},[b.value]),Q=m.useCallback(()=>T==null?void 0:T.focus(),[T]),V=m.useCallback((W,O,K)=>{const z=!j.current&&!K;(b.value!==void 0&&b.value===O||z)&&B(W)},[b.value]),H=r==="popper"?sl:Fp,ne=H===sl?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:v,hideWhenDetached:x,avoidCollisions:y}:{};return u.jsx(Lp,{scope:n,content:T,viewport:S,onViewportChange:C,itemRefCallback:_,selectedItem:A,onItemLeave:Q,itemTextRefCallback:V,focusSelectedItem:U,selectedItemText:D,position:r,isPositioned:G,searchRef:q,children:u.jsx(ds,{as:gk,allowPinchZoom:!0,children:u.jsx(Wo,{asChild:!0,trapped:b.open,onMountAutoFocus:W=>{W.preventDefault()},onUnmountAutoFocus:he(o,W=>{var O;(O=b.trigger)==null||O.focus({preventScroll:!0}),W.preventDefault()}),children:u.jsx(Ho,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:W=>W.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:u.jsx(H,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:W=>W.preventDefault(),...g,...ne,onPlaced:()=>M(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...g.style},onKeyDown:he(g.onKeyDown,W=>{const O=W.ctrlKey||W.altKey||W.metaKey;if(W.key==="Tab"&&W.preventDefault(),!O&&W.key.length===1&&Z(W.key),["ArrowUp","ArrowDown","Home","End"].includes(W.key)){let z=Y().filter(te=>!te.disabled).map(te=>te.ref.current);if(["ArrowUp","End"].includes(W.key)&&(z=z.slice().reverse()),["ArrowUp","ArrowDown"].includes(W.key)){const te=W.target,X=z.indexOf(te);z=z.slice(X+1)}setTimeout(()=>I(z)),W.preventDefault()}})})})})})})});$p.displayName=mk;var xk="SelectItemAlignedPosition",Fp=m.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Bn(ar,n),i=zn(ar,n),[a,l]=m.useState(null),[c,d]=m.useState(null),f=We(t,E=>d(E)),h=Qs(n),p=m.useRef(!1),v=m.useRef(!0),{viewport:x,selectedItem:y,selectedItemText:g,focusSelectedItem:b}=i,T=m.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&x&&y&&g){const E=s.trigger.getBoundingClientRect(),A=c.getBoundingClientRect(),R=s.valueNode.getBoundingClientRect(),D=g.getBoundingClientRect();if(s.dir!=="rtl"){const te=D.left-A.left,X=R.left-te,ge=E.left-X,le=E.width+ge,oe=Math.max(le,A.width),me=window.innerWidth-fn,be=qa(X,[fn,Math.max(fn,me-oe)]);a.style.minWidth=le+"px",a.style.left=be+"px"}else{const te=A.right-D.right,X=window.innerWidth-R.right-te,ge=window.innerWidth-E.right-X,le=E.width+ge,oe=Math.max(le,A.width),me=window.innerWidth-fn,be=qa(X,[fn,Math.max(fn,me-oe)]);a.style.minWidth=le+"px",a.style.right=be+"px"}const B=h(),Y=window.innerHeight-fn*2,G=x.scrollHeight,M=window.getComputedStyle(c),j=parseInt(M.borderTopWidth,10),I=parseInt(M.paddingTop,10),U=parseInt(M.borderBottomWidth,10),$=parseInt(M.paddingBottom,10),P=j+I+G+$+U,q=Math.min(y.offsetHeight*5,P),Z=window.getComputedStyle(x),_=parseInt(Z.paddingTop,10),Q=parseInt(Z.paddingBottom,10),V=E.top+E.height/2-fn,H=Y-V,ne=y.offsetHeight/2,W=y.offsetTop+ne,O=j+I+W,K=P-O;if(O<=V){const te=B.length>0&&y===B[B.length-1].ref.current;a.style.bottom="0px";const X=c.clientHeight-x.offsetTop-x.offsetHeight,ge=Math.max(H,ne+(te?Q:0)+X+U),le=O+ge;a.style.height=le+"px"}else{const te=B.length>0&&y===B[0].ref.current;a.style.top="0px";const ge=Math.max(V,j+x.offsetTop+(te?_:0)+ne)+K;a.style.height=ge+"px",x.scrollTop=O-V+x.offsetTop}a.style.margin=`${fn}px 0`,a.style.minHeight=q+"px",a.style.maxHeight=Y+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,c,x,y,g,s.dir,r]);Nt(()=>T(),[T]);const[k,S]=m.useState();Nt(()=>{c&&S(window.getComputedStyle(c).zIndex)},[c]);const C=m.useCallback(E=>{E&&v.current===!0&&(T(),b==null||b(),v.current=!1)},[T,b]);return u.jsx(vk,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:C,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(Se.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});Fp.displayName=xk;var yk="SelectPopperPosition",sl=m.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=fn,...s}=e,i=ei(n);return u.jsx(Mu,{...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)"}})});sl.displayName=yk;var[vk,il]=jr(ar,{}),al="SelectViewport",Bp=m.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=zn(al,n),i=il(al,n),a=We(t,s.onViewportChange),l=m.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(Zs.Slot,{scope:n,children:u.jsx(Se.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:he(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const v=window.innerHeight-fn*2,x=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),g=Math.max(x,y);if(g<v){const b=g+p,T=Math.min(v,b),k=b-T;f.style.height=T+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});Bp.displayName=al;var zp="SelectGroup",[bk,wk]=jr(zp),Sk=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=$t();return u.jsx(bk,{scope:n,id:o,children:u.jsx(Se.div,{role:"group","aria-labelledby":o,...r,ref:t})})});Sk.displayName=zp;var Up="SelectLabel",Hp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=wk(Up,n);return u.jsx(Se.div,{id:o.id,...r,ref:t})});Hp.displayName=Up;var ti="SelectItem",[Ck,Wp]=jr(ti),Vp=m.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Bn(ti,n),l=zn(ti,n),c=a.value===r,[d,f]=m.useState(s??""),[h,p]=m.useState(!1),v=We(t,b=>{var T;return(T=l.itemRefCallback)==null?void 0:T.call(l,b,r,o)}),x=$t(),y=m.useRef("touch"),g=()=>{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(Ck,{scope:n,value:r,disabled:o,textId:x,isSelected:c,onItemTextChange:m.useCallback(b=>{f(T=>T||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx(Zs.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(Se.div,{role:"option","aria-labelledby":x,"data-highlighted":h?"":void 0,"aria-selected":c&&h,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:v,onFocus:he(i.onFocus,()=>p(!0)),onBlur:he(i.onBlur,()=>p(!1)),onClick:he(i.onClick,()=>{y.current!=="mouse"&&g()}),onPointerUp:he(i.onPointerUp,()=>{y.current==="mouse"&&g()}),onPointerDown:he(i.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:he(i.onPointerMove,b=>{var T;y.current=b.pointerType,o?(T=l.onItemLeave)==null||T.call(l):y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:he(i.onPointerLeave,b=>{var T;b.currentTarget===document.activeElement&&((T=l.onItemLeave)==null||T.call(l))}),onKeyDown:he(i.onKeyDown,b=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&b.key===" "||(lk.includes(b.key)&&g(),b.key===" "&&b.preventDefault())})})})})});Vp.displayName=ti;var xo="SelectItemText",Kp=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Bn(xo,n),a=zn(xo,n),l=Wp(xo,n),c=fk(xo,n),[d,f]=m.useState(null),h=We(t,g=>f(g),l.onItemTextChange,g=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,g,l.value,l.disabled)}),p=d==null?void 0:d.textContent,v=m.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:x,onNativeOptionRemove:y}=c;return Nt(()=>(x(v),()=>y(v)),[x,y,v]),u.jsxs(u.Fragment,{children:[u.jsx(Se.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?wo.createPortal(s.children,i.valueNode):null]})});Kp.displayName=xo;var qp="SelectItemIndicator",Gp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return Wp(qp,n).isSelected?u.jsx(Se.span,{"aria-hidden":!0,...r,ref:t}):null});Gp.displayName=qp;var ll="SelectScrollUpButton",Yp=m.forwardRef((e,t)=>{const n=zn(ll,e.__scopeSelect),r=il(ll,e.__scopeSelect),[o,s]=m.useState(!1),i=We(t,r.onScrollButtonChange);return Nt(()=>{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(Jp,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});Yp.displayName=ll;var cl="SelectScrollDownButton",Xp=m.forwardRef((e,t)=>{const n=zn(cl,e.__scopeSelect),r=il(cl,e.__scopeSelect),[o,s]=m.useState(!1),i=We(t,r.onScrollButtonChange);return Nt(()=>{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(Jp,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});Xp.displayName=cl;var Jp=m.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=zn("SelectScrollButton",n),i=m.useRef(null),a=Qs(n),l=m.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return m.useEffect(()=>()=>l(),[l]),Nt(()=>{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(Se.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:he(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:he(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:he(o.onPointerLeave,()=>{l()})})}),Tk="SelectSeparator",Zp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Se.div,{"aria-hidden":!0,...r,ref:t})});Zp.displayName=Tk;var ul="SelectArrow",kk=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ei(n),s=Bn(ul,n),i=zn(ul,n);return s.open&&i.position==="popper"?u.jsx(Ru,{...o,...r,ref:t}):null});kk.displayName=ul;var Ek="SelectBubbleInput",Qp=m.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=m.useRef(null),s=We(r,o),i=Ip(t);return m.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(Se.select,{...n,style:{...Np,...n.style},ref:s,defaultValue:t})});Qp.displayName=Ek;function em(e){return e===""||e===void 0}function tm(e){const t=At(e),n=m.useRef(""),r=m.useRef(0),o=m.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=m.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function nm(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=Ik(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 Ik(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Nk=Ap,rm=_p,Ak=Rp,jk=Pp,_k=Op,om=Dp,Mk=Bp,sm=Hp,im=Vp,Rk=Kp,Pk=Gp,am=Yp,lm=Xp,cm=Zp;const um=Nk,dm=Ak,dl=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(rm,{ref:r,className:se("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(jk,{asChild:!0,children:u.jsx(ae.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));dl.displayName=rm.displayName;const fm=m.forwardRef(({className:e,...t},n)=>u.jsx(am,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ae.ChevronUp,{className:"h-4 w-4"})}));fm.displayName=am.displayName;const hm=m.forwardRef(({className:e,...t},n)=>u.jsx(lm,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ae.ChevronDown,{className:"h-4 w-4"})}));hm.displayName=lm.displayName;const fl=m.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(_k,{children:u.jsxs(om,{ref:o,className:se("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(fm,{}),u.jsx(Mk,{className:se("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(hm,{})]})}));fl.displayName=om.displayName;const Ok=m.forwardRef(({className:e,...t},n)=>u.jsx(sm,{ref:n,className:se("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Ok.displayName=sm.displayName;const lr=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(im,{ref:r,className:se("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(Pk,{children:u.jsx(ae.Check,{className:"h-4 w-4"})})}),u.jsx(Rk,{children:t})]}));lr.displayName=im.displayName;const Dk=m.forwardRef(({className:e,...t},n)=>u.jsx(cm,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));Dk.displayName=cm.displayName;var Lk="Separator",pm="horizontal",$k=["horizontal","vertical"],mm=m.forwardRef((e,t)=>{const{decorative:n,orientation:r=pm,...o}=e,s=Fk(r)?r:pm,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(Se.div,{"data-orientation":s,...a,...o,ref:t})});mm.displayName=Lk;function Fk(e){return $k.includes(e)}var gm=mm;const xm=m.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(gm,{ref:o,decorative:n,orientation:t,className:se("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));xm.displayName=gm.displayName;const Bk=Da,zk=vC,Uk=La,ym=m.forwardRef(({className:e,...t},n)=>u.jsx(io,{className:se("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}));ym.displayName=io.displayName;const Hk=bo.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"}}),vm=m.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(Uk,{children:[u.jsx(ym,{}),u.jsxs(ao,{ref:o,className:se(Hk({side:e}),t),...r,children:[n,u.jsxs(ph,{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(ae.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vm.displayName=ao.displayName;const bm=({className:e,...t})=>u.jsx("div",{className:se("flex flex-col space-y-2 text-center sm:text-left",e),...t});bm.displayName="SheetHeader";const wm=m.forwardRef(({className:e,...t},n)=>u.jsx(rr,{ref:n,className:se("text-lg font-semibold text-foreground",e),...t}));wm.displayName=rr.displayName;const Sm=m.forwardRef(({className:e,...t},n)=>u.jsx(Ls,{ref:n,className:se("text-sm text-muted-foreground",e),...t}));Sm.displayName=Ls.displayName;var ni="Switch",[Wk,_E]=Tn(ni),[Vk,Kk]=Wk(ni),Cm=m.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,[h,p]=m.useState(null),v=We(t,T=>p(T)),x=m.useRef(!1),y=h?d||!!h.closest("form"):!0,[g,b]=pr({prop:o,defaultProp:s??!1,onChange:c,caller:ni});return u.jsxs(Vk,{scope:n,checked:g,disabled:a,children:[u.jsx(Se.button,{type:"button",role:"switch","aria-checked":g,"aria-required":i,"data-state":Im(g),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:v,onClick:he(e.onClick,T=>{b(k=>!k),y&&(x.current=T.isPropagationStopped(),x.current||T.stopPropagation())})}),y&&u.jsx(Em,{control:h,bubbles:!x.current,name:r,value:l,checked:g,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});Cm.displayName=ni;var Tm="SwitchThumb",km=m.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=Kk(Tm,n);return u.jsx(Se.span,{"data-state":Im(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});km.displayName=Tm;var qk="SwitchBubbleInput",Em=m.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=m.useRef(null),a=We(i,s),l=Ip(n),c=bu(t);return m.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&p){const v=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(v)}},[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}})});Em.displayName=qk;function Im(e){return e?"checked":"unchecked"}var Nm=Cm,Gk=km;const Un=m.forwardRef(({className:e,...t},n)=>u.jsx(Nm,{className:se("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(Gk,{className:se("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=Nm.displayName;const Yk={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 Xk({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(e),[c,d]=w.useState(!1),{toast:f}=Ha();w.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),w.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(Yk),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},v=()=>{l(e),d(!1),o(!1)},x=async()=>{try{const g=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${g.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(Bk,{open:r,onOpenChange:o,children:[u.jsx(zk,{asChild:!0,children:u.jsxs(tt,{variant:"outline",size:"sm",className:n,children:[u.jsx(ae.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Kf,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(vm,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(bm,{children:[u.jsx(wm,{children:"Chat Settings"}),u.jsx(Sm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(uo,{children:[u.jsx(fo,{className:"pb-3",children:u.jsxs(ho,{className:"text-lg flex items-center gap-2",children:[u.jsx(ae.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(po,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Js,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(g=>({...g,api:{...g.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(tt,{variant:"outline",onClick:x,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Un,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(g=>({...g,api:{...g.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Js,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(g=>({...g,api:{...g.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(tt,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(ae.EyeOff,{className:"h-4 w-4"}):u.jsx(ae.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(uo,{children:[u.jsx(fo,{className:"pb-3",children:u.jsxs(ho,{className:"text-lg flex items-center gap-2",children:[u.jsx(ae.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(po,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(um,{value:a.ui.layout,onValueChange:y=>l(g=>({...g,ui:{...g.ui,layout:y}})),children:[u.jsx(dl,{children:u.jsx(dm,{})}),u.jsxs(fl,{children:[u.jsx(lr,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(lr,{value:"fullscreen",children:"Fullscreen"}),u.jsx(lr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"theme",children:"Theme"}),u.jsxs(um,{value:a.ui.theme,onValueChange:y=>l(g=>({...g,ui:{...g.ui,theme:y}})),children:[u.jsx(dl,{children:u.jsx(dm,{})}),u.jsxs(fl,{children:[u.jsx(lr,{value:"light",children:"Light"}),u.jsx(lr,{value:"dark",children:"Dark"}),u.jsx(lr,{value:"system",children:"System"})]})]})]}),u.jsx(xm,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Un,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(g=>({...g,ui:{...g.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Un,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(g=>({...g,ui:{...g.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Un,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(g=>({...g,ui:{...g.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(uo,{children:[u.jsx(fo,{className:"pb-3",children:u.jsxs(ho,{className:"text-lg flex items-center gap-2",children:[u.jsx(ae.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(po,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(rn,{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(g=>({...g,behavior:{...g.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(rn,{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(g=>({...g,behavior:{...g.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(rn,{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(g=>({...g,behavior:{...g.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(tt,{variant:"outline",onClick:p,children:[u.jsx(ae.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(tt,{variant:"outline",onClick:v,children:"Cancel"}),u.jsxs(tt,{onClick:h,disabled:!c,children:[u.jsx(ae.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function Jk({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=w.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(zo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(Vs,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(zo,{...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(ol,{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(Vs,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(zo,{...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(ol,{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(Vs,{onError:s.onError,enableFileUpload:!0})})]})})}ke.ChatApi=cc,ke.ChatInput=$c,ke.ChatInterface=Vs,ke.ChatProviders=zo,ke.ChatSettings=Xk,ke.MarkdownContent=co,ke.MessageComponent=Ws,ke.MessageList=Ka,ke.ThreadManager=ol,ke.TimelineColumn=JT,ke.applySettings=nk,ke.buildMessagePreviewMap=cx,ke.chatApiClient=Nn,ke.default=Jk,ke.del=bi,ke.get=Wt,ke.getChatToken=ic,ke.getCurrentSettings=tk,ke.getDefaultApiConfig=Sp,ke.getDefaultChatSettings=Cp,ke.onChatTokenChanged=ac,ke.post=Po,ke.put=lc,ke.setChatToken=Ro,ke.useApi=wi,ke.useChatStream=_c,ke.useMessagesReducer=Ac,ke.useStream=Dc,ke.useThreadState=Bo,ke.useThreads=Fo,Object.defineProperties(ke,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
137
+ dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[H[ce]?u.jsx(ae.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[Be,H[ce]?" (processing)":""]})]},ce)}if(L.type==="interrupt"){const xe=L,Be=Ps((xe==null?void 0:xe.id)??(xe==null?void 0:xe.interrupt_id)),De=!!(Me&&Be&&Be===Me),mt=De?Ce??(xe==null?void 0:xe.value):xe==null?void 0:xe.value,Xe=Be?{...xe,id:Be,interrupt_id:Be}:xe;return u.jsx(JC,{interruptPart:Xe,onApprove:Tt,onReject:Ie,disabled:T,isActive:De,payload:mt},ce)}return null},[ne,H,Tt,Ie,q,c,d,j,P,Me,Ce,b,T,me]),pt=w.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(ae.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),wt=w.useCallback(()=>{const L=te.trim().length>0||le.length>0||oe.length>0||me.length>0;if(!Z&&oe.length>0&&!r)return pt();if(!Z&&!L&&!r)return null;if(Z)return!f&&et.length>0?null:f?u.jsx(eT,{message:t,viewMode:G,isStreaming:ge},t.id):null;if(!Z&&!_){const ce=t,xe=u.jsx("div",{className:"space-y-2",children:ce.content.map((Be,De)=>u.jsx(Fe,{part:Be,i:De},De))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[xe,u.jsx(rT,{className:z})]}):xe}},[te,le.length,oe.length,me.length,r,Z,G,f,et.length,pt,z]),Dt=w.useMemo(()=>_?"Assistant":rC(t),[_,t]),Pe=w.useMemo(()=>_?[]:Array.isArray(C)?C:[],[C,_]),qt=w.useMemo(()=>{var L;return Pe.length?R&&Pe.some(ce=>ce.id===R)?R:((L=Pe[0])==null?void 0:L.id)??null:null},[R,Pe]),He=w.useMemo(()=>!Pe.length||!E?null:Pe.some(L=>L.id===E)?E:null,[E,Pe])??qt,ut=q==="user"&&Pe.length>0&&typeof A=="function",kt=w.useCallback((L,ce=!1)=>{if(!A)return;const xe=(L==null?void 0:L.id)??null,Be=(L==null?void 0:L.parentId)??D??null;A(xe,Be,ce)},[D,A]),qe=w.useMemo(()=>He?Pe.findIndex(L=>L.id===He):-1,[He,Pe]),J=w.useMemo(()=>qe<0?null:Pe[qe]??null,[qe,Pe]);return Z&&!f&&et.length===0?null:Q&&_?u.jsx("div",{className:se(bt(),p.container),children:u.jsxs("div",{className:se(ht(),p.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(ae.Bot,{className:se("h-4 w-4",z)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(co,{content:_.content,className:"text-current"})]})}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:se(bt(),p.container),children:u.jsxs("div",{className:se(ht(),p.content),children:[(i||a||Z)&&u.jsxs("div",{className:se("flex items-center justify-between mb-2 pb-2 border-b border-current/10",P&&"mb-1 pb-1",z,p.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[at(),a&&Dt&&u.jsx("span",{className:se("font-medium",P?"text-xs":"text-sm"),children:Dt}),Z&&u.jsxs(Kf,{variant:"outline",className:se("text-xs flex items-center gap-1 cursor-pointer select-none",z,"border border-current/40",P&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":G==="expanded",onClick:()=>M(L=>L==="expanded"?"preview":"expanded"),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),M(ce=>ce==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:X.name??"Tool Output"}),X.toolCallId&&u.jsx("span",{className:"opacity-70",children:X.toolCallId.slice(0,8)}),G==="expanded"?u.jsx(ae.ChevronUp,{className:"h-3 w-3"}):u.jsx(ae.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[ut&&J&&qe>=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:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",qe<Pe.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(qe>=Pe.length-1)return;const L=Pe[qe+1];L&&kt(L)},"aria-label":"Older checkpoint (back in time)",disabled:qe>=Pe.length-1,children:u.jsx(ae.ChevronLeft,{className:"h-3 w-3"})}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"whitespace-nowrap",children:[Pe.length-qe," / ",Pe.length]})}),u.jsx("button",{type:"button",className:se("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",qe>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(!(qe<=0))if(qe===1)kt(null,!0);else{const L=Pe[qe-1];L&&kt(L,!1)}},"aria-label":"Newer checkpoint (forward in time)",disabled:qe<=0,children:u.jsx(ae.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:se("text-xs opacity-60",z,P&&"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:se("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",p.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>rt(),className:se("h-6 w-6 p-0 hover:bg-foreground/10",z,P&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(ae.Copy,{className:se(B?"text-success":z,P?"h-3 w-3":"h-4 w-4")})})}),q==="user"&&v&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ke,className:se("h-6 w-6 p-0 hover:bg-foreground/10",z,P&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(ae.Edit,{className:se(z,P?"h-3 w-3":"h-4 w-4")})}),q==="assistant"&&x&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ge,className:se("h-6 w-6 p-0 hover:bg-foreground/10",z,P&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(ae.RotateCcw,{className:se(z,P?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[wt(),h&&et.length>0&&u.jsx("div",{className:"mt-3 space-y-4",children:et.map((L,ce)=>u.jsx(XC,{preview:L,idx:ce},`artifact-${ce}`))})]}),Z&&G==="expanded"&&(X.toolCallId||X.name)&&u.jsxs("div",{className:se("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",P&&"text-xs"),children:[X.name&&u.jsxs("div",{children:["Function: ",X.name]}),X.toolCallId&&u.jsxs("div",{children:["Call ID: ",X.toolCallId]})]}),!(i||a||Z)&&s&&!o&&u.jsxs("div",{className:se("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",p.actions),children:[u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>rt(),className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ae.Copy,{className:se(B?"text-success":"text-current",P?"h-3 w-3":"h-4 w-4")})}),q==="user"&&v&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ke,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ae.Edit,{className:se("text-current",P?"h-3 w-3":"h-4 w-4")})}),q==="assistant"&&x&&u.jsx(tt,{variant:"ghost",size:"sm",onClick:Ge,className:se("h-6 w-6 p-0 hover:bg-background/50 text-current",P&&"h-5 w-5"),children:u.jsx(ae.RotateCcw,{className:se("text-current",P?"h-3 w-3":"h-4 w-4")})})]})]})}),O&&u.jsx(IC,{isOpen:W,onClose:K,fileId:O.id,fileName:O.name,mimeType:O.mimeType})]})},(e,t)=>{var l,c,d,f,h,p,v,x;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&Yf(e.message)===Yf(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)&&((h=e.customStyles)==null?void 0:h.actions)===((p=t.customStyles)==null?void 0:p.actions)&&((v=e.customStyles)==null?void 0:v.header)===((x=t.customStyles)==null?void 0:x.header);if(!o||!s)return!1;const i=Ph(e.message),a=Ph(t.message);return i.length===a.length});Ws.displayName="MessageComponent";function oT(e,t){return w.useMemo(()=>{var d,f,h,p,v;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 x=e,y=x.checkpointId??null;s=x.additionalKwargs??{},i=x.responseMetadata??{};const g=y&&t.checkpointMetaById?t.checkpointMetaById.get(y)??null:null;a=typeof s.step=="number"?s.step:typeof i.step=="number"?i.step:(g==null?void 0:g.step)??null;const b=typeof s.source=="string"?s.source:typeof i.source=="string"?i.source:(g==null?void 0:g.source)??null;l=b?String(b):null;const T=a!==null&&l?`${a}:${l}`:null;if(T&&((d=t.checkpointIndexByKey)!=null&&d.has(T))?r=t.checkpointIndexByKey.get(T)??[]:y&&g&&(r=[g]),o=y??((f=r[0])==null?void 0:f.id)??null,c=y?((h=t.attemptMetaById)==null?void 0:h.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 S=k[0].checkpointId;c=((p=t.attemptMetaById)==null?void 0:p.get(S))??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 S=[];for(const[C,E]of t.attemptMetaById.entries())if(E.baseUserMessageId===k){const A=(v=t.checkpointMetaById)==null?void 0:v.get(C);A&&S.push(A)}S.length>0&&(r=S)}}if(c&&c.attemptCount>1&&t.checkpointMetaById&&t.attemptMetaById){const k=[];for(const[S,C]of t.checkpointMetaById.entries()){const E=t.attemptMetaById.get(S);E&&E.attemptCount===c.attemptCount&&E.baseUserMessageId===c.baseUserMessageId&&k.push(C)}k.sort((S,C)=>{const E=S.createdAt?Date.parse(S.createdAt):0;return(C.createdAt?Date.parse(C.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(S=>S.id)}))}}return{checkpointCandidates:r,defaultCheckpointId:o,attemptMeta:c,resolvedStep:a,resolvedSource:l}},[e,t.checkpointMetaById,t.checkpointIndexByKey,t.attemptMetaById,t.userMessageIdToAttempts])}const Oh=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Dh=w.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:h,disableInterruptActions:p,onInterruptActionStart:v,onInterruptActionEnd:x,showToolMessages:y,showArtifactPreviews:g,checkpointMetaById:b,checkpointIndexByKey:T,attemptMetaById:k,userMessageIdToAttempts:S,activeCheckpointId:C,onSelectCheckpoint:E}){const A=Oh(t,n),R="type"in t&&t.type==="default_message",B=!!t.__syntheticStreaming,{checkpointCandidates:Y,defaultCheckpointId:G,attemptMeta:M}=oT(t,{checkpointMetaById:b,checkpointIndexByKey:T,attemptMetaById:k,userMessageIdToAttempts:S}),j=t&&!R?t.additionalKwargs??{}:{},I=t&&!R?t.responseMetadata??{}:{},U=(()=>{if(typeof j.parentCheckpointId=="string")return j.parentCheckpointId;if(typeof I.parentCheckpointId=="string")return I.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":A,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(Ws,{message:t,messageIndex:n,isStreamingMessage:B||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:h,disableInterruptActions:p,onInterruptActionStart:v,onInterruptActionEnd:x,showToolMessages:y,showArtifactPreviews:g,checkpointCandidates:Y,activeCheckpointId:C??null,onSelectCheckpoint:E,defaultCheckpointId:G,messageParentCheckpointId:U,attemptMeta:M})})});Dh.displayName="MessageRow";const Ka=w.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:h,emptyMessage:p,followNewMessages:v=!0,isNavigatingCheckpoint:x=!1,onScrollAway:y,onAtBottom:g,activeInterrupt:b,disableInterruptActions:T=!1,onInterruptActionStart:k,onInterruptActionEnd:S,showToolMessages:C=!0,showArtifactPreviews:E=!0,checkpointMetaById:A,checkpointIndexByKey:R,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:Y,onSelectCheckpoint:G,createSyntheticThinkingMessage:M=!0},j)=>{const I=w.useRef(null),U=w.useRef(null),$=w.useRef(!1),P=w.useRef(!1),[q,Z]=w.useState(!0),_=w.useMemo(()=>b?e.some(oe=>"type"in oe&&oe.type==="default_message"?!1:Array.isArray(oe==null?void 0:oe.content)&&oe.content.some(me=>me&&me.type==="interrupt"&&(me.id??me.interrupt_id)===b.id)):!1,[b,e]),Q=w.useMemo(()=>{if(!b||_)return null;const oe=b.id&&String(b.id).trim()?String(b.id).trim():"pending-interrupt";let me;const be=b.value;if(be&&typeof be=="object"&&!Array.isArray(be)){const Me=be.title;typeof Me=="string"&&Me.trim()&&(me=Me.trim())}return{id:`interrupt-${oe}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:oe,value:be,title:me}]}},[b,_]),V=w.useMemo(()=>Q?[...e,Q]:e,[e,Q]),H=w.useMemo(()=>!M||!t?V:!V.some(me=>me.role==="assistant")&&V.length>0?[...V,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString(),__syntheticStreaming:!0}]:V,[V,t,M]),ne=w.useMemo(()=>C?H:H.filter(oe=>(oe==null?void 0:oe.role)!=="tool"),[H,C]),W=w.useCallback(oe=>{Z(oe),y&&y(!oe),g&&g(oe)},[y,g]),O=w.useMemo(()=>{if(a)return async()=>{if(!$.current){$.current=!0;try{await a()}finally{$.current=!1}}}},[a]),K=w.useMemo(()=>!v||x?!1:q?"auto":!1,[q,v,x]),z=w.useMemo(()=>{if(typeof p!="string")return null;const oe=p.trim();return oe?{id:"default-message",role:"assistant",type:"default_message",content:oe,createdAt:new Date().toISOString()}:null},[p]),te=["flex h-full flex-col md:flex-row",f].filter(Boolean).join(" "),X=()=>z?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(Ws,{message:z,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:p??"No messages yet. Start a conversation!"}),ge=ne.length,le=ge>0;return w.useEffect(()=>{var oe,me;if(ge===0){P.current=!1;return}if(!P.current)if(P.current=!0,I.current&&ne.length>0){const be=ne.length-1;(me=(oe=I.current).scrollToIndex)==null||me.call(oe,{index:be,align:"end",behavior:"auto"})}else U.current&&(U.current.scrollTop=U.current.scrollHeight)},[ge,ne.length]),w.useImperativeHandle(j,()=>({scrollToLatest:()=>{var oe,me;if(I.current&&ne.length>0){const be=ne.length-1;(me=(oe=I.current).scrollToIndex)==null||me.call(oe,{index:be,align:"end",behavior:"auto"})}else U.current&&(U.current.scrollTop=U.current.scrollHeight)},scrollToTop:()=>{var oe,me;I.current&&ne.length>0?(me=(oe=I.current).scrollToIndex)==null||me.call(oe,{index:0,align:"start",behavior:"auto"}):U.current&&(U.current.scrollTop=0)}}),[ne]),u.jsx("div",{className:te,style:h,children:u.jsx("div",{className:"relative flex-1 min-h-0",children:le?u.jsx(LS,{ref:oe=>{I.current=oe},scrollerRef:oe=>{U.current=oe instanceof HTMLDivElement?oe:null},data:ne,followOutput:K,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{O&&O()},atBottomStateChange:W,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(oe,me)=>Oh(me,oe),itemContent:(oe,me)=>u.jsx(Dh,{message:me,index:oe,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:l,onRegenerate:c,onCancelEdit:d,activeInterrupt:b,disableInterruptActions:T,onInterruptActionStart:k,onInterruptActionEnd:S,showToolMessages:C,showArtifactPreviews:E,checkpointMetaById:A,checkpointIndexByKey:R,attemptMetaById:D,userMessageIdToAttempts:B,activeCheckpointId:Y,onSelectCheckpoint:G})}):X()})})});Ka.displayName="MessageList";const Lh={value:""};function Vs({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:h={},onMessageSent:p,onExcelUploadSuccess:v,onError:x}){const{api:y}=wi(),{currentThreadId:g}=Fo(),{threadId:b,messages:T,isHistoryLoading:k,isLoading:S,navigateToCheckpoint:C,returnToLatest:E,checkpoint:A,checkpoints:R,interrupt:D,metadata:B,timelineCheckpoints:Y,messagePreviews:G}=Bo(),{isStreaming:M,error:j,connectionState:I,submit:U,stop:$}=Dc(),P=b??g??null,q=(A==null?void 0:A.id)??null,Z=(A==null?void 0:A.namespace)??null,_=(B==null?void 0:B.assemblingMessageId)??null,Q=D,[V,H]=w.useState(!1);w.useEffect(()=>{Q||H(!1)},[Q]);const ne=w.useCallback(()=>{H(!0)},[]),W=w.useCallback(()=>{H(!1)},[]),O=!!Q||V,[K,z]=w.useState(null),[te,X]=w.useState(""),[ge,le]=w.useState(null),[oe,me]=w.useState(null),[be,Me]=w.useState([]),[Ce,Ue]=w.useState(0),[et,rt]=w.useState(0),[Ke,Ge]=w.useState(!1),[at,bt]=w.useState(null),[ht,Tt]=w.useState(null),[Ie,Fe]=w.useState(!1),[pt,wt]=w.useState(null),Dt=w.useRef(!1),[Pe,qt]=w.useState(()=>Lh.value),Ye=w.useRef(Pe),He=w.useRef(null),ut=w.useCallback(pe=>{Lh.value=pe,qt(pe)},[]),[kt,qe]=w.useState(!1),J=w.useRef(null),{checkpointMetaById:L,checkpointIndexByKey:ce,attemptMetaById:xe,userMessageIdToAttempts:Be}=T0(R),De=Y??[],mt=w.useRef(null),Xe=w.useRef(null),Et=w.useCallback(()=>{mt.current&&(mt.current.value=""),Xe.current&&(Xe.current.value=""),Ue(pe=>pe+1),rt(pe=>pe+1)},[]),yo=w.useCallback(pe=>{ut(pe)},[ut]),vo=w.useRef(!1);w.useEffect(()=>{vo.current&&!M&&(Me([]),Et()),vo.current=M},[M,Et]);const[ri,hl]=w.useState("desktop");w.useEffect(()=>{const pe=()=>{const Te=window.innerWidth;hl(Te<640?"phone":Te<1024?"tablet":"desktop")};return pe(),window.addEventListener("resize",pe),()=>window.removeEventListener("resize",pe)},[]),w.useEffect(()=>{Dt.current=!1},[P]),w.useEffect(()=>{Ye.current=Pe},[Pe]),w.useEffect(()=>{if(!K){He.current=null;return}He.current===null&&(He.current=Ye.current),ut(te??"")},[te,K,ut]),w.useEffect(()=>{(async()=>{if(!y.baseUrl){wt(null);return}try{const je=(await y.getAgent("default")).uiDefaultMessage||"";wt(je||null)}catch(Te){console.warn("Failed to fetch default message:",Te),wt(null)}})()},[y.baseUrl]),w.useEffect(()=>{j&&!Ie&&(x==null||x(j))},[j,Ie,x]);const pl=pe=>{if(pe.length>vs)return`Message too long (${pe.length}/${vs} characters)`;try{return I0(pe),null}catch(Te){return(Te==null?void 0:Te.message)||"Invalid message"}},ml=async pe=>{const Te=pe.trim();if(!(!Te&&be.length===0)){if(Te){const je=pl(Te);if(je){me(je);return}}try{const je=K?(ge==null?void 0:ge.checkpointId)??q??void 0:q??void 0,Je=K?(ge==null?void 0:ge.checkpointNs)??Z??void 0:Z??void 0;await U({text:Te||"",attachments:be},{checkpointId:je,checkpointNs:Je,edit:!!K,originalMessageId:K??void 0}),p==null||p(Te),ut(""),me(null),Me([]),Et(),z(null),X(""),le(null)}catch(je){const Je=(je==null?void 0:je.message)||"Failed to send message";me(Je),x==null||x(Je)}}},oi=w.useCallback((pe,Te,je)=>{c&&(He.current=Pe,z(pe),X(Te),ut(Te),me(null),le({checkpointId:(je==null?void 0:je.checkpointId)??null,checkpointNs:(je==null?void 0:je.checkpointNs)??null}))},[Pe,c,ut]),N=w.useCallback(()=>{z(null),X(""),le(null),me(null),ut(He.current??Pe),He.current=null},[Pe,ut]),re=w.useCallback((pe,Te,je)=>{oi(pe,Te,je)},[oi]),ue=w.useCallback(pe=>{let Te=null;for(let on=pe-1;on>=0;on--)if(T[on].role==="user"){Te=T[on];break}if(!Te)return;const je=Array.isArray(Te.content)?Te.content:[],Hn=je.filter(on=>(on==null?void 0:on.type)==="text").map(on=>on.text).join("")||(()=>{try{return JSON.stringify(je,null,2)}catch{return String(je)}})();Hn&&U({text:Hn},{checkpointId:q??void 0,checkpointNs:Z??void 0,edit:!0,originalMessageId:Te.id})},[T,U,q,Z]),Ne=pe=>{const Te=Array.from(pe.target.files||[]);Me(je=>[...je,...Te]),pe.target.value=""},Qe=pe=>{Me(Te=>{const je=Te.filter((Je,Hn)=>pe!==Hn);return je.length===0&&Et(),je})},ot=async pe=>{const Te=(pe.target.files||[])[0];if(Te){bt(null),Tt(null),Ge(!0);try{await U({attachments:[Te]},{checkpointId:q??void 0,checkpointNs:Z??void 0});const je=`Uploaded ${Te.name} - processing through chat stream`;Tt(je)}catch(je){const Je=je instanceof Error?je.message:"Failed to upload Excel file";console.error("Excel upload failed",je),bt(Je),x==null||x(Je)}finally{Ge(!1),pe.target.value="",Et()}}},ze=async pe=>{if(g){qe(!0);try{if(!pe){await E(),requestAnimationFrame(()=>{var Je;(Je=J.current)==null||Je.scrollToLatest()});return}const Te=R.find(Je=>Je.checkpointId===pe),je=(Te==null?void 0:Te.checkpointNs)??null;await C(pe,je),requestAnimationFrame(()=>{var Je;(Je=J.current)==null||Je.scrollToTop()})}finally{qe(!1)}}},$e=w.useCallback(async(pe,Te,je)=>{await ze(je?null:pe)},[ze]),jt=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${h.container||""}`,gt=`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 ${h.messagesArea||""}`,xt=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${h.inputArea||""}`;return u.jsxs("div",{className:jt,children:[!!j&&!Ie&&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:j}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>Fe(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(ae.X,{size:16})})]}),u.jsxs("div",{className:`relative ${gt}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(Ka,{ref:J,className:"h-full",style:{height:"100%"},messages:T,isStreaming:M,streamingAssistantId:_,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:ri,enableMessageEditing:c,editingMessageId:K,onEdit:re,onRegenerate:ue,onCancelEdit:N,emptyMessage:pt??void 0,isNavigatingCheckpoint:kt,activeInterrupt:Q,disableInterruptActions:V,onInterruptActionStart:ne,onInterruptActionEnd:W,showToolMessages:d,showArtifactPreviews:f,checkpointMetaById:L,checkpointIndexByKey:ce,attemptMetaById:xe,userMessageIdToAttempts:Be,activeCheckpointId:q,onSelectCheckpoint:$e,timelineCheckpoints:De,messagePreviews:G,createSyntheticThinkingMessage:!0}),(I==="reconnecting"||I==="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(ae.Loader2,{className:"h-3 w-3 animate-spin"}),I==="reconnecting"?"Reconnecting…":"Connecting…"]})}),I==="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"}),S&&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(ae.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||kt)&&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(ae.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:[K&&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(ae.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:N,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(ae.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:mt,type:"file",multiple:!0,onChange:pe=>Ne(pe),className:"hidden"},Ce),be.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:be.map((pe,Te)=>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(ae.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:pe.name}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>Qe(Te),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 ${pe.name}`,children:u.jsx(ae.X,{size:12})})]},Te))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:Xe,type:"file",accept:".xls,.xlsx,.xlsm",onChange:ot,className:"hidden"},et),Ke&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ae.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),ht&&!Ke&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:ht}),at&&!Ke&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:at})]})]}),oe&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:oe}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(aa,{children:[u.jsx(la,{asChild:!0,children:u.jsx(tt,{type:"button",size:"icon",variant:"outline",disabled:M||O,title:"More input actions",className:h.moreButton||"",children:u.jsx(ae.Plus,{size:16})})}),u.jsxs(xs,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Jn,{onClick:()=>{var pe;return(pe=mt.current)==null?void 0:pe.click()},className:"cursor-pointer",children:[u.jsx(ae.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Jn,{onClick:()=>{var pe;Ke||(pe=Xe.current)==null||pe.click()},className:`cursor-pointer ${Ke?"opacity-60 pointer-events-none":""}`,children:[u.jsx(ae.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(hy,{initialValue:te,editingMessageId:K,value:Pe,onValueChange:yo,placeholder:K?"Edit your message...":t,isStreaming:M,disabled:O,maxLength:vs,onSend:ml,onCancelEdit:N,onStop:$,allowEmptySend:be.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${K?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${oe?"border-red-400":""} ${h.textarea||""}`})})]})]})]})}function qa(e,[t,n]){return Math.min(n,Math.max(t,e))}function sT(e,t){return m.useReducer((n,r)=>t[n][r]??n,e)}var Ga="ScrollArea",[$h,AE]=Tn(Ga),[iT,nn]=$h(Ga),Fh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...i}=e,[a,l]=m.useState(null),[c,d]=m.useState(null),[f,h]=m.useState(null),[p,v]=m.useState(null),[x,y]=m.useState(null),[g,b]=m.useState(0),[T,k]=m.useState(0),[S,C]=m.useState(!1),[E,A]=m.useState(!1),R=We(t,B=>l(B)),D=Uo(o);return u.jsx(iT,{scope:n,type:r,dir:D,scrollHideDelay:s,scrollArea:a,viewport:c,onViewportChange:d,content:f,onContentChange:h,scrollbarX:p,onScrollbarXChange:v,scrollbarXEnabled:S,onScrollbarXEnabledChange:C,scrollbarY:x,onScrollbarYChange:y,scrollbarYEnabled:E,onScrollbarYEnabledChange:A,onCornerWidthChange:b,onCornerHeightChange:k,children:u.jsx(Se.div,{dir:D,...i,ref:R,style:{position:"relative","--radix-scroll-area-corner-width":g+"px","--radix-scroll-area-corner-height":T+"px",...e.style}})})});Fh.displayName=Ga;var Bh="ScrollAreaViewport",zh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...s}=e,i=nn(Bh,n),a=m.useRef(null),l=We(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(Se.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})})]})});zh.displayName=Bh;var Sn="ScrollAreaScrollbar",Ya=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=nn(Sn,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:i}=o,a=e.orientation==="horizontal";return m.useEffect(()=>(a?s(!0):i(!0),()=>{a?s(!1):i(!1)}),[a,s,i]),o.type==="hover"?u.jsx(aT,{...r,ref:t,forceMount:n}):o.type==="scroll"?u.jsx(lT,{...r,ref:t,forceMount:n}):o.type==="auto"?u.jsx(Uh,{...r,ref:t,forceMount:n}):o.type==="always"?u.jsx(Xa,{...r,ref:t}):null});Ya.displayName=Sn;var aT=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=nn(Sn,e.__scopeScrollArea),[s,i]=m.useState(!1);return m.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(Zt,{present:n||s,children:u.jsx(Uh,{"data-state":s?"visible":"hidden",...r,ref:t})})}),lT=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=nn(Sn,e.__scopeScrollArea),s=e.orientation==="horizontal",i=Ys(()=>l("SCROLL_END"),100),[a,l]=sT("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 m.useEffect(()=>{if(a==="idle"){const c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),m.useEffect(()=>{const c=o.viewport,d=s?"scrollLeft":"scrollTop";if(c){let f=c[d];const h=()=>{const p=c[d];f!==p&&(l("SCROLL"),i()),f=p};return c.addEventListener("scroll",h),()=>c.removeEventListener("scroll",h)}},[o.viewport,s,l,i]),u.jsx(Zt,{present:n||a!=="hidden",children:u.jsx(Xa,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:he(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:he(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Uh=m.forwardRef((e,t)=>{const n=nn(Sn,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,i]=m.useState(!1),a=e.orientation==="horizontal",l=Ys(()=>{if(n.viewport){const c=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?c:d)}},10);return Er(n.viewport,l),Er(n.content,l),u.jsx(Zt,{present:r||s,children:u.jsx(Xa,{"data-state":s?"visible":"hidden",...o,ref:t})})}),Xa=m.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,o=nn(Sn,e.__scopeScrollArea),s=m.useRef(null),i=m.useRef(0),[a,l]=m.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=qh(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:h=>s.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,p){return pT(h,i.current,a,p)}return n==="horizontal"?u.jsx(cT,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollLeft,p=Gh(h,a,o.dir);s.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollLeft=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollLeft=f(h,o.dir))}}):n==="vertical"?u.jsx(uT,{...d,ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const h=o.viewport.scrollTop,p=Gh(h,a);s.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:h=>{o.viewport&&(o.viewport.scrollTop=h)},onDragScroll:h=>{o.viewport&&(o.viewport.scrollTop=f(h))}}):null}),cT=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=nn(Sn,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),c=We(t,l,s.onScrollbarXChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Wh,{"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":Gs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),Xh(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:qs(i.paddingLeft),paddingEnd:qs(i.paddingRight)}})}})}),uT=m.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=nn(Sn,e.__scopeScrollArea),[i,a]=m.useState(),l=m.useRef(null),c=We(t,l,s.onScrollbarYChange);return m.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),u.jsx(Wh,{"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":Gs(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(s.viewport){const h=s.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),Xh(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&s.viewport&&i&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:qs(i.paddingTop),paddingEnd:qs(i.paddingBottom)}})}})}),[dT,Hh]=$h(Sn),Wh=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:d,onResize:f,...h}=e,p=nn(Sn,n),[v,x]=m.useState(null),y=We(t,R=>x(R)),g=m.useRef(null),b=m.useRef(""),T=p.viewport,k=r.content-r.viewport,S=At(d),C=At(l),E=Ys(f,10);function A(R){if(g.current){const D=R.clientX-g.current.left,B=R.clientY-g.current.top;c({x:D,y:B})}}return m.useEffect(()=>{const R=D=>{const B=D.target;(v==null?void 0:v.contains(B))&&S(D,k)};return document.addEventListener("wheel",R,{passive:!1}),()=>document.removeEventListener("wheel",R,{passive:!1})},[T,v,k,S]),m.useEffect(C,[r,C]),Er(v,E),Er(p.content,E),u.jsx(dT,{scope:n,scrollbar:v,hasThumb:o,onThumbChange:At(s),onThumbPointerUp:At(i),onThumbPositionChange:C,onThumbPointerDown:At(a),children:u.jsx(Se.div,{...h,ref:y,style:{position:"absolute",...h.style},onPointerDown:he(e.onPointerDown,R=>{R.button===0&&(R.target.setPointerCapture(R.pointerId),g.current=v.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),A(R))}),onPointerMove:he(e.onPointerMove,A),onPointerUp:he(e.onPointerUp,R=>{const D=R.target;D.hasPointerCapture(R.pointerId)&&D.releasePointerCapture(R.pointerId),document.body.style.webkitUserSelect=b.current,p.viewport&&(p.viewport.style.scrollBehavior=""),g.current=null})})})}),Ks="ScrollAreaThumb",Vh=m.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=Hh(Ks,e.__scopeScrollArea);return u.jsx(Zt,{present:n||o.hasThumb,children:u.jsx(fT,{ref:t,...r})})}),fT=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=nn(Ks,n),i=Hh(Ks,n),{onThumbPositionChange:a}=i,l=We(t,f=>i.onThumbChange(f)),c=m.useRef(void 0),d=Ys(()=>{c.current&&(c.current(),c.current=void 0)},100);return m.useEffect(()=>{const f=s.viewport;if(f){const h=()=>{if(d(),!c.current){const p=mT(f,a);c.current=p,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[s.viewport,d,a]),u.jsx(Se.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:he(e.onPointerDownCapture,f=>{const p=f.target.getBoundingClientRect(),v=f.clientX-p.left,x=f.clientY-p.top;i.onThumbPointerDown({x:v,y:x})}),onPointerUp:he(e.onPointerUp,i.onThumbPointerUp)})});Vh.displayName=Ks;var Ja="ScrollAreaCorner",Kh=m.forwardRef((e,t)=>{const n=nn(Ja,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?u.jsx(hT,{...e,ref:t}):null});Kh.displayName=Ja;var hT=m.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=nn(Ja,n),[s,i]=m.useState(0),[a,l]=m.useState(0),c=!!(s&&a);return Er(o.scrollbarX,()=>{var f;const d=((f=o.scrollbarX)==null?void 0:f.offsetHeight)||0;o.onCornerHeightChange(d),l(d)}),Er(o.scrollbarY,()=>{var f;const d=((f=o.scrollbarY)==null?void 0:f.offsetWidth)||0;o.onCornerWidthChange(d),i(d)}),c?u.jsx(Se.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 qs(e){return e?parseInt(e,10):0}function qh(e,t){const n=e/t;return isNaN(n)?0:n}function Gs(e){const t=qh(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function pT(e,t,n,r="ltr"){const o=Gs(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 Yh([l,c],f)(e)}function Gh(e,t,n="ltr"){const r=Gs(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=qa(e,l);return Yh([0,i],[0,a])(c)}function Yh(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 Xh(e,t){return e>0&&e<t}var mT=(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 Ys(e,t){const n=At(e),r=m.useRef(0);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),m.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Er(e,t){const n=At(t);Nt(()=>{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 Jh=Fh,gT=zh,xT=Kh;const Zh=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Jh,{ref:r,className:se("relative overflow-hidden",e),...n,children:[u.jsx(gT,{className:"h-full w-full rounded-[inherit] overflow-auto",children:t}),u.jsx(Qh,{}),u.jsx(xT,{})]}));Zh.displayName=Jh.displayName;const Qh=m.forwardRef(({className:e,orientation:t="vertical",...n},r)=>u.jsx(Ya,{ref:r,orientation:t,className:se("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(Vh,{className:"relative flex-1 rounded-full bg-border"})}));Qh.displayName=Ya.displayName;var ep=1,yT=.9,vT=.8,bT=.17,Za=.1,Qa=.999,wT=.9999,ST=.99,CT=/[\\\/_+.#"@\[\(\{&]/,TT=/[\\\/_+.#"@\[\(\{&]/g,kT=/[\s-]/,tp=/[\s-]/g;function el(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?ep:ST;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(s),c=n.indexOf(l,o),d=0,f,h,p,v;c>=0;)f=el(e,t,n,r,c+1,s+1,i),f>d&&(c===o?f*=ep:CT.test(e.charAt(c-1))?(f*=vT,p=e.slice(o,c-1).match(TT),p&&o>0&&(f*=Math.pow(Qa,p.length))):kT.test(e.charAt(c-1))?(f*=yT,v=e.slice(o,c-1).match(tp),v&&o>0&&(f*=Math.pow(Qa,v.length))):(f*=bT,o>0&&(f*=Math.pow(Qa,c-o))),e.charAt(c)!==t.charAt(s)&&(f*=wT)),(f<Za&&n.charAt(c-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(c-1)!==r.charAt(s))&&(h=el(e,t,n,r,c+1,s+2,i),h*Za>f&&(f=h*Za)),f>d&&(d=f),c=n.indexOf(l,c+1);return i[a]=d,d}function np(e){return e.toLowerCase().replace(tp," ")}function ET(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,el(e,t,np(e),np(t),0,0,{})}var mo='[cmdk-group=""]',tl='[cmdk-group-items=""]',IT='[cmdk-group-heading=""]',rp='[cmdk-item=""]',op=`${rp}:not([aria-disabled="true"])`,nl="cmdk-item-select",Ir="data-value",NT=(e,t,n)=>ET(e,t,n),sp=m.createContext(void 0),go=()=>m.useContext(sp),ip=m.createContext(void 0),rl=()=>m.useContext(ip),ap=m.createContext(void 0),lp=m.forwardRef((e,t)=>{let n=Nr(()=>{var _,Q;return{search:"",value:(Q=(_=e.value)!=null?_:e.defaultValue)!=null?Q:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Nr(()=>new Set),o=Nr(()=>new Map),s=Nr(()=>new Map),i=Nr(()=>new Set),a=cp(e),{label:l,children:c,value:d,onValueChange:f,filter:h,shouldFilter:p,loop:v,disablePointerSelection:x=!1,vimBindings:y=!0,...g}=e,b=$t(),T=$t(),k=$t(),S=m.useRef(null),C=FT();sr(()=>{if(d!==void 0){let _=d.trim();n.current.value=_,E.emit()}},[d]),sr(()=>{C(6,G)},[]);let E=m.useMemo(()=>({subscribe:_=>(i.current.add(_),()=>i.current.delete(_)),snapshot:()=>n.current,setState:(_,Q,V)=>{var H,ne,W,O;if(!Object.is(n.current[_],Q)){if(n.current[_]=Q,_==="search")Y(),D(),C(1,B);else if(_==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let K=document.getElementById(k);K?K.focus():(H=document.getElementById(b))==null||H.focus()}if(C(7,()=>{var K;n.current.selectedItemId=(K=M())==null?void 0:K.id,E.emit()}),V||C(5,G),((ne=a.current)==null?void 0:ne.value)!==void 0){let K=Q??"";(O=(W=a.current).onValueChange)==null||O.call(W,K);return}}E.emit()}},emit:()=>{i.current.forEach(_=>_())}}),[]),A=m.useMemo(()=>({value:(_,Q,V)=>{var H;Q!==((H=s.current.get(_))==null?void 0:H.value)&&(s.current.set(_,{value:Q,keywords:V}),n.current.filtered.items.set(_,R(Q,V)),C(2,()=>{D(),E.emit()}))},item:(_,Q)=>(r.current.add(_),Q&&(o.current.has(Q)?o.current.get(Q).add(_):o.current.set(Q,new Set([_]))),C(3,()=>{Y(),D(),n.current.value||B(),E.emit()}),()=>{s.current.delete(_),r.current.delete(_),n.current.filtered.items.delete(_);let V=M();C(4,()=>{Y(),(V==null?void 0:V.getAttribute("id"))===_&&B(),E.emit()})}),group:_=>(o.current.has(_)||o.current.set(_,new Set),()=>{s.current.delete(_),o.current.delete(_)}),filter:()=>a.current.shouldFilter,label:l||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:b,inputId:k,labelId:T,listInnerRef:S}),[]);function R(_,Q){var V,H;let ne=(H=(V=a.current)==null?void 0:V.filter)!=null?H:NT;return _?ne(_,n.current.search,Q):0}function D(){if(!n.current.search||a.current.shouldFilter===!1)return;let _=n.current.filtered.items,Q=[];n.current.filtered.groups.forEach(H=>{let ne=o.current.get(H),W=0;ne.forEach(O=>{let K=_.get(O);W=Math.max(K,W)}),Q.push([H,W])});let V=S.current;j().sort((H,ne)=>{var W,O;let K=H.getAttribute("id"),z=ne.getAttribute("id");return((W=_.get(z))!=null?W:0)-((O=_.get(K))!=null?O:0)}).forEach(H=>{let ne=H.closest(tl);ne?ne.appendChild(H.parentElement===ne?H:H.closest(`${tl} > *`)):V.appendChild(H.parentElement===V?H:H.closest(`${tl} > *`))}),Q.sort((H,ne)=>ne[1]-H[1]).forEach(H=>{var ne;let W=(ne=S.current)==null?void 0:ne.querySelector(`${mo}[${Ir}="${encodeURIComponent(H[0])}"]`);W==null||W.parentElement.appendChild(W)})}function B(){let _=j().find(V=>V.getAttribute("aria-disabled")!=="true"),Q=_==null?void 0:_.getAttribute(Ir);E.setState("value",Q||void 0)}function Y(){var _,Q,V,H;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let ne=0;for(let W of r.current){let O=(Q=(_=s.current.get(W))==null?void 0:_.value)!=null?Q:"",K=(H=(V=s.current.get(W))==null?void 0:V.keywords)!=null?H:[],z=R(O,K);n.current.filtered.items.set(W,z),z>0&&ne++}for(let[W,O]of o.current)for(let K of O)if(n.current.filtered.items.get(K)>0){n.current.filtered.groups.add(W);break}n.current.filtered.count=ne}function G(){var _,Q,V;let H=M();H&&(((_=H.parentElement)==null?void 0:_.firstChild)===H&&((V=(Q=H.closest(mo))==null?void 0:Q.querySelector(IT))==null||V.scrollIntoView({block:"nearest"})),H.scrollIntoView({block:"nearest"}))}function M(){var _;return(_=S.current)==null?void 0:_.querySelector(`${rp}[aria-selected="true"]`)}function j(){var _;return Array.from(((_=S.current)==null?void 0:_.querySelectorAll(op))||[])}function I(_){let Q=j()[_];Q&&E.setState("value",Q.getAttribute(Ir))}function U(_){var Q;let V=M(),H=j(),ne=H.findIndex(O=>O===V),W=H[ne+_];(Q=a.current)!=null&&Q.loop&&(W=ne+_<0?H[H.length-1]:ne+_===H.length?H[0]:H[ne+_]),W&&E.setState("value",W.getAttribute(Ir))}function $(_){let Q=M(),V=Q==null?void 0:Q.closest(mo),H;for(;V&&!H;)V=_>0?LT(V,mo):$T(V,mo),H=V==null?void 0:V.querySelector(op);H?E.setState("value",H.getAttribute(Ir)):U(_)}let P=()=>I(j().length-1),q=_=>{_.preventDefault(),_.metaKey?P():_.altKey?$(1):U(1)},Z=_=>{_.preventDefault(),_.metaKey?I(0):_.altKey?$(-1):U(-1)};return m.createElement(Se.div,{ref:t,tabIndex:-1,...g,"cmdk-root":"",onKeyDown:_=>{var Q;(Q=g.onKeyDown)==null||Q.call(g,_);let V=_.nativeEvent.isComposing||_.keyCode===229;if(!(_.defaultPrevented||V))switch(_.key){case"n":case"j":{y&&_.ctrlKey&&q(_);break}case"ArrowDown":{q(_);break}case"p":case"k":{y&&_.ctrlKey&&Z(_);break}case"ArrowUp":{Z(_);break}case"Home":{_.preventDefault(),I(0);break}case"End":{_.preventDefault(),P();break}case"Enter":{_.preventDefault();let H=M();if(H){let ne=new Event(nl);H.dispatchEvent(ne)}}}}},m.createElement("label",{"cmdk-label":"",htmlFor:A.inputId,id:A.labelId,style:zT},l),Xs(e,_=>m.createElement(ip.Provider,{value:E},m.createElement(sp.Provider,{value:A},_))))}),AT=m.forwardRef((e,t)=>{var n,r;let o=$t(),s=m.useRef(null),i=m.useContext(ap),a=go(),l=cp(e),c=(r=(n=l.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;sr(()=>{if(!c)return a.item(o,i==null?void 0:i.id)},[c]);let d=up(o,s,[e.value,e.children,s],e.keywords),f=rl(),h=Fn(C=>C.value&&C.value===d.current),p=Fn(C=>c||a.filter()===!1?!0:C.search?C.filtered.items.get(o)>0:!0);m.useEffect(()=>{let C=s.current;if(!(!C||e.disabled))return C.addEventListener(nl,v),()=>C.removeEventListener(nl,v)},[p,e.onSelect,e.disabled]);function v(){var C,E;x(),(E=(C=l.current).onSelect)==null||E.call(C,d.current)}function x(){f.setState("value",d.current,!0)}if(!p)return null;let{disabled:y,value:g,onSelect:b,forceMount:T,keywords:k,...S}=e;return m.createElement(Se.div,{ref:An(s,t),...S,id:o,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!h,"data-disabled":!!y,"data-selected":!!h,onPointerMove:y||a.getDisablePointerSelection()?void 0:x,onClick:y?void 0:v},e.children)}),jT=m.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:o,...s}=e,i=$t(),a=m.useRef(null),l=m.useRef(null),c=$t(),d=go(),f=Fn(p=>o||d.filter()===!1?!0:p.search?p.filtered.groups.has(i):!0);sr(()=>d.group(i),[]),up(i,a,[e.value,e.heading,l]);let h=m.useMemo(()=>({id:i,forceMount:o}),[o]);return m.createElement(Se.div,{ref:An(a,t),...s,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&m.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:c},n),Xs(e,p=>m.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?c:void 0},m.createElement(ap.Provider,{value:h},p))))}),_T=m.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,o=m.useRef(null),s=Fn(i=>!i.search);return!n&&!s?null:m.createElement(Se.div,{ref:An(o,t),...r,"cmdk-separator":"",role:"separator"})}),MT=m.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,o=e.value!=null,s=rl(),i=Fn(c=>c.search),a=Fn(c=>c.selectedItemId),l=go();return m.useEffect(()=>{e.value!=null&&s.setState("search",e.value)},[e.value]),m.createElement(Se.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:o?e.value:i,onChange:c=>{o||s.setState("search",c.target.value),n==null||n(c.target.value)}})}),RT=m.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...o}=e,s=m.useRef(null),i=m.useRef(null),a=Fn(c=>c.selectedItemId),l=go();return m.useEffect(()=>{if(i.current&&s.current){let c=i.current,d=s.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let p=c.offsetHeight;d.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return h.observe(c),()=>{cancelAnimationFrame(f),h.unobserve(c)}}},[]),m.createElement(Se.div,{ref:An(s,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:l.listId},Xs(e,c=>m.createElement("div",{ref:An(i,l.listInnerRef),"cmdk-list-sizer":""},c)))}),PT=m.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:o,contentClassName:s,container:i,...a}=e;return m.createElement(Da,{open:n,onOpenChange:r},m.createElement(La,{container:i},m.createElement(io,{"cmdk-overlay":"",className:o}),m.createElement(ao,{"aria-label":e.label,"cmdk-dialog":"",className:s},m.createElement(lp,{ref:t,...a}))))}),OT=m.forwardRef((e,t)=>Fn(n=>n.filtered.count===0)?m.createElement(Se.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),DT=m.forwardRef((e,t)=>{let{progress:n,children:r,label:o="Loading...",...s}=e;return m.createElement(Se.div,{ref:t,...s,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},Xs(e,i=>m.createElement("div",{"aria-hidden":!0},i)))}),Kt=Object.assign(lp,{List:RT,Item:AT,Input:MT,Group:jT,Separator:_T,Dialog:PT,Empty:OT,Loading:DT});function LT(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function $T(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function cp(e){let t=m.useRef(e);return sr(()=>{t.current=e}),t}var sr=typeof window>"u"?m.useEffect:m.useLayoutEffect;function Nr(e){let t=m.useRef();return t.current===void 0&&(t.current=e()),t}function Fn(e){let t=rl(),n=()=>e(t.snapshot());return m.useSyncExternalStore(t.subscribe,n,n)}function up(e,t,n,r=[]){let o=m.useRef(),s=go();return sr(()=>{var i;let a=(()=>{var c;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(c=d.current.textContent)==null?void 0:c.trim():o.current}})(),l=r.map(c=>c.trim());s.value(e,a,l),(i=t.current)==null||i.setAttribute(Ir,a),o.current=a}),o}var FT=()=>{let[e,t]=m.useState(),n=Nr(()=>new Map);return sr(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,o)=>{n.current.set(r,o),t({})}};function BT(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Xs({asChild:e,children:t},n){return e&&m.isValidElement(t)?m.cloneElement(BT(t),{ref:t.ref},n(t.props.children)):n(t)}var zT={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const dp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt,{ref:n,className:se("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));dp.displayName=Kt.displayName;const fp=m.forwardRef(({className:e,...t},n)=>u.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[u.jsx(ae.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),u.jsx(Kt.Input,{ref:n,className:se("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));fp.displayName=Kt.Input.displayName;const hp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.List,{ref:n,className:se("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));hp.displayName=Kt.List.displayName;const pp=m.forwardRef((e,t)=>u.jsx(Kt.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));pp.displayName=Kt.Empty.displayName;const mp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.Group,{ref:n,className:se("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));mp.displayName=Kt.Group.displayName;const UT=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.Separator,{ref:n,className:se("-mx-1 h-px bg-border",e),...t}));UT.displayName=Kt.Separator.displayName;const gp=m.forwardRef(({className:e,...t},n)=>u.jsx(Kt.Item,{ref:n,className:se("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),...t}));gp.displayName=Kt.Item.displayName;const Js=m.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{type:t,className:se("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}));Js.displayName="Input";const HT="group relative p-3 rounded-lg cursor-pointer transition-colors border text-gray-900 dark:text-slate-100",WT="bg-slate-700 border-slate-600 hover:bg-slate-600",VT="bg-slate-600 border-slate-500";function KT({thread:e,isActive:t,editingThreadId:n,editingTitle:r,onSelect:o,onStartEditing:s,onEditingTitleChange:i,onSaveEditing:a,onCancelEditing:l,onShare:c,onDelete:d,showEditTitle:f,showDeleteButton:h,formatDate:p,getDisplayThreadTitle:v,secondaryLine:x,itemClassName:y,activeItemClassName:g}){const b=n===e.threadId,T=t?`${g??VT}`:`${y??WT}`,k=S=>{S.stopPropagation(),o(e.threadId)};return u.jsxs("div",{onClick:k,className:`${HT} ${T}`,children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("div",{className:"flex-1 min-w-0",children:b?u.jsxs("div",{className:"flex items-center gap-2",onClick:S=>S.stopPropagation(),children:[u.jsx(Js,{value:r,onChange:S=>i(S.target.value),onKeyDown:S=>{S.key==="Enter"?a(e.threadId):S.key==="Escape"&&l()},className:"h-6 text-sm",autoFocus:!0}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:()=>a(e.threadId),className:"h-6 w-6 p-0",children:u.jsx(ae.Check,{size:12})}),u.jsx(tt,{variant:"ghost",size:"sm",onClick:l,className:"h-6 w-6 p-0",children:u.jsx(ae.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:v(e)}),u.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mt-1",children:[u.jsx(ae.Calendar,{size:10}),u.jsx("span",{children:p(e.updatedAt||e.createdAt)})]}),x&&u.jsx("div",{className:"text-[11px] text-muted-foreground mt-1",children:x})]})}),u.jsx("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity ml-2",children:u.jsxs(aa,{children:[u.jsx(la,{asChild:!0,children:u.jsx(tt,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:u.jsx(ae.MoreHorizontal,{size:12})})}),u.jsxs(xs,{align:"end",sideOffset:6,className:"w-44",children:[u.jsxs(Jn,{onClick:S=>{S.preventDefault(),c(e.threadId)},children:[u.jsx(ae.Share2,{className:"mr-2 h-4 w-4"}),"Share thread"]}),f&&n!==e.threadId&&u.jsxs(Jn,{onClick:S=>{S.preventDefault(),s(e,S)},children:[u.jsx(ae.Edit3,{className:"mr-2 h-4 w-4"}),"Rename"]}),h&&d&&u.jsxs(Jn,{className:"text-red-400 hover:text-red-300",onClick:S=>{S.preventDefault(),d(e.threadId,S)},children:[u.jsx(ae.Trash2,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})})]}),t&&u.jsx("div",{className:"absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-blue-400 rounded-r"})]})}const xp=25,yp="thread-manager-view",qT=e=>e==="default"||e==="shared",GT=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(yp);if(qT(e))return e}catch{}return null};function YT({defaultView:e}={}){const[t,n]=w.useState(()=>GT()??e??"default");w.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(yp,t)}catch{}},[t]);const r=w.useCallback(o=>{n(o)},[]);return{view:t,setView:r}}const XT=[{key:"default",label:"My chats"},{key:"shared",label:"Shared with you"}];function ol({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,view:f,defaultView:h,onViewChange:p,viewOptions:v,viewState:x,showHeader:y=!0}){const{threads:g,sharedThreads:b,currentThreadId:T,setCurrentThreadId:k,isLoading:S,isLoadingSharedThreads:C,smartOrgUsers:E,isLoadingSmartOrgUsers:A,actions:R,shareInFlight:D,shareStatus:B,clearShareStatus:Y}=Fo(),{createThread:G,deleteThread:M,renameThread:j,shareThread:I}=R,{loadThread:U}=Bo(),$=i??T,[P,q]=w.useState(Array.isArray(g)?g:[]),Z=w.useRef(P.length>0),_=w.useRef(null),Q=w.useRef(0),[V,H]=w.useState(null),[ne,W]=w.useState(""),[O,K]=w.useState(!1),[z,te]=w.useState(!1),[X,ge]=w.useState(null),[le,oe]=w.useState(""),me=v&&v.length>0?v:XT,be=YT({defaultView:h}),Me=x??be,Ce=f??Me.view,Ue=w.useCallback(J=>{f||Me.setView(J),p==null||p(J)},[f,p,Me]),et=me.find(J=>J.key===Ce)??me[0],rt=J=>{ge(J),oe(""),te(!0)},Ke=()=>{te(!1),ge(null),oe(""),Y()},Ge=w.useCallback(async J=>{if(!X||D)return;const L=J.user_id??J.id??J.username??J.email;if(L)try{await I(X,L),setTimeout(()=>Ke(),600)}catch(ce){console.error("Failed to share thread:",ce)}},[Ke,D,X,I]),at=w.useMemo(()=>{const J=le.trim().toLowerCase();return J?E.filter(L=>`${L.username??""} ${L.user_id??""} ${L.email??""} ${L.name??""}`.toLowerCase().includes(J)):E},[E,le]),bt=Ce==="shared",ht=bt?b:P,Tt=bt?C:S,Ie=bt?"No shared conversations yet":"No conversations yet",Fe=J=>{const L=J.sharedAt?` • ${ut(J.sharedAt)}`:"";return`Shared by ${J.sharedByUserId}${L}`},pt=J=>"sharedByUserId"in J;w.useEffect(()=>{const J=Array.isArray(g)?g:[];if(J.length>0){Z.current=!0,q(J);return}S||(Z.current=!1,q(J))},[g,S]),w.useEffect(()=>{if(!_.current)return;const J=_.current.querySelector("[data-radix-scroll-area-viewport]");if(!J)return;let L=null,ce=null;return L=requestAnimationFrame(()=>{ce=requestAnimationFrame(()=>{J.scrollTop=Q.current})}),()=>{L!==null&&cancelAnimationFrame(L),ce!==null&&cancelAnimationFrame(ce)}},[P]);const wt=async J=>{try{k(J),await U(J,void 0,{clearProgress:!0}),a==null||a(J),l==null||l(J)}catch(L){console.error("Failed to select thread:",L)}},Dt=async()=>{try{K(!0);const J=await G();J&&(c==null||c(J),a==null||a(J))}catch(J){console.error("Failed to create thread:",J)}finally{K(!1)}},Pe=async(J,L)=>{if(L.stopPropagation(),!!confirm("Delete this thread?")){if(_.current){const ce=_.current.querySelector("[data-radix-scroll-area-viewport]");ce&&(Q.current=ce.scrollTop)}try{await M(J),d==null||d(J)}catch(ce){console.error("Failed to delete thread:",ce)}}},qt=(J,L)=>{L.stopPropagation(),H(J.threadId),W(J.title||`Thread ${J.threadId.slice(0,8)}`)},Ye=async J=>{if(ne.trim())try{await j(J,ne.trim()),H(null),W("")}catch(L){console.error("Failed to update title:",L)}},He=()=>{H(null),W("")},ut=J=>{if(!J)return"";try{const L=new Date(J),xe=new Date().getTime()-L.getTime(),Be=Math.floor(xe/(1e3*60*60*24));return Be===0?L.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):Be===1?"Yesterday":Be<7?`${Be} days ago`:L.toLocaleDateString()}catch{return""}},kt=J=>J.title||`Thread ${J.threadId.slice(0,8)}`,qe=J=>{const L=kt(J);return L.length<=xp?L:`${L.slice(0,xp)}...`};return u.jsxs("div",{className:`flex flex-col h-full ${e} ${s.container||""}`,children:[y&&u.jsxs("div",{className:s.header||"flex flex-col gap-2 px-1 py-0 border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900 shadow-sm",children:[t&&u.jsx("div",{className:"flex justify-end",children:u.jsxs(tt,{onClick:Dt,disabled:O||S,className:s.createButton||"px-3 py-2 gap-1",size:"sm",variant:"ghost",title:O?"Creating...":"New Chat",children:[u.jsx(ae.Edit3,{size:16}),u.jsx("span",{children:"New chat"})]})}),u.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-200 uppercase tracking-wide leading-tight",children:[u.jsx("span",{children:"Current View"}),u.jsxs(aa,{children:[u.jsx(la,{asChild:!0,children:u.jsx(tt,{variant:"outline",size:"sm",className:"text-[11px] text-slate-700 dark:text-slate-200 border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 hover:bg-slate-50 dark:hover:bg-slate-800 px-2 py-0",children:et.label})}),u.jsx(xs,{align:"start",sideOffset:6,className:"w-40",children:me.map(J=>u.jsxs(Jn,{className:"justify-between text-[12px]",onClick:L=>{L.preventDefault(),Ue(J.key)},children:[u.jsx("span",{children:J.label}),Ce===J.key&&u.jsx(ae.Check,{className:"h-3 w-3"})]},J.key))})]})]})]}),u.jsx(Zh,{ref:_,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:Tt?u.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-8 text-slate-400",children:[u.jsx(ae.Loader2,{className:"h-5 w-5 animate-spin"}),u.jsx("span",{className:"text-sm",children:"Loading threads…"})]}):ht.length===0?u.jsxs("div",{className:"text-center py-8 text-slate-400",children:[u.jsx(ae.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:Ie})]}):ht.slice().sort((J,L)=>new Date(L.updatedAt||L.createdAt||"").getTime()-new Date(J.updatedAt||J.createdAt||"").getTime()).map(J=>u.jsx(KT,{thread:J,isActive:$===J.threadId,editingThreadId:V,editingTitle:ne,onSelect:wt,onStartEditing:qt,onEditingTitleChange:L=>W(L),onSaveEditing:Ye,onCancelEditing:He,onShare:()=>rt(J.threadId),onDelete:Pe,showEditTitle:r,showDeleteButton:n,formatDate:ut,getDisplayThreadTitle:qe,secondaryLine:bt&&pt(J)?Fe(J):void 0,itemClassName:s.threadItem,activeItemClassName:s.activeThread},J.threadId))})}),u.jsx(mh,{open:z,onOpenChange:J=>!J&&Ke(),children:u.jsxs($a,{className:"max-w-md p-0",children:[u.jsx(Fa,{children:u.jsx(Ba,{children:"Share thread"})}),u.jsxs(dp,{children:[u.jsx(fp,{autoFocus:!0,value:le,onValueChange:J=>oe(J),placeholder:"Search for users (name, email, id)..."}),u.jsxs(hp,{children:[B&&u.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-xs text-muted-foreground",children:[D&&u.jsx(ae.Loader2,{className:"h-3 w-3 animate-spin"}),u.jsx("span",{className:B.startsWith("Failed")?"text-red-500":B.startsWith("Shared")?"text-emerald-500":"text-slate-600 dark:text-slate-400",children:B})]}),u.jsx(pp,{children:A?u.jsxs("span",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(ae.Loader2,{className:"h-4 w-4 animate-spin"}),"Loading users…"]}):"No matching users found"}),u.jsx(mp,{heading:"Users",children:at.map(J=>{const L=J.username??J.user_id??J.email??"Unknown user",ce=[J.email,J.user_id].filter(Boolean).join(" • "),xe=J.user_id??J.id??J.username??J.email??L;return u.jsx(gp,{onSelect:()=>Ge(J),children:u.jsxs("div",{className:"flex flex-col items-start text-sm",children:[u.jsx("span",{className:"font-medium",children:L}),ce&&u.jsx("span",{className:"text-xs text-muted-foreground",children:ce})]})},xe)})})]})]})]})})]})}const JT=({timelineEntries:e,activeCheckpointId:t,onSelectCheckpoint:n,messagePreviews:r,className:o,onHoverStart:s,onHoverEnd:i})=>{const a=e??[],l=a.length>0,c=w.useMemo(()=>l?[...a].reverse():[],[a,l]),d=t??(a.length?a[a.length-1].id:null);if(!l)return null;const h=["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:h,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(p=>{const v=d===p.id,x=(r==null?void 0:r.get(p.id))??null;return u.jsxs("button",{type:"button",disabled:!n,onClick:()=>n==null?void 0:n(p.id),className:`relative flex items-start gap-2 text-left text-[11px] transition ${v?"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 ${v?"border-primary bg-primary/10 text-primary":"border-border bg-background"}`,children:u.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${v?"bg-primary":"bg-border"}`})}),u.jsxs("span",{className:"flex-1",children:[u.jsx("span",{className:"block font-medium leading-tight",children:p.label||"User input"}),u.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-muted-foreground/70",children:[p.step!==null?`STEP ${p.step}`:"STEP —",p.next?` - ${p.next}`:""]}),x&&u.jsx("p",{className:"text-[10px] text-muted-foreground/80 mt-1 line-clamp-2",title:x,children:x})]})]},p.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 Ar(e){if(!(typeof globalThis>"u"))return globalThis[e]}function ZT(e){if(typeof e!="string")return;const t=e.trim();if(t)return Cn(t)}function vp(){const e=[Ar("__API_BASE_URL__"),Ar("__CHAT_API_BASE_URL__"),Ar("__CHAT_API_URL__")];for(const t of e){const n=ZT(t);if(n)return n}}function bp(){const e=[Ar("__API_AUTH_TOKEN__"),Ar("__CHAT_API_KEY__"),Ar("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function wp(...e){for(const t of e)if(typeof t=="string"&&t.trim())return Cn(t);return Cn()}function Sp(){const e={},t=vp(),n=bp();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function Cp(){const e=Sp(),t=Nn.getAuthToken(),n=vp();return{apiBaseUrl:wp(e.baseUrl,Nn.baseUrl,n),apiKey:t||e.apiKey||bp()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Tp="chat-settings";function QT(){try{const e=localStorage.getItem(Tp);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function ek(e){try{const t={...e,apiBaseUrl:Cn(e.apiBaseUrl)};localStorage.setItem(Tp,JSON.stringify(t)),t.apiKey&&Nn.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function tk(){const e=Cp(),t=QT(),n=Nn.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:wp(Nn.baseUrl,r,e.apiBaseUrl)}}function nk(e){Nn.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),ek(e)}var rk="Label",kp=m.forwardRef((e,t)=>u.jsx(Se.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())}}));kp.displayName=rk;var Ep=kp;const ok=bo.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),rn=m.forwardRef(({className:e,...t},n)=>u.jsx(Ep,{ref:n,className:se(ok(),e),...t}));rn.displayName=Ep.displayName;function Ip(e){const t=m.useRef({value:e,previous:e});return m.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Np=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"}),sk="VisuallyHidden",ik=m.forwardRef((e,t)=>u.jsx(Se.span,{...e,ref:t,style:{...Np,...e.style}}));ik.displayName=sk;var ak=[" ","Enter","ArrowUp","ArrowDown"],lk=[" ","Enter"],ir="Select",[Zs,Qs,ck]=Ei(ir),[jr,jE]=Tn(ir,[ck,ts]),ei=ts(),[uk,Bn]=jr(ir),[dk,fk]=jr(ir),Ap=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:h,required:p,form:v}=e,x=ei(t),[y,g]=m.useState(null),[b,T]=m.useState(null),[k,S]=m.useState(!1),C=Uo(c),[E,A]=pr({prop:r,defaultProp:o??!1,onChange:s,caller:ir}),[R,D]=pr({prop:i,defaultProp:a,onChange:l,caller:ir}),B=m.useRef(null),Y=y?v||!!y.closest("form"):!0,[G,M]=m.useState(new Set),j=Array.from(G).map(I=>I.props.value).join(";");return u.jsx(ju,{...x,children:u.jsxs(uk,{required:p,scope:t,trigger:y,onTriggerChange:g,valueNode:b,onValueNodeChange:T,valueNodeHasChildren:k,onValueNodeHasChildrenChange:S,contentId:$t(),value:R,onValueChange:D,open:E,onOpenChange:A,dir:C,triggerPointerDownPosRef:B,disabled:h,children:[u.jsx(Zs.Provider,{scope:t,children:u.jsx(dk,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(I=>{M(U=>new Set(U).add(I))},[]),onNativeOptionRemove:m.useCallback(I=>{M(U=>{const $=new Set(U);return $.delete(I),$})},[]),children:n})}),Y?u.jsxs(Qp,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:R,onChange:I=>D(I.target.value),disabled:h,form:v,children:[R===void 0?u.jsx("option",{value:""}):null,Array.from(G)]},j):null]})})};Ap.displayName=ir;var jp="SelectTrigger",_p=m.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=ei(n),i=Bn(jp,n),a=i.disabled||r,l=We(t,i.onTriggerChange),c=Qs(n),d=m.useRef("touch"),[f,h,p]=tm(x=>{const y=c().filter(T=>!T.disabled),g=y.find(T=>T.value===i.value),b=nm(y,x,g);b!==void 0&&i.onValueChange(b.value)}),v=x=>{a||(i.onOpenChange(!0),p()),x&&(i.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)})};return u.jsx(_u,{asChild:!0,...s,children:u.jsx(Se.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":em(i.value)?"":void 0,...o,ref:l,onClick:he(o.onClick,x=>{x.currentTarget.focus(),d.current!=="mouse"&&v(x)}),onPointerDown:he(o.onPointerDown,x=>{d.current=x.pointerType;const y=x.target;y.hasPointerCapture(x.pointerId)&&y.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&x.pointerType==="mouse"&&(v(x),x.preventDefault())}),onKeyDown:he(o.onKeyDown,x=>{const y=f.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&h(x.key),!(y&&x.key===" ")&&ak.includes(x.key)&&(v(),x.preventDefault())})})})});_p.displayName=jp;var Mp="SelectValue",Rp=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Bn(Mp,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,f=We(t,l.onValueNodeChange);return Nt(()=>{c(d)},[c,d]),u.jsx(Se.span,{...a,ref:f,style:{pointerEvents:"none"},children:em(l.value)?u.jsx(u.Fragment,{children:i}):s})});Rp.displayName=Mp;var hk="SelectIcon",Pp=m.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(Se.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Pp.displayName=hk;var pk="SelectPortal",Op=e=>u.jsx(ns,{asChild:!0,...e});Op.displayName=pk;var ar="SelectContent",Dp=m.forwardRef((e,t)=>{const n=Bn(ar,e.__scopeSelect),[r,o]=m.useState();if(Nt(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?wo.createPortal(u.jsx(Lp,{scope:e.__scopeSelect,children:u.jsx(Zs.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx($p,{...e,ref:t})});Dp.displayName=ar;var fn=10,[Lp,zn]=jr(ar),mk="SelectContentImpl",gk=Wn.createSlot("SelectContent.RemoveScroll"),$p=m.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:h,collisionPadding:p,sticky:v,hideWhenDetached:x,avoidCollisions:y,...g}=e,b=Bn(ar,n),[T,k]=m.useState(null),[S,C]=m.useState(null),E=We(t,W=>k(W)),[A,R]=m.useState(null),[D,B]=m.useState(null),Y=Qs(n),[G,M]=m.useState(!1),j=m.useRef(!1);m.useEffect(()=>{if(T)return Gi(T)},[T]),Ai();const I=m.useCallback(W=>{const[O,...K]=Y().map(X=>X.ref.current),[z]=K.slice(-1),te=document.activeElement;for(const X of W)if(X===te||(X==null||X.scrollIntoView({block:"nearest"}),X===O&&S&&(S.scrollTop=0),X===z&&S&&(S.scrollTop=S.scrollHeight),X==null||X.focus(),document.activeElement!==te))return},[Y,S]),U=m.useCallback(()=>I([A,T]),[I,A,T]);m.useEffect(()=>{G&&U()},[G,U]);const{onOpenChange:$,triggerPointerDownPosRef:P}=b;m.useEffect(()=>{if(T){let W={x:0,y:0};const O=z=>{var te,X;W={x:Math.abs(Math.round(z.pageX)-(((te=P.current)==null?void 0:te.x)??0)),y:Math.abs(Math.round(z.pageY)-(((X=P.current)==null?void 0:X.y)??0))}},K=z=>{W.x<=10&&W.y<=10?z.preventDefault():T.contains(z.target)||$(!1),document.removeEventListener("pointermove",O),P.current=null};return P.current!==null&&(document.addEventListener("pointermove",O),document.addEventListener("pointerup",K,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",O),document.removeEventListener("pointerup",K,{capture:!0})}}},[T,$,P]),m.useEffect(()=>{const W=()=>$(!1);return window.addEventListener("blur",W),window.addEventListener("resize",W),()=>{window.removeEventListener("blur",W),window.removeEventListener("resize",W)}},[$]);const[q,Z]=tm(W=>{const O=Y().filter(te=>!te.disabled),K=O.find(te=>te.ref.current===document.activeElement),z=nm(O,W,K);z&&setTimeout(()=>z.ref.current.focus())}),_=m.useCallback((W,O,K)=>{const z=!j.current&&!K;(b.value!==void 0&&b.value===O||z)&&(R(W),z&&(j.current=!0))},[b.value]),Q=m.useCallback(()=>T==null?void 0:T.focus(),[T]),V=m.useCallback((W,O,K)=>{const z=!j.current&&!K;(b.value!==void 0&&b.value===O||z)&&B(W)},[b.value]),H=r==="popper"?sl:Fp,ne=H===sl?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:v,hideWhenDetached:x,avoidCollisions:y}:{};return u.jsx(Lp,{scope:n,content:T,viewport:S,onViewportChange:C,itemRefCallback:_,selectedItem:A,onItemLeave:Q,itemTextRefCallback:V,focusSelectedItem:U,selectedItemText:D,position:r,isPositioned:G,searchRef:q,children:u.jsx(ds,{as:gk,allowPinchZoom:!0,children:u.jsx(Wo,{asChild:!0,trapped:b.open,onMountAutoFocus:W=>{W.preventDefault()},onUnmountAutoFocus:he(o,W=>{var O;(O=b.trigger)==null||O.focus({preventScroll:!0}),W.preventDefault()}),children:u.jsx(Ho,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:W=>W.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:u.jsx(H,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:W=>W.preventDefault(),...g,...ne,onPlaced:()=>M(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...g.style},onKeyDown:he(g.onKeyDown,W=>{const O=W.ctrlKey||W.altKey||W.metaKey;if(W.key==="Tab"&&W.preventDefault(),!O&&W.key.length===1&&Z(W.key),["ArrowUp","ArrowDown","Home","End"].includes(W.key)){let z=Y().filter(te=>!te.disabled).map(te=>te.ref.current);if(["ArrowUp","End"].includes(W.key)&&(z=z.slice().reverse()),["ArrowUp","ArrowDown"].includes(W.key)){const te=W.target,X=z.indexOf(te);z=z.slice(X+1)}setTimeout(()=>I(z)),W.preventDefault()}})})})})})})});$p.displayName=mk;var xk="SelectItemAlignedPosition",Fp=m.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Bn(ar,n),i=zn(ar,n),[a,l]=m.useState(null),[c,d]=m.useState(null),f=We(t,E=>d(E)),h=Qs(n),p=m.useRef(!1),v=m.useRef(!0),{viewport:x,selectedItem:y,selectedItemText:g,focusSelectedItem:b}=i,T=m.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&x&&y&&g){const E=s.trigger.getBoundingClientRect(),A=c.getBoundingClientRect(),R=s.valueNode.getBoundingClientRect(),D=g.getBoundingClientRect();if(s.dir!=="rtl"){const te=D.left-A.left,X=R.left-te,ge=E.left-X,le=E.width+ge,oe=Math.max(le,A.width),me=window.innerWidth-fn,be=qa(X,[fn,Math.max(fn,me-oe)]);a.style.minWidth=le+"px",a.style.left=be+"px"}else{const te=A.right-D.right,X=window.innerWidth-R.right-te,ge=window.innerWidth-E.right-X,le=E.width+ge,oe=Math.max(le,A.width),me=window.innerWidth-fn,be=qa(X,[fn,Math.max(fn,me-oe)]);a.style.minWidth=le+"px",a.style.right=be+"px"}const B=h(),Y=window.innerHeight-fn*2,G=x.scrollHeight,M=window.getComputedStyle(c),j=parseInt(M.borderTopWidth,10),I=parseInt(M.paddingTop,10),U=parseInt(M.borderBottomWidth,10),$=parseInt(M.paddingBottom,10),P=j+I+G+$+U,q=Math.min(y.offsetHeight*5,P),Z=window.getComputedStyle(x),_=parseInt(Z.paddingTop,10),Q=parseInt(Z.paddingBottom,10),V=E.top+E.height/2-fn,H=Y-V,ne=y.offsetHeight/2,W=y.offsetTop+ne,O=j+I+W,K=P-O;if(O<=V){const te=B.length>0&&y===B[B.length-1].ref.current;a.style.bottom="0px";const X=c.clientHeight-x.offsetTop-x.offsetHeight,ge=Math.max(H,ne+(te?Q:0)+X+U),le=O+ge;a.style.height=le+"px"}else{const te=B.length>0&&y===B[0].ref.current;a.style.top="0px";const ge=Math.max(V,j+x.offsetTop+(te?_:0)+ne)+K;a.style.height=ge+"px",x.scrollTop=O-V+x.offsetTop}a.style.margin=`${fn}px 0`,a.style.minHeight=q+"px",a.style.maxHeight=Y+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,s.trigger,s.valueNode,a,c,x,y,g,s.dir,r]);Nt(()=>T(),[T]);const[k,S]=m.useState();Nt(()=>{c&&S(window.getComputedStyle(c).zIndex)},[c]);const C=m.useCallback(E=>{E&&v.current===!0&&(T(),b==null||b(),v.current=!1)},[T,b]);return u.jsx(vk,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:C,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(Se.div,{...o,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});Fp.displayName=xk;var yk="SelectPopperPosition",sl=m.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=fn,...s}=e,i=ei(n);return u.jsx(Mu,{...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)"}})});sl.displayName=yk;var[vk,il]=jr(ar,{}),al="SelectViewport",Bp=m.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=zn(al,n),i=il(al,n),a=We(t,s.onViewportChange),l=m.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(Zs.Slot,{scope:n,children:u.jsx(Se.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:he(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const v=window.innerHeight-fn*2,x=parseFloat(f.style.minHeight),y=parseFloat(f.style.height),g=Math.max(x,y);if(g<v){const b=g+p,T=Math.min(v,b),k=b-T;f.style.height=T+"px",f.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});Bp.displayName=al;var zp="SelectGroup",[bk,wk]=jr(zp),Sk=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=$t();return u.jsx(bk,{scope:n,id:o,children:u.jsx(Se.div,{role:"group","aria-labelledby":o,...r,ref:t})})});Sk.displayName=zp;var Up="SelectLabel",Hp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=wk(Up,n);return u.jsx(Se.div,{id:o.id,...r,ref:t})});Hp.displayName=Up;var ti="SelectItem",[Ck,Wp]=jr(ti),Vp=m.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Bn(ti,n),l=zn(ti,n),c=a.value===r,[d,f]=m.useState(s??""),[h,p]=m.useState(!1),v=We(t,b=>{var T;return(T=l.itemRefCallback)==null?void 0:T.call(l,b,r,o)}),x=$t(),y=m.useRef("touch"),g=()=>{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(Ck,{scope:n,value:r,disabled:o,textId:x,isSelected:c,onItemTextChange:m.useCallback(b=>{f(T=>T||((b==null?void 0:b.textContent)??"").trim())},[]),children:u.jsx(Zs.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(Se.div,{role:"option","aria-labelledby":x,"data-highlighted":h?"":void 0,"aria-selected":c&&h,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:v,onFocus:he(i.onFocus,()=>p(!0)),onBlur:he(i.onBlur,()=>p(!1)),onClick:he(i.onClick,()=>{y.current!=="mouse"&&g()}),onPointerUp:he(i.onPointerUp,()=>{y.current==="mouse"&&g()}),onPointerDown:he(i.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:he(i.onPointerMove,b=>{var T;y.current=b.pointerType,o?(T=l.onItemLeave)==null||T.call(l):y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:he(i.onPointerLeave,b=>{var T;b.currentTarget===document.activeElement&&((T=l.onItemLeave)==null||T.call(l))}),onKeyDown:he(i.onKeyDown,b=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&b.key===" "||(lk.includes(b.key)&&g(),b.key===" "&&b.preventDefault())})})})})});Vp.displayName=ti;var xo="SelectItemText",Kp=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Bn(xo,n),a=zn(xo,n),l=Wp(xo,n),c=fk(xo,n),[d,f]=m.useState(null),h=We(t,g=>f(g),l.onItemTextChange,g=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,g,l.value,l.disabled)}),p=d==null?void 0:d.textContent,v=m.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:x,onNativeOptionRemove:y}=c;return Nt(()=>(x(v),()=>y(v)),[x,y,v]),u.jsxs(u.Fragment,{children:[u.jsx(Se.span,{id:l.textId,...s,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?wo.createPortal(s.children,i.valueNode):null]})});Kp.displayName=xo;var qp="SelectItemIndicator",Gp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return Wp(qp,n).isSelected?u.jsx(Se.span,{"aria-hidden":!0,...r,ref:t}):null});Gp.displayName=qp;var ll="SelectScrollUpButton",Yp=m.forwardRef((e,t)=>{const n=zn(ll,e.__scopeSelect),r=il(ll,e.__scopeSelect),[o,s]=m.useState(!1),i=We(t,r.onScrollButtonChange);return Nt(()=>{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(Jp,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});Yp.displayName=ll;var cl="SelectScrollDownButton",Xp=m.forwardRef((e,t)=>{const n=zn(cl,e.__scopeSelect),r=il(cl,e.__scopeSelect),[o,s]=m.useState(!1),i=We(t,r.onScrollButtonChange);return Nt(()=>{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(Jp,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});Xp.displayName=cl;var Jp=m.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=zn("SelectScrollButton",n),i=m.useRef(null),a=Qs(n),l=m.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return m.useEffect(()=>()=>l(),[l]),Nt(()=>{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(Se.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:he(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:he(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:he(o.onPointerLeave,()=>{l()})})}),Tk="SelectSeparator",Zp=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(Se.div,{"aria-hidden":!0,...r,ref:t})});Zp.displayName=Tk;var ul="SelectArrow",kk=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ei(n),s=Bn(ul,n),i=zn(ul,n);return s.open&&i.position==="popper"?u.jsx(Ru,{...o,...r,ref:t}):null});kk.displayName=ul;var Ek="SelectBubbleInput",Qp=m.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=m.useRef(null),s=We(r,o),i=Ip(t);return m.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(Se.select,{...n,style:{...Np,...n.style},ref:s,defaultValue:t})});Qp.displayName=Ek;function em(e){return e===""||e===void 0}function tm(e){const t=At(e),n=m.useRef(""),r=m.useRef(0),o=m.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=m.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function nm(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=Ik(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 Ik(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Nk=Ap,rm=_p,Ak=Rp,jk=Pp,_k=Op,om=Dp,Mk=Bp,sm=Hp,im=Vp,Rk=Kp,Pk=Gp,am=Yp,lm=Xp,cm=Zp;const um=Nk,dm=Ak,dl=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(rm,{ref:r,className:se("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(jk,{asChild:!0,children:u.jsx(ae.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));dl.displayName=rm.displayName;const fm=m.forwardRef(({className:e,...t},n)=>u.jsx(am,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ae.ChevronUp,{className:"h-4 w-4"})}));fm.displayName=am.displayName;const hm=m.forwardRef(({className:e,...t},n)=>u.jsx(lm,{ref:n,className:se("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(ae.ChevronDown,{className:"h-4 w-4"})}));hm.displayName=lm.displayName;const fl=m.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(_k,{children:u.jsxs(om,{ref:o,className:se("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(fm,{}),u.jsx(Mk,{className:se("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(hm,{})]})}));fl.displayName=om.displayName;const Ok=m.forwardRef(({className:e,...t},n)=>u.jsx(sm,{ref:n,className:se("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Ok.displayName=sm.displayName;const lr=m.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(im,{ref:r,className:se("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(Pk,{children:u.jsx(ae.Check,{className:"h-4 w-4"})})}),u.jsx(Rk,{children:t})]}));lr.displayName=im.displayName;const Dk=m.forwardRef(({className:e,...t},n)=>u.jsx(cm,{ref:n,className:se("-mx-1 my-1 h-px bg-muted",e),...t}));Dk.displayName=cm.displayName;var Lk="Separator",pm="horizontal",$k=["horizontal","vertical"],mm=m.forwardRef((e,t)=>{const{decorative:n,orientation:r=pm,...o}=e,s=Fk(r)?r:pm,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(Se.div,{"data-orientation":s,...a,...o,ref:t})});mm.displayName=Lk;function Fk(e){return $k.includes(e)}var gm=mm;const xm=m.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(gm,{ref:o,decorative:n,orientation:t,className:se("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));xm.displayName=gm.displayName;const Bk=Da,zk=vC,Uk=La,ym=m.forwardRef(({className:e,...t},n)=>u.jsx(io,{className:se("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}));ym.displayName=io.displayName;const Hk=bo.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"}}),vm=m.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(Uk,{children:[u.jsx(ym,{}),u.jsxs(ao,{ref:o,className:se(Hk({side:e}),t),...r,children:[n,u.jsxs(ph,{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(ae.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));vm.displayName=ao.displayName;const bm=({className:e,...t})=>u.jsx("div",{className:se("flex flex-col space-y-2 text-center sm:text-left",e),...t});bm.displayName="SheetHeader";const wm=m.forwardRef(({className:e,...t},n)=>u.jsx(rr,{ref:n,className:se("text-lg font-semibold text-foreground",e),...t}));wm.displayName=rr.displayName;const Sm=m.forwardRef(({className:e,...t},n)=>u.jsx(Ls,{ref:n,className:se("text-sm text-muted-foreground",e),...t}));Sm.displayName=Ls.displayName;var ni="Switch",[Wk,_E]=Tn(ni),[Vk,Kk]=Wk(ni),Cm=m.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,[h,p]=m.useState(null),v=We(t,T=>p(T)),x=m.useRef(!1),y=h?d||!!h.closest("form"):!0,[g,b]=pr({prop:o,defaultProp:s??!1,onChange:c,caller:ni});return u.jsxs(Vk,{scope:n,checked:g,disabled:a,children:[u.jsx(Se.button,{type:"button",role:"switch","aria-checked":g,"aria-required":i,"data-state":Im(g),"data-disabled":a?"":void 0,disabled:a,value:l,...f,ref:v,onClick:he(e.onClick,T=>{b(k=>!k),y&&(x.current=T.isPropagationStopped(),x.current||T.stopPropagation())})}),y&&u.jsx(Em,{control:h,bubbles:!x.current,name:r,value:l,checked:g,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});Cm.displayName=ni;var Tm="SwitchThumb",km=m.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=Kk(Tm,n);return u.jsx(Se.span,{"data-state":Im(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});km.displayName=Tm;var qk="SwitchBubbleInput",Em=m.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=m.useRef(null),a=We(i,s),l=Ip(n),c=bu(t);return m.useEffect(()=>{const d=i.current;if(!d)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(l!==n&&p){const v=new Event("click",{bubbles:r});p.call(d,n),d.dispatchEvent(v)}},[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}})});Em.displayName=qk;function Im(e){return e?"checked":"unchecked"}var Nm=Cm,Gk=km;const Un=m.forwardRef(({className:e,...t},n)=>u.jsx(Nm,{className:se("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(Gk,{className:se("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=Nm.displayName;const Yk={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 Xk({settings:e,onSettingsChange:t,className:n=""}){const[r,o]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(e),[c,d]=w.useState(!1),{toast:f}=Ha();w.useEffect(()=>{const y=JSON.stringify(a)!==JSON.stringify(e);d(y)},[a,e]),w.useEffect(()=>{l(e)},[e]);const h=()=>{t(a),d(!1),f({title:"Settings saved",description:"Your chat configuration has been updated successfully."})},p=()=>{l(Yk),d(!0),f({title:"Settings reset",description:"Configuration has been reset to defaults."})},v=()=>{l(e),d(!1),o(!1)},x=async()=>{try{const g=await(await fetch(`${a.api.baseUrl}/health`)).json();f({title:"Connection successful",description:`API is ${g.status||"healthy"}`})}catch{f({title:"Connection failed",description:"Unable to connect to the API endpoint.",variant:"destructive"})}};return u.jsxs(Bk,{open:r,onOpenChange:o,children:[u.jsx(zk,{asChild:!0,children:u.jsxs(tt,{variant:"outline",size:"sm",className:n,children:[u.jsx(ae.Settings,{className:"h-4 w-4 mr-2"}),"Settings",c&&u.jsx(Kf,{variant:"destructive",className:"ml-2 h-4 w-4 p-0"})]})}),u.jsxs(vm,{className:"w-[500px] sm:w-[600px] overflow-y-auto",children:[u.jsxs(bm,{children:[u.jsx(wm,{children:"Chat Settings"}),u.jsx(Sm,{children:"Configure your chat interface, API connection, and behavior preferences."})]}),u.jsxs("div",{className:"space-y-6 py-6",children:[u.jsxs(uo,{children:[u.jsx(fo,{className:"pb-3",children:u.jsxs(ho,{className:"text-lg flex items-center gap-2",children:[u.jsx(ae.Server,{className:"h-5 w-5"}),"API Configuration"]})}),u.jsxs(po,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"api-url",children:"API Base URL"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Js,{id:"api-url",value:a.api.baseUrl,onChange:y=>l(g=>({...g,api:{...g.api,baseUrl:y.target.value}})),placeholder:"http://localhost:8000/api"}),u.jsx(tt,{variant:"outline",onClick:x,children:"Test"})]})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"enable-auth",children:"Enable Authentication"}),u.jsx(Un,{id:"enable-auth",checked:a.api.enableAuth,onCheckedChange:y=>l(g=>({...g,api:{...g.api,enableAuth:y}}))})]}),a.api.enableAuth&&u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"auth-token",children:"Authentication Token"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Js,{id:"auth-token",type:s?"text":"password",value:a.api.authToken,onChange:y=>l(g=>({...g,api:{...g.api,authToken:y.target.value}})),placeholder:"Enter your Bearer token"}),u.jsx(tt,{variant:"outline",size:"icon",onClick:()=>i(!s),children:s?u.jsx(ae.EyeOff,{className:"h-4 w-4"}):u.jsx(ae.Eye,{className:"h-4 w-4"})})]})]})]})]}),u.jsxs(uo,{children:[u.jsx(fo,{className:"pb-3",children:u.jsxs(ho,{className:"text-lg flex items-center gap-2",children:[u.jsx(ae.Layout,{className:"h-5 w-5"}),"Interface Settings"]})}),u.jsxs(po,{className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"layout",children:"Layout Style"}),u.jsxs(um,{value:a.ui.layout,onValueChange:y=>l(g=>({...g,ui:{...g.ui,layout:y}})),children:[u.jsx(dl,{children:u.jsx(dm,{})}),u.jsxs(fl,{children:[u.jsx(lr,{value:"sidebar",children:"Sidebar Layout"}),u.jsx(lr,{value:"fullscreen",children:"Fullscreen"}),u.jsx(lr,{value:"tabs",children:"Tabbed Interface"})]})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx(rn,{htmlFor:"theme",children:"Theme"}),u.jsxs(um,{value:a.ui.theme,onValueChange:y=>l(g=>({...g,ui:{...g.ui,theme:y}})),children:[u.jsx(dl,{children:u.jsx(dm,{})}),u.jsxs(fl,{children:[u.jsx(lr,{value:"light",children:"Light"}),u.jsx(lr,{value:"dark",children:"Dark"}),u.jsx(lr,{value:"system",children:"System"})]})]})]}),u.jsx(xm,{}),u.jsxs("div",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"show-timestamps",children:"Show Timestamps"}),u.jsx(Un,{id:"show-timestamps",checked:a.ui.showTimestamps,onCheckedChange:y=>l(g=>({...g,ui:{...g.ui,showTimestamps:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"show-agent-names",children:"Show Agent Names"}),u.jsx(Un,{id:"show-agent-names",checked:a.ui.showAgentNames,onCheckedChange:y=>l(g=>({...g,ui:{...g.ui,showAgentNames:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx(rn,{htmlFor:"compact-messages",children:"Compact Messages"}),u.jsx(Un,{id:"compact-messages",checked:a.ui.compactMessages,onCheckedChange:y=>l(g=>({...g,ui:{...g.ui,compactMessages:y}}))})]})]})]})]}),u.jsxs(uo,{children:[u.jsx(fo,{className:"pb-3",children:u.jsxs(ho,{className:"text-lg flex items-center gap-2",children:[u.jsx(ae.MessageCircle,{className:"h-5 w-5"}),"Behavior Settings"]})}),u.jsxs(po,{className:"space-y-4",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(rn,{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(g=>({...g,behavior:{...g.behavior,autoSave:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(rn,{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(g=>({...g,behavior:{...g.behavior,enableStreaming:y}}))})]}),u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx(rn,{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(g=>({...g,behavior:{...g.behavior,showTypingIndicator:y}}))})]})]})]})]}),u.jsxs("div",{className:"flex items-center justify-between pt-6 border-t",children:[u.jsxs(tt,{variant:"outline",onClick:p,children:[u.jsx(ae.RotateCcw,{className:"h-4 w-4 mr-2"}),"Reset"]}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(tt,{variant:"outline",onClick:v,children:"Cancel"}),u.jsxs(tt,{onClick:h,disabled:!c,children:[u.jsx(ae.Save,{className:"h-4 w-4 mr-2"}),"Save Changes"]})]})]})]})]})}function Jk({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=w.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(zo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(Vs,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(zo,{...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(ol,{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(Vs,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(zo,{...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(ol,{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(Vs,{onError:s.onError,enableFileUpload:!0})})]})})}ke.ChatApi=cc,ke.ChatInput=$c,ke.ChatInterface=Vs,ke.ChatProviders=zo,ke.ChatSettings=Xk,ke.MarkdownContent=co,ke.MessageComponent=Ws,ke.MessageList=Ka,ke.ThreadManager=ol,ke.TimelineColumn=JT,ke.applySettings=nk,ke.buildMessagePreviewMap=cx,ke.chatApiClient=Nn,ke.default=Jk,ke.del=bi,ke.get=Wt,ke.getChatToken=ic,ke.getCurrentSettings=tk,ke.getDefaultApiConfig=Sp,ke.getDefaultChatSettings=Cp,ke.onChatTokenChanged=ac,ke.post=Po,ke.put=lc,ke.setChatToken=Ro,ke.useApi=wi,ke.useChatStream=_c,ke.useMessagesReducer=Ac,ke.useStream=Dc,ke.useThreadState=Bo,ke.useThreads=Fo,Object.defineProperties(ke,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teodor-new-chat-ui",
3
- "version": "4.3.379",
3
+ "version": "4.3.381",
4
4
  "description": "React chat UI components with streaming support, tool calls, and modern design",
5
5
  "main": "dist/index.umd.js",
6
6
  "module": "dist/index.esm.js",