react-ai-agent 1.6.5 → 1.6.7
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.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/ui.css +1 -1
- package/package.json +3 -6
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e,{createContext as t,useContext as n,useRef as s,useEffect as r,useState as i,useMemo as o,useCallback as a,createElement as l,memo as c,useLayoutEffect as d,useImperativeHandle as u,forwardRef as h}from"react";import{jsx as g,jsxs as m,Fragment as p}from"react/jsx-runtime";import f from"react-dom";import{Streamdown as x}from"streamdown";import{Prism as v}from"react-syntax-highlighter";import y from"react-markdown";import{motion as w}from"framer-motion";import{useVirtualizer as b}from"@tanstack/react-virtual";class I{constructor(e={}){this.config=e,this.abortController=null}async sendMessage(e,t=null){throw Error("Implement sendMessage()")}async getHistory(e={}){throw Error("Implement getHistory()")}async uploadFiles(e,t){return null}abort(){this.abortController&&(this.abortController.abort(),this.abortController=null)}}class S extends I{constructor(e={}){super({chatUrl:"https://api.oblien.com/ai/chat/send",historyUrl:"https://api.oblien.com/ai/session/history",uploadUrl:"https://api.oblien.com/ai/chat/upload",...e}),this.tokenManager=e.tokenManager||null}async getHeaders(){const e={"Content-Type":"application/json"};return this.tokenManager?e.Authorization="Bearer "+await this.tokenManager.getAccessToken():this.config.token&&(e.Authorization="Bearer "+this.config.token),e}async sendMessage(e,t=null){this.abort(),this.abortController=new AbortController;try{const n=await this.getHeaders();t&&(n.Accept="text/event-stream");const s=await fetch(this.config.chatUrl,{method:"POST",headers:n,body:JSON.stringify(e),signal:this.abortController.signal,credentials:this.config.credentials||"same-origin"});if(!s.ok){const e=await s.json().catch(()=>({error:"Request failed"}));return t&&t(JSON.stringify({event:"stream_error",data:{errorType:"http_error",error:e.error,message:e.message}})),{status:!1,error:e.error}}if(!t)return{status:!0,data:await s.json()};const r=s.body.getReader(),i=new TextDecoder;let o="";for(;;){const{value:e,done:n}=await r.read();if(n){t(JSON.stringify({event:"ai_response_end",data:{status:"end"}}));break}o+=i.decode(e,{stream:!0});const s=o.split("\n");o=s.pop()||"";for(const r of s)r.trim()&&t(r)}return{status:!0}}catch(n){return t&&t(JSON.stringify({event:"stream_error",data:{errorType:"connection_error",error:n.message}})),{status:!1,error:n.message}}}async getHistory(e={}){try{const t=await this.getHeaders(),{offset:n=0,limit:s=20,sessionId:r}=e,i=`${this.config.historyUrl}?offset=${n}&limit=${s}&sessionId=${r}`,o=await fetch(i,{headers:t,credentials:this.config.credentials||"same-origin"});return o.ok?await o.json():{error:"Failed to load history"}}catch(t){return{error:t.message}}}async uploadFiles(e,t){if(!e?.length)return null;const n=new FormData;e.forEach(e=>n.append("files",e.file,e.name));const s={};this.tokenManager?s.Authorization="Bearer "+await this.tokenManager.getAccessToken():this.config.token&&(s.Authorization="Bearer "+this.config.token);const r=await fetch(this.config.uploadUrl,{method:"POST",headers:s,body:n,signal:t,credentials:this.config.credentials||"same-origin"});if(!r.ok)throw Error("Upload failed");return(await r.json()).uploadId}}const k=new class{constructor({socketUrl:e}={}){this.socket=null,this.listeners=new Map,this.bufferedEvents=new Map,this.bufferableEventTypes=new Set([]),this.reconnectAttempts=0,this.maxReconnectAttempts=5e3,this.reconnectTimeout=3e3,this.socketUrl=e,this.requireAppRunning=null}setSocketUrl(e){this.socketUrl=e}_processBinaryData(e){this.notifyListeners("binary",{data:e})}async connect(e,t=[]){return this.socket&&this.disconnect(),e||(e=await getToken()),new Promise(async(n,s)=>{try{const s=new URL(this.socketUrl+"?token="+e+"&"+t.join("&"));this.socket=new WebSocket(s),this.socket.onopen=()=>{this.reconnectAttempts=0,this.reconnectTimeout=3e3,this.notifyListeners("connect",{connected:!0}),n(!0)},this.socket.onmessage=async e=>{try{if(e.data instanceof Blob){const t=new FileReader;return t.onload=()=>{this._processBinaryData(t.result)},void t.readAsArrayBuffer(e.data)}if(e.data instanceof ArrayBuffer)return void this._processBinaryData(e.data);if("string"==typeof e.data){const t=JSON.parse(e.data);if(this._checkPendingRequests(t))return;return this.notifyListeners("message",t),this.requireAppRunning?.events.includes(t.type)&&!this.listeners.has(t?.type)&&t?.type&&this.requireAppRunning&&"running"!==this.requireAppRunning?.status&&await this.requireAppRunning.callback(t),void(t.type&&this.notifyListeners(t.type,t))}}catch(t){}},this.socket.onclose=n=>{this.notifyListeners("disconnect",{code:n.code,reason:n.reason}),1e3!==n.code&&this.attemptReconnect(e,t)},this.socket.onerror=e=>{this.notifyListeners("error",e)}}catch(r){}})}disconnect(){this.socket&&(this.notifyListeners("close",{code:1e3,reason:"User disconnected"}),this.socket.close(1e3,"User disconnected"),this.socket=null)}attemptReconnect(e,t){this.maxReconnectAttempts>this.reconnectAttempts&&this.socket?(this.reconnectAttempts++,this.notifyListeners("reconnectAttempt",{attempts:this.reconnectAttempts}),setTimeout(()=>{this.connect(e,t)},this.reconnectTimeout)):this.notifyListeners("reconnectFailed",{attempts:this.reconnectAttempts})}isConnected(){return this.socket&&this.socket.readyState===WebSocket.OPEN}sendAsync(e,t=3e4){return new Promise((n,s)=>{if(!this.isConnected())return s(Error("WebSocket is not connected"));const r=e.requestId||`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i={...e,requestId:r};this.pendingRequests||(this.pendingRequests=new Map),this.pendingRequests.set(r,{resolve:n,reject:s,timeoutId:setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),s(Error(`Request ${r} timed out after ${t}ms`)))},t)}),this.send(i)})}_checkPendingRequests(e){if(!this.pendingRequests||!e.requestId)return!1;const t=this.pendingRequests.get(e.requestId);return!!t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e),!0)}send(e){return!!this.isConnected()&&(this.socket.send(JSON.stringify(e)),!0)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),this.bufferedEvents.has(e)&&(this.bufferedEvents.get(e).forEach(e=>{try{t(e)}catch(n){}}),this.bufferedEvents.delete(e)),()=>this.off(e,t)}off(e,t){if(!this.listeners.has(e))return;const n=this.listeners.get(e),s=n.indexOf(t);-1!==s&&n.splice(s,1),0===n.length&&this.listeners.delete(e)}notifyListeners(e,t){const n=this.listeners.has(e);if(!n&&this.bufferableEventTypes.has(e))return this.bufferedEvents.has(e)||this.bufferedEvents.set(e,[]),void this.bufferedEvents.get(e).push(t);n&&this.listeners.get(e).forEach(e=>{try{e(t)}catch(n){}})}setAppServerStatus(e){this.requireAppRunning.status=e}setRequireAppRunning(e,t,n){return this.requireAppRunning={events:e,callback:t,status:n},()=>{this.requireAppRunning=null}}};class C{constructor(){this.buffer=""}feed(e){if(!e)return[];const t=this._tryDirectJson(e);if(t.length)return t;const n=this._tryDirectSSE(e);return n.length?n:(this.buffer+=e,this._fallbackExtract())}_tryDirectJson(e){const t=[];try{const n=JSON.parse(e);return n&&"object"==typeof n&&t.push(n),t}catch{}return e.includes("{")&&e.includes("}")?this._fallbackExtractFromText(e):[]}_tryDirectSSE(e){const t=[];for(let n of e.split("\n")){if(n=n.trim(),!n.startsWith("data:"))continue;const e=n.slice(5).trim();try{const n=JSON.parse(e);n&&"object"==typeof n&&t.push(n)}catch{}}return t}_fallbackExtract(){const e=this._fallbackExtractFromText(this.buffer);for(const t of e){const e=JSON.stringify(t),n=this.buffer.indexOf(e);-1!==n&&(this.buffer=this.buffer.slice(0,n)+this.buffer.slice(n+e.length))}return e}_fallbackExtractFromText(e){const t=[];let n=-1,s=0,r=!1,i=!1;for(let o=0;e.length>o;o++){const a=e[o];if(i)i=!1;else if("\\"===a)i=!0;else if('"'===a)r=!r;else if(!r)if("{"===a)0===s&&(n=o),s++;else if("}"===a&&(s--,0===s&&-1!==n)){const s=e.slice(n,o+1);try{const e=JSON.parse(s);t.push(e)}catch{}n=-1}}return t}}class T{constructor(){this.jsonStreamParser=new C}parseJsonStream(e){return this.jsonStreamParser.feed(e)}processRawChunk(e,t){try{const n=this.parseJsonStream(e);if(!n.length)return;for(const e of n){let n,s=e.event||"response";n=e.type&&("started"===e.type||"finished"===e.type||"status"===e.type||e.taskId)?e:e.data||e,"ai_response"===s?s="response":"ai_response_end"===s&&(s="response_end"),t(s,n)}}catch(n){}}}class M{constructor(e){this.chatApi=e,this.streamProcessor=new T,this.eventHandlers=new Map,this.mode=null}setMode(e="sse",t=null){this.mode=e}on(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),()=>{const n=this.eventHandlers.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}}off(e,t){const n=this.eventHandlers.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}emit(e,t){const n=this.eventHandlers.get(e);n&&n.forEach(e=>{try{e(t)}catch(n){}})}abort(){}send(e){"websocket"===this.mode&&k&&k.send(e)}startStream(e,t,n){return this.chatApi.sendMessage(e,e=>{if(t&&n)try{t(e)}catch(s){}this.streamProcessor.processRawChunk(e,(r,i)=>{if(t&&!n)try{t(e)}catch(s){}this.emit(r,i)})})}clear(){this.eventHandlers.clear()}}class z{constructor(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.refreshCallback=null,this.sessionId=null}decodeJWT(e){try{const t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),n=decodeURIComponent(atob(t).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(n)}catch(t){return null}}isTokenExpired(e,t=30){if(!e)return!0;const n=this.decodeJWT(e);if(!n||!n.exp)return!0;const s=1e3*n.exp;return Date.now()>=s-1e3*t}setRefreshCallback(e){this.refreshCallback=e}async setAuth({accessToken:e,refreshToken:t,expiresIn:n,sessionId:s}){this.accessToken=e,this.refreshToken=t,this.sessionId=s;const r=this.decodeJWT(e);r&&r.exp?(this.tokenExpiry=1e3*r.exp,this.tokenExpiry<Date.now()+3e4&&await this.refreshTokens()):n&&(this.tokenExpiry=Date.now()+1e3*n)}async getAccessToken(){if(!this.accessToken)throw Error("No access token available. Initialize tokens first.");return this.isTokenExpired(this.accessToken,30)&&await this.refreshTokens(),this.accessToken}getSessionId(){return this.sessionId}async refreshTokens(){if(!this.refreshCallback)throw Error("No refresh callback provided");if(!this.refreshToken)throw Error("No refresh token available");try{const e=await this.refreshCallback(this.refreshToken);if(!e||!e.accessToken)throw Error("Invalid refresh response");return this.setAuth({accessToken:e.accessToken,refreshToken:e.refreshToken||this.refreshToken,expiresIn:e.expiresIn,sessionId:e.sessionId||this.sessionId}),this.accessToken}catch(e){throw this.clear(),e}}hasTokens(){return!!this.accessToken}clear(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.sessionId=null}}class H{constructor(){this.messages=[],this.messageIndex=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}_notify(){this.listeners.forEach(e=>e([...this.messages]))}_rebuildIndex(){this.messageIndex.clear(),this.messages.forEach((e,t)=>{this.messageIndex.set(e.messageId,t)})}addMessage(e){const t={...e,messageId:e.messageId||this._generateId(),timestamp:e.timestamp||Date.now(),uniqueKey:`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`};return this.messages.push(t),this.messageIndex.set(t.messageId,this.messages.length-1),this._notify(),t}updateMessage(e,t,n={}){const s=this.messageIndex.get(e);if(void 0===s)return null;const r=this.messages[s],i={};if(Object.entries(t).forEach(([e,t])=>{i[e]="function"==typeof t?t(r[e]):t}),n.silent)return Object.assign(this.messages[s],i),this.messages[s];const o=i.hasOwnProperty("isLive")||i.hasOwnProperty("isFinished")||i.hasOwnProperty("isThinkingFinished")||i.hasOwnProperty("statusType")||i.hasOwnProperty("sender")||i.hasOwnProperty("type")||i.hasOwnProperty("text");return this.messages[s]={...r,...i,...o&&{uniqueKey:`msg-${e}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}},this._notify(),this.messages[s]}insertMessage(e,t="end"){const n={...e,messageId:e.messageId||this._generateId(),timestamp:e.timestamp||Date.now(),uniqueKey:`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`};return"start"===t||0===t?this.messages.unshift(n):"end"!==t&&this.messages.length>t?this.messages.splice(t,0,n):this.messages.push(n),this._rebuildIndex(),this._notify(),n}insertMessages(e,t="end"){const n=e.map(e=>({...e,messageId:e.messageId||this._generateId(),timestamp:e.timestamp||Date.now(),uniqueKey:e.uniqueKey||`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,isLive:!1,isFinished:!0,text:e.content||e.text||""}));return"start"===t||0===t?this.messages.unshift(...n):"end"!==t&&this.messages.length>t?this.messages.splice(t,0,...n):this.messages.push(...n),this._rebuildIndex(),this._notify(),n}removeMessage(e){const t=this.messageIndex.get(e);return void 0!==t&&(this.messages.splice(t,1),this._rebuildIndex(),this._notify(),!0)}getMessage(e){const t=this.messageIndex.get(e);return void 0!==t?this.messages[t]:null}hasMessage(e){return this.messageIndex.has(e)}getAllMessages(){return[...this.messages]}clear(){this.messages=[],this.messageIndex.clear(),this._notify()}setMessages(e){this.messages=e.map(e=>({...e,uniqueKey:e.uniqueKey||`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`})),this._rebuildIndex(),this._notify()}_generateId(){return`msg-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}get count(){return this.messages.length}}class R{constructor(e,t){this.messageManager=e,this.statusRegistry=t,this.activeStreamingMessages=new Map}handleUserMessage({messageId:e,text:t,attachedFiles:n=[],...s}){return this.messageManager.addMessage({messageId:e||this.messageManager._generateId("user"),sender:"user",type:"user",text:t,attachedFiles:n,...s})}incrementChunkIndex(e){const t=this._getState(e);return t.chunkIndex+=1,t.chunkIndex}markTypeProcessed(e,t){this._getState(e).lastProcessedType=t}shouldFinishThinking(e){const t=this._getState(e);return t.hasChunk&&t.hasThinking&&!t.thinkingFinished}markThinkingFinished(e){const t=this._getState(e),n=e+"-thinking";t.thinkingFinished=!0,t.hasChunk=!0,t.hasThinking&&this.messageManager.hasMessage(n)&&this.messageManager.updateMessage(n,{isLive:!1,isThinkingFinished:!0})}}class N{constructor(){this.handlers=new Map,this.globalHandlers=[],this.streamForwarders=new Map}register(e,t,n={}){this.handlers.has(e)||this.handlers.set(e,[]);const s={handler:t,filter:n};return this.handlers.get(e).push(s),()=>{const t=this.handlers.get(e);if(t){const e=t.indexOf(s);e>-1&&t.splice(e,1)}}}registerGlobal(e,t={}){const n={handler:e,filter:t};return this.globalHandlers.push(n),()=>{const e=this.globalHandlers.indexOf(n);e>-1&&this.globalHandlers.splice(e,1)}}_matchesFilter(e,t){return!t.instanceId||e.instanceId===t.instanceId}async handle(e){const{status:t,messageId:n}=e,s=t?.type||e.type;await Promise.all(this.globalHandlers.filter(t=>this._matchesFilter(e,t.filter)).map(t=>Promise.resolve(t.handler(e)).catch(e=>{})));const r=this.handlers.get(s)||[];await Promise.all(r.filter(t=>this._matchesFilter(e,t.filter)).map(t=>Promise.resolve(t.handler(e)).catch(e=>{}))),"started"===t?.state||"in_progress"===t?.state?this._startStreamForwarding(n,s,e):"finished"!==t?.state&&"error"!==t?.state||this._stopStreamForwarding(n,s,e)}registerStreamForwarder(e){const t=Math.random().toString(36).substring(2,9);return this.streamForwarders.set(t,{forwarder:e,active:!1,messageId:null}),{id:t,stop:()=>this.streamForwarders.delete(t)}}forwardStream(e,t){this.streamForwarders.forEach(n=>{if(n.active&&n.messageId===e)try{"chunk"===t.type&&n.forwarder({...t,statusType:n.statusType})}catch(s){}})}_startStreamForwarding(e,t,n){this.streamForwarders.forEach(s=>{s.active=!0,s.messageId=e,s.statusType=t,s.forwarder.onStart&&s.forwarder.onStart({...n,statusType:t})})}_stopStreamForwarding(e,t,n){this.streamForwarders.forEach(s=>{s.messageId===e&&(s.active=!1,s.statusType=null,s.forwarder.onEnd&&s.forwarder.onEnd({...n,statusType:t}))})}clear(){this.handlers.clear(),this.globalHandlers=[],this.streamForwarders.clear()}}const E=new N;function A(){return E}const F={current:{}},O=new Map;class B{constructor(e){this.messageId=e,this.fullText="",this.displayIndex=0,this.previousDisplayIndex=0,this.isTyping=!1,this.isComplete=!1,this.isCleanedUp=!1,this.intervalId=null,this.mode=F.current.mode,this.speed=F.current.speed,this.batchSize=F.current.batchSize,this.listeners=new Set}setFullText(e,t){this.fullText+=e||"",!this.isTyping&&this.fullText.length>0&&this.startTyping(),t||!1!==this.isComplete||(this.isComplete=!0)}waitForAnimation(){return new Promise(e=>{if(this.displayIndex>=this.fullText.length)return void e();const t=setInterval(()=>{this.fullText.length>this.displayIndex||(clearInterval(t),e())},50)})}startTyping(){this.isTyping||(this.isTyping=!0,this.intervalId=setInterval(()=>{if(this.fullText.length>this.displayIndex){const e=this.getNextIncrement();this.previousDisplayIndex=this.displayIndex,this.displayIndex=Math.min(this.displayIndex+e,this.fullText.length),this.notifyListeners()}else this.isComplete&&(this.stopTyping(),this.onComplete&&(this.onComplete(),this.onComplete=null))},1e3/this.speed))}getNextIncrement(){switch(this.mode){case"char":case"chars":default:return 1;case"word":case"words":{let e=this.displayIndex+1;for(;this.fullText.length>e;){const t=this.fullText[e];if(" "===t||"\n"===t||/[.,!?;:]/.test(t))return e-this.displayIndex+1;e++}return this.fullText.length-this.displayIndex}case"batch":case"batches":return this.batchSize}}stopTyping(){this.isTyping=!1,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}subscribe(e,t={}){const n={callback:e,newOnly:t.newOnly||!1};return this.listeners.add(n),()=>this.listeners.delete(n)}notifyListeners(){const e=this.fullText.slice(this.previousDisplayIndex,this.displayIndex),t=this.fullText.slice(0,this.displayIndex);this.listeners.forEach(n=>{n.callback(n.newOnly?e:t)})}cleanup(){this.isCleanedUp||(this.isCleanedUp=!0,this.stopTyping(),this.listeners.clear(),O.delete(this.messageId))}}function L(e){return O.get(e)}class _{constructor(){}async processChunk(e,t=null,n,s){const r=e.messageId,i=function(e){if(O.has(e))return O.get(e);const t=new B(e);return O.set(e,t),t}(e.messageId);if(i.setFullText(e.text||"",e.isLive),n){const n=e.from&&this.forwardingManager?.handlers[e.from],s=t&&this.forwardingManager?this.forwardingManager.getSession(t):null,i=n&&s&&e.from===s?.action;e.from&&!n&&this.forwardingManager&&(this._warnedActions||(this._warnedActions=new Set),this._warnedActions.has(e.from)||this._warnedActions.add(e.from));const o=n?this.forwardingManager.handlers[e.from]:null,a=e.from&&"replace"===(o?.mode||"replace");if(i){const n=this.forwardingManager.isAnimated(t),s=this.forwardingManager.getSubscriptionMode(t);if(n){const n=L(r);n.hasForwarder||(n.hasForwarder=!0,n.subscribe(n=>{this.forwardingManager.forwardChunk(t,n,e.isLive)},{newOnly:"delta"===s}),n.onComplete=()=>{this.forwardingManager.cleanupSession(t)})}else this.forwardingManager.forwardChunk(t,e.text||"",e.isLive)}if(a)return}this.messageHandlers.messageManager.hasMessage(r)?this.messageHandlers.messageManager.updateMessage(r,{text:t=>t+(e.text||"")},{silent:!0}):this.messageHandlers.messageManager.addMessage({messageId:r,sender:"ai",type:"chunk",text:e.text||"",isLive:!0,tokens:e.tokens}),await i.waitForAnimation()}async processHolding(e){}async processThinking(e){const t=e.messageId+"-thinking";this.messageHandlers.messageManager.hasMessage(t)?this.messageHandlers.messageManager.updateMessage(t,{text:t=>t+(e.text||"")}):this.messageHandlers.messageManager.addMessage({messageId:t,sender:"ai",type:"thinking",text:e.text||"",isLive:!0,timestamp:Date.now()})}async finishThinking(e){const t=e.messageId+"-thinking",n=this.messageHandlers.messageManager.getMessage(t);if(n){const e=Date.now();this.messageHandlers.messageManager.updateMessage(t,{isLive:!1,finalized:!0,duration:parseFloat(((e-(n.timestamp||e))/1e3).toFixed(1)),endTimestamp:e})}}async finishChunk(e){const t=e.messageId,n=this.messageHandlers.messageManager.getMessage(t);n&&this.messageHandlers.messageManager.updateMessage(t,{isLive:!1,finalized:!0,text:n.text||""})}async processStatus(e,t=null){const n=e.taskId||e.messageId;if(!n)return;if(this.messageHandlers.statusRegistry)try{await this.messageHandlers.statusRegistry.handle({...e,messageId:n,instanceId:t,status:{type:e.action||e.type,state:"started"===e.type?"started":"finished"===e.type?"finished":"in_progress",data:e.data}})}catch(r){}const s=this.messageHandlers.messageManager.hasMessage(n);"started"!==e.type&&"status"!==e.type?"finished"!==e.type?s?this.messageHandlers.messageManager.updateMessage(n,{statusType:e.type,data:e.data,metadata:e.metadata,isFinished:e.type.includes("end")||"finished"===e.type}):this.messageHandlers.messageManager.addMessage({messageId:n,sender:"ai",type:"status",action:e.action,statusType:e.type,data:e.data,metadata:e.metadata,isFinished:e.type.includes("end")||"finished"===e.type,isFlat:!0}):s&&this.messageHandlers.messageManager.updateMessage(n,{statusType:e.type,isFinished:!0}):s||this.messageHandlers.messageManager.addMessage({messageId:n,sender:"ai",type:"status",action:e.action,statusType:e.type,data:e.data,metadata:e.metadata,isFinished:!1,isFlat:!0})}}class D extends _{constructor(e,t,n,s=null){super(),this.messageHandlers=e,this.forwardingManager=t,this.queue=[],this.queueHistory=[],this.isProcessing=!1,this.lastMessageId=null,this.useForwarding=n,this.currentForwardingSession=null,this.onQueueComplete=null,this.instanceId=s}async process(){this.isProcessing=!0;const e=[...this.queue];this.queueHistory.push(...e),this.queue=[];for(let t=0;e.length>t;t++){const n=e[t],s=this.queueHistory.findIndex(e=>(e.messageId||e.taskId)==(n.messageId||n.taskId)),r=this.queueHistory[s-1];r&&!r.finalized&&(r.finalized=!0,await this.notifyPreviousItem(r)),await this.processItem(n)}this.isProcessing=!1,this.queue.length>0?this.process():(this.finalize(),this.onQueueComplete&&this.onQueueComplete())}filterData(e){return e}async addToQueue(e){const t=this.filterData(e);this.queue.push(t),this.isProcessing||this.process()}async notifyPreviousItem(e){"thinking"===e.type?await this.finishThinking(e):"chunk"===e.type&&await this.finishChunk(e)}async processItem(e){const{type:t}=e;e.messageId&&(this.lastMessageId=e.messageId);const n=e.action||e.data?.action,s=e.taskId||e.messageId;switch(this.forwardingManager&&this.useForwarding&&("started"===t&&n&&this.forwardingManager.startSession(s,n,this.instanceId)&&(this.currentForwardingSession=s),"finished"===t&&this.currentForwardingSession&&(this.forwardingManager.endSession(this.currentForwardingSession),this.currentForwardingSession=null),"end"===t&&this.currentForwardingSession&&(this.forwardingManager.endSession(this.currentForwardingSession),this.currentForwardingSession=null)),t){case"thinking":await this.processThinking(e);break;case"holding":await this.processHolding(e);break;case"chunk":await this.processChunk(e,this.currentForwardingSession,this.useForwarding,this.forwardingManager.newOnly);break;case"started":case"finished":case"status":case"status_start":case"status_end":case"status_error":case"error":case"action":await this.processStatus(e,this.instanceId);break;case"end":await this.finalize(e)}}async clear(){this.queue=[],this.isProcessing=!1,O.forEach(e=>{e.stopTyping(),e.cleanup()}),this.currentForwardingSession&&this.forwardingManager&&(this.forwardingManager.endSession(this.currentForwardingSession),this.currentForwardingSession=null),this.onQueueComplete&&this.onQueueComplete()}async endResponse(){this.queueHistory=[]}async finalize(e){this.lastMessageId&&await this.finishChunk({messageId:this.lastMessageId}),this.isProcessing=!1,this.queue=[]}}let P=null;class W{constructor(e={}){this.initialHandlers={...e},this.dynamicHandlers={},this.handlers={...e},this.activeSessions=new Map}register(e,t,n={}){const s=n.instanceId?`${e}:${n.instanceId}`:e;return this.dynamicHandlers[s]={handler:t,mode:n.mode||"dual",animated:!1!==n.animated,subscriptionMode:n.subscriptionMode||"delta",instanceId:n.instanceId},this._rebuildHandlers(),()=>{delete this.dynamicHandlers[s],this._rebuildHandlers()}}_rebuildHandlers(){this.handlers={...this.initialHandlers},Object.assign(this.handlers,this.dynamicHandlers)}startSession(e,t,n=null){const s=n?`${t}:${n}`:null,r=s&&this.handlers[s]||this.handlers[t];return!(!r||r.instanceId&&r.instanceId!==n||(this.activeSessions.get(e)||this.activeSessions.set(e,{action:t,handler:r.handler,mode:r.mode,animated:r.animated,subscriptionMode:r.subscriptionMode,instanceId:r.instanceId,lastText:"",fullText:"",streamEnded:!1}),0))}endSession(e){const t=this.activeSessions.get(e);t&&(t.streamEnded=!0,t.animated||this.cleanupSession(e))}cleanupSession(e){const t=this.activeSessions.get(e);if(t){if(t.handler&&t.fullText)try{t.handler(null,t.fullText,{action:t.action,event:"end",isLive:!1})}catch(n){}this.activeSessions.delete(e)}}isActive(e){return this.activeSessions.has(e)}getSession(e){return this.activeSessions.get(e)}forwardChunk(e,t,n=!0){const s=this.activeSessions.get(e);if(!s)return!1;const r=t||"";if(0===r.length&&n)return!0;let i,o;"full"===s.subscriptionMode?(o=r,i=r):(s.fullText+=r,i=r,o=s.fullText);try{s.handler(i,o,{action:s.action,isLive:!s.streamEnded&&n,event:"chunk",subscriptionMode:s.subscriptionMode})}catch(a){}return!0}shouldReplace(e){const t=this.activeSessions.get(e);return t&&"replace"===t.mode}isAnimated(e){const t=this.activeSessions.get(e);return t&&t.animated}getSubscriptionMode(e){const t=this.activeSessions.get(e);return t?t.subscriptionMode:"delta"}getActiveSessions(){return Array.from(this.activeSessions.keys())}clearAll(){this.activeSessions.clear()}}function q(e){return P?e&&Object.keys(e).length>0&&(P.initialHandlers={...e},P._rebuildHandlers()):P=new W(e),P}function j(e){P=e}function U(){P=null}const V=t(null);function $(e,t,i={}){const o=n(V),a=void 0!==i.instanceId?i.instanceId:o,l=a?{instanceId:a}:{},c=A(),d=s(t);r(()=>{d.current=t},[t]),r(()=>{const t=[];if("object"==typeof e&&null!==e)Object.entries(e).forEach(([e,n])=>{if("*"===e){const e=c.registerGlobal(n,l);t.push(e)}else{const s=c.register(e,n,l);t.push(s)}});else if("string"==typeof e){const n=e=>d.current?.(e);if("*"===e){const e=c.registerGlobal(n,l);t.push(e)}else{const s=c.register(e,n,l);t.push(s)}}return()=>{t.forEach(e=>e?.())}},[e,a])}const G=t({}),K=()=>n(G);let J={},Y=null;const Q=()=>Y;function X({children:t,initialWelcome:n={title:"Welcome to AI Chat Agent",description:"A perfect agent library for your needs, for docs visit oblien.com/docs/chat-agent"},refreshTokenCallback:l,markdownComponents:c,typingAnimation:d={mode:"chars",speed:400},statusComponents:u,forwardingHandlers:h={},authConfig:g,enableHistory:m=!0,loadingComponent:p,allowThinking:f=!0,headerComponent:x,config:v,apiHandler:y,agentId:w,className:b="h-full w-full",onError:I}){const k=s(w||"chat-"+Math.random().toString(36).substring(2,9)).current,[C,T]=i(!0),[N,E]=i(g?.sessionId),[O,B]=i(!1),[L,_]=i(!1),[P,W]=i(!1),[j,U]=i(null),[$,K]=i(null),[Q,X]=i(!1),[Z,ee]=i(!1),[te,ne]=i(null),se=s(n).current,[re,ie]=i([]),oe=s(!1),ae=s(!1),le=s(new H),ce=s(null),de=o(()=>A(),[]),ue=s(l?new z:null),he=s(y||new S({...v,...ue.current&&{tokenManager:ue.current},token:g?.accessToken,sessionId:g?.sessionId})),ge=s(new M(he.current)),me=s(q(h)),pe=s(new R(le.current,de)),fe=s(new D(pe.current,me.current,Object.keys(h).length>0,k)),xe=a(()=>{const e=oe.current||ae.current;_(e),e||B(!1)},[]);r(()=>{fe.current.onQueueComplete=()=>{ae.current=!1,xe();const e=me.current.handlers._loading_end;if(e?.handler)try{e.handler({messageId:ce.current||null,instanceId:k,timestamp:Date.now()})}catch(t){}}},[xe,k]);const ve=s(c).current;r(()=>{Y=ve},[ve]);const ye=s(p),we=s(u),be=s(x);r(()=>{var e;p!==ye.current&&(ye.current=p),u!==we.current&&(we.current=u,e=u||{},J={...e}),x!==be.current&&(be.current=x),l&&ue.current&&ue.current.setRefreshCallback(l)},[p,u,x,l]);const Ie=s(!1),Se=s(N),ke=s(null);F.current=d;const Ce=s(new Set);r(()=>{const e=le.current.subscribe(e=>{ie(e)});return()=>{e()}},[]),r(()=>{Se.current=N},[N]);const Te=s(!1);r(()=>{(async()=>{if(g&&g.sessionId&&ue.current)try{await ue.current.setAuth(g)}catch(j){let t="Authentication failed. Please refresh the page.";j?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":j?.message&&(t=j.message),U({type:"auth_error",message:t,error:j}),T(!1)}else m||T(!1)})()},[!1,g,m]);const Me=a(e=>{U(e.error)},[]),ze=a(async()=>{if(m)try{if(Ce.current.has(N))return void T(!1);Ce.current.add(N),T(!0);const e=await he.current.getHistory();if(e.error)return Me(e),void T(!1);e.history&&e.history.length>0&&le.current.insertMessages(e.history,"end"),ee(!!e.has_more),T(!1)}catch(e){let t="Could not load message history.";e?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":e?.message?.includes("Network")?t="Network error. Please check your connection.":e?.message&&(t=e.message),U({type:"history_error",message:t,error:e}),T(!1)}else T(!1)},[N,Me,m]);r(()=>{(async()=>{N&&!Te.current?(Te.current=!0,await ze()):N||Te.current||(Te.current=!0,m?await ze():T(!1))})()},[N,ze,m]);const He=a(()=>(oe.current=!1,ae.current=!1,_(!1),B(!1),W(!1),fe.current.clear(),ce.current=null,he.current.abort(),ge.current.abort()),[]),Re=a(e=>{const t={...e,id:e?.id||Math.random().toString(36).substring(2,9),timestamp:Date.now(),instanceId:k};K(t),I&&I(t);const n=me.current.handlers._error;if(n?.handler)try{n.handler(t)}catch(s){}},[I,k]),Ne=a(()=>{K(null)},[]),Ee=a(()=>{oe.current=!1;const e=ce.current;if(e){fe.current.endResponse(),ce.current=null;const n=me.current.handlers._response_end;if(n?.handler)try{n.handler({messageId:e,instanceId:k,timestamp:Date.now()})}catch(t){}}xe()},[xe,k]),Ae=a(()=>{Ie.current=!1,oe.current=!1,xe()},[xe]),Fe=a(e=>{const t=e?.data?.messageId||e?.messageId;if(t&&(ce.current=t),!P){W(!0);const e=me.current.handlers._response_start;if(e?.handler)try{e.handler({messageId:t,instanceId:k,timestamp:Date.now()})}catch(n){}}ae.current=!0,fe.current.addToQueue(e),xe()},[P,xe,k]);r(()=>(ge.current.on("stream_error",Re),ge.current.on("response",Fe),ge.current.on("response_end",Ee),ge.current.on("disconnect",Ae),()=>{ge.current.off("stream_error",Re),ge.current.off("response",Fe),ge.current.off("response_end",Ee),ge.current.off("disconnect",Ae)}),[Re,Fe,Ee,Ae]);const Oe=async({messageId:e=Math.random().toString(36).substring(2,9),message:t="",attachedFiles:n=[],uploadId:s=null}={})=>{if(!t.trim())return;const r="user-"+e;try{ke.current&&ke.current?.messageId===r||pe.current.handleUserMessage({messageId:r,text:t,attachedFiles:n}),ke.current={messageId:r,message:t,attachedFiles:n,uploadId:s},B(!0),W(!1),oe.current=!0,xe();const e=me.current.handlers._stream_feedback,i=e?.handler,o="raw"===e?.mode,a=await ge.current.startStream({message:t,attachedFiles:n,uploadId:s,sessionId:Se.current,context:null,allowThinking:f},i,o);a.status||(oe.current=!1,xe(),Re({errorType:"connection_error",error:a.error||"Error occurred while connecting to server",message:a.message||"Failed to send message"}))}catch(i){oe.current=!1,xe(),Re({errorType:"send_error",error:i.message||"Unknown error",message:"Failed to send message"})}finally{B(!1)}},Be=a(async()=>{ke.current&&await Oe(ke.current)},[]),Le=o(()=>({addMessage:e=>le.current.addMessage(e),updateMessage:(e,t)=>le.current.updateMessage(e,t),removeMessage:e=>le.current.removeMessage(e),getMessage:e=>le.current.getMessage(e),clear:()=>le.current.clear()}),[]),_e=o(()=>({register:(e,t)=>de.register(e,t,{instanceId:k}),registerGlobal:e=>de.registerGlobal(e,{instanceId:k})}),[k,de]);return e.createElement("div",{className:"react-ai-agent-root "+b},e.createElement(G.Provider,{value:{sendMsg:Oe,messages:re,messageManager:Le,isLoading:O,isStreaming:L,isResponseStarted:P,isInitialLoading:C,isLoadingMore:Q,error:j,streamError:$,clearStreamError:Ne,getHistory:ze,loadMoreMessages:async()=>{if(m&&!Q&&Z){X(!0);try{const e=le.current.count,t=await he.current.getHistory({offset:e,limit:20});if(t.error)return Me(t),void X(!1);t.history&&t.history.length>0?(le.current.insertMessages(t.history,"start"),ee(t.has_more)):ee(!1)}catch(e){U({type:"load_more_error",message:"Failed to load more messages",error:e})}finally{X(!1)}}},hasMoreMessages:Z,enableHistory:m,retryLastMessage:Be,abort:He,sessionId:N,setSessionId:E,instanceId:k,currentSelectedFile:te,setCurrentSelectedFile:ne,welcome:se,statusRegistry:_e,markdownComponents:ve,statusComponents:we.current,loadingComponent:ye.current,headerComponent:be.current,typingAnimation:d}},e.createElement(V.Provider,{value:k},t)))}const Z={send:"/arrow up md-61-1696832363.png",attach:"/attach-1-1662364367.png",public:"/world-229-1658433759.png",arrowDown:"/chevron down-4-1696832126.png",close:"/close remove-802-1662363936.png",add:"/plus 4-12-1662493809.png",logs:"/website terminal-62-1658431404.png",terminal:"/terminal-184-1658431404.png",minimize:"/chevron down-4-1696832126.png",removeBold:"/delete-29-1661490994.png",info:"/info menu-42-1661490994.png",leftSidebar:"/grid interface-166-1658433281.png",file:"/document-180-1658431575.png",folder:"/folder file-32-1661323044.png",tick:"/check circle-3-1660219236.png",square:"/square-38-1666783764.png",search:"/search-123-1658435124.png",check:"/checkmark-7-1660219236.png",lock:"/lock-62-1691989601.png",discord:"/discord-141-1693375491.png",twitter:"/x.com-179-1693375584.png",refresh:"/refresh right-64-1696832204.png",back:"/arrow right md-49-1696832059.png",home:"/home-123-1658433759.png",forward:"/arrow left md-33-1696832059.png",newTab:"/new tab-123-1658433759.png",devTools:"/developer tools-123-1658433759.png",externalLink:"/External_link_HtLszLDBXqHilHK674zh2aKoSL7xUhyboAzP.png",deploy:"/space rocket-88-1687505465.png",projects:"/git fork-163-1658431404.png",settings:"/setting-100-1658432731.png",logout:"/Logout_q9Ri9V6YI29BipbKthCSXYDM0WoxMC05JTYO.png",notfound:"/search not found-92-1666688362.png",chatai:"/chat intelligence-6-1686046192.png",credit:"/bank card-91-1658234909.png",question:"/question mark circle-29-1662452248.png",blank:"/code-15-1658431404.png",react:"/react-native-29-1693375583.png",nextjs:"/next js circle-172-1693375539.png",vue:"/vue-160-1693375217.png",angular:"/angular-62-1693375491.png",node:"/npm-183-1693375539.png",python:"/python-122-1662819152.png",mobile:"/iphone-36-1658434492.png",laravel:"/laravel-108-1693375539.png",php:"/php-7-1693375216.png",url:"/link-68-1692683696.png",grid:"/gallery view-155-1658433281.png",list:"/bulleted list-15-1692683663.png",download:"/Download_61W5ztaZuYZoYEY7utQW7FU1y4lMiUO2rHjg.png",upload:"/upload-123-1658433759.png",starfilled:"/star-31-1660810259.png",edit:"/pen-304-1658238246.png",globe:"/earth-30-1687505545.png",minus:"/minus 4-9-1660810450.png",switch:"/changing-330-1658238246.png",history:"/counter clockwise undo-46-1658435834.png",golang:"/Go_Logo_Blue.svg.png",github:"/github-8-1693375538.png",pull:"/git pull-170-1658431404.png",sync:"/update left-39-1696832255.png",error:"/error triangle-16-1662499385.png",reload:"/flash refresh-94-1658434699.png",filter:"/filter-25-1662364403.png",sets:"/setting-41-1662364403.png",read:"/eye-20-1691989638.png",index:"/database-27-1658237565.png",debug:"/terminal-184-1658431404.png",brain:"/brain-41-1686045820.png",command:"/command-147-1658431404.png",pdf:"/document pdf-66-1662364367.png",websocket:"/power outlet-81-1689918655.png",ai:"/ai chip-118-1686045593.png",dashboard:"/dashboard 6-8-1662364403.png",store:"/store-30-1662820309.png",icons:"/ui8-139-1693375584.png",build:"/tools-58-1662364403.png",linkedin:"/linkedin-113-1693375539.png",support:"/headphone-24-1663753435.png",nofee:"/snow%20bag-318-1672139659.png",anytime:"/circle%20clock-39-1658435834.png",free:"/bird-106-1678249964.png",cloud:"/cloud%20connect-56-1658236831.png",code:"/code-12-1658431404.png",screenshot:"/scan%20image-226-1658434699.png",pagecontent:"/web%20page%20download-36-1658436291.png",improve:"/ai%20neural%20share-142-1686045754.png",roadmap:"/roadmap-159-1681196175.png"},ee={figma:"/icons/project/Figma-logo.svg.png",githubraw:"/icons/project/github-mark-white.png"},te=(e,t,n="#000",s={},r=!1)=>{if(r)return g("img",{src:ee[e]?.replace(/ /g,"%20"),alt:e,style:{width:t,height:t,objectFit:"contain",...s}});let i=Z[e]?.replace(/ /g,"%20")||e?.replace(/ /g,"%20");return i=e.startsWith("http")?e:"https://cdn.oblien.com/static/png-icons/"+i,g("div",{style:{maskImage:`url('${i}')`,maskSize:"contain",maskRepeat:"no-repeat",maskPosition:"center",WebkitMaskSize:"contain",WebkitMaskRepeat:"no-repeat",WebkitMaskPosition:"center",width:t,height:t,backgroundColor:n,...s}})},ne=({showLoadMore:e,enableHistory:t,hasMoreMessages:n,messagesLength:s,error:r,isInitialLoading:i,loadMoreMessages:o,isLoadingMore:a})=>e&&t&&n&&0!==s&&!r&&!i?g("div",{className:"react-chat-core-load-more flex justify-center py-4",children:g("button",{onClick:o,disabled:a,className:"react-chat-core-load-more-button flex items-center gap-2 text-theme-tertiary hover:text-theme-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed opacity-50",children:m(p,a?{children:[g("div",{className:"react-chat-core-load-more-spinner w-4 h-4 border-2 border-theme-primary border-t-theme-tertiary rounded-full animate-spin"}),g("span",{className:"react-chat-core-load-more-text text-sm",children:"Loading..."})]}:{children:[te("refresh",18,"currentColor"),g("span",{className:"react-chat-core-load-more-text text-sm",children:"Load more messages"})]})})}):null,se=({error:e})=>{const{welcome:t}=K(),n=(()=>{if(!e)return null;let t="";return t="string"==typeof e?e:e.message?e.message:e.error?"string"==typeof e.error?e.error:e.error.message||"An error occurred":"An unexpected error occurred",t})();return g("div",{className:"react-ai-agent-start-chat flex flex-col items-center justify-center h-full",children:"object"!=typeof t||t?.title?m("div",{className:"react-ai-agent-start-chat-content text-center mb-8 flex flex-col items-center justify-center gap-2",children:[e&&g("span",{className:"react-ai-agent-start-chat-error-icon",children:te("error",70,"currentColor",{marginBottom:"10px"})}),g("h2",{className:"react-ai-agent-start-chat-title text-2xl font-light text-theme-primary mb-4",children:e?"Something went wrong":t?.title}),g("p",{className:"react-ai-agent-start-chat-description text-theme-muted mb-6 max-w-md text-base leading-relaxed",children:e?n:t?.description}),e&&e.type&&g("p",{className:"react-ai-agent-start-chat-error-type text-xs text-theme-tertiary mt-2 opacity-50",children:e.type.replace("_"," ")})]}):t})},re=({WelcomeComponent:e,error:t,isPanelOpen:n})=>e?g(e,{error:t}):g(se,{error:t,miniMode:n}),ie=()=>m("div",{className:"react-ai-agent-loading-mock mt-20 space-y-8 px-5 pt-20 pb-40 w-full max-w-[800px] mx-auto",children:[m("div",{className:"react-ai-agent-loading-mock-welcome flex items-start gap-4 mb-12",children:[g("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-welcome w-10 h-10 rounded-full shimmer-skeleton"}),m("div",{className:"react-ai-agent-loading-mock-content flex-1 space-y-3",children:[g("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-4 rounded-full shimmer-skeleton w-2/3"}),g("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-2 h-4 rounded-full shimmer-skeleton w-1/2"})]})]}),Array.from({length:2}).map((e,t)=>m("div",{className:"react-ai-agent-loading-mock-message-group space-y-6",children:[m("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-user flex items-start gap-4 justify-end",children:[g("div",{className:"react-ai-agent-loading-mock-message-content max-w-[70%] space-y-2",children:g("div",{className:"react-ai-agent-loading-mock-line h-3 rounded-full shimmer-skeleton w-full"})}),g("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-user w-8 h-8 rounded-full shimmer-skeleton"})]}),m("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-ai flex items-start gap-4",children:[g("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-ai w-8 h-8 rounded-full shimmer-skeleton"}),m("div",{className:"react-ai-agent-loading-mock-message-content flex-1 space-y-3",children:[g("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-3 rounded-full shimmer-skeleton w-4/5"}),g("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-2 h-3 rounded-full shimmer-skeleton w-3/4"})]})]})]},t))]}),oe=({onComplete:e,duration:t=800})=>{const[n,o]=i(0),[a,l]=i(!1),c=s(0);return r(()=>{c.current=300,requestAnimationFrame(()=>{o(c.current)});const n=setTimeout(()=>{l(!0),e?.()},t);return()=>clearTimeout(n)},[t,e]),a?null:g("div",{style:{height:n+"px",transition:`height ${t}ms cubic-bezier(0.4, 0, 0.2, 1)`,pointerEvents:"none"}})};function ae(e){return()=>e}function le(e){e()}function ce(e,t){return n=>e(t(n))}function de(e,t){return()=>e(t)}function ue(e){return void 0!==e}function he(){}function ge(e,t){return t(e),e}function me(e,t){return t(e)}function pe(...e){return e}function fe(e,t){return e(1,t)}function xe(e,t){e(0,t)}function ve(e){e(2)}function ye(e){return e(4)}function we(e,t){return fe(e,function(e){return t=>e(0,t)}(t))}function be(e,t){const n=e(1,e=>{n(),t(e)});return n}function Ie(e){let t,n;return s=>r=>{t=r,n&&clearTimeout(n),n=setTimeout(()=>{s(t)},e)}}function Se(e,t){return e===t}function ke(e=Se){let t;return n=>s=>{e(t,s)||(t=s,n(s))}}function Ce(e){return t=>n=>{e(n)&&t(n)}}function Te(e){return t=>ce(t,e)}function Me(e){return t=>()=>{t(e)}}function ze(e,...t){const n=function(...e){return t=>e.reduceRight(me,t)}(...t);return(t,s)=>{switch(t){case 2:return void ve(e);case 1:return fe(e,n(s))}}}function He(e,t){return n=>s=>{n(t=e(t,s))}}function Re(e){return t=>n=>{e>0?e--:t(n)}}function Ne(e){let t,n=null;return s=>r=>{n=r,!t&&(t=setTimeout(()=>{t=void 0,s(n)},e))}}function Ee(...e){const t=Array(e.length);let n=0,s=null;const r=Math.pow(2,e.length)-1;return e.forEach((e,i)=>{const o=Math.pow(2,i);fe(e,e=>{const a=n;n|=o,t[i]=e,a!==r&&n===r&&s&&(s(),s=null)})}),e=>i=>{const o=()=>{e([i].concat(t))};n===r?o():s=o}}function Ae(e){let t=e;const n=Oe();return(e,s)=>{switch(e){case 0:t=s;break;case 1:s(t);break;case 4:return t}return n(e,s)}}function Fe(e,t){return ge(Ae(t),t=>we(e,t))}function Oe(){const e=[];return(t,n)=>{switch(t){case 0:return void e.slice().forEach(e=>{e(n)});case 2:return void e.splice(0,e.length);case 1:return e.push(n),()=>{const t=e.indexOf(n);t>-1&&e.splice(t,1)}}}}function Be(e){return ge(Oe(),t=>we(e,t))}function Le(e,t=[],{singleton:n}={singleton:!0}){return{constructor:e,dependencies:t,id:_e(),singleton:n}}const _e=()=>Symbol();function De(...e){const t=Oe(),n=Array(e.length);let s=0;const r=Math.pow(2,e.length)-1;return e.forEach((e,i)=>{const o=Math.pow(2,i);fe(e,e=>{n[i]=e,s|=o,s===r&&xe(t,n)})}),function(e,i){switch(e){case 2:return void ve(t);case 1:return s===r&&i(n),fe(t,i)}}}function Pe(e,t=Se){return ze(e,ke(t))}function We(...e){return function(t,n){switch(t){case 2:return;case 1:return function(...e){return()=>{e.map(le)}}(...e.map(e=>fe(e,n)))}}}var qe=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(qe||{});const je=Le(()=>{const e=Ae(3);return{log:Ae((t,n,s=1)=>{null!=(typeof globalThis>"u"?window:globalThis).VIRTUOSO_LOG_LEVEL||ye(e)}),logLevel:e}},[],{singleton:!0});function Ue(e,t,n){return Ve(e,t,n).callbackRef}function Ve(t,n,s){const r=e.useRef(null);let i=e=>{};const o=e.useMemo(()=>"u">typeof ResizeObserver?new ResizeObserver(e=>{const n=()=>{const n=e[0].target;null!==n.offsetParent&&t(n)};s?n():requestAnimationFrame(n)}):null,[t,s]);return i=e=>{e&&n?(null==o||o.observe(e),r.current=e):(r.current&&(null==o||o.unobserve(r.current)),r.current=null)},{callbackRef:i,ref:r}}function $e(e,t,n){return"normal"!==t&&!(null!=t&&t.endsWith("px"))&&n(e+" was not resolved to pixel value correctly",t,qe.WARN),"normal"===t?0:parseInt(null!=t?t:"0",10)}function Ge(t,n,s){const r=e.useRef(null),i=e.useCallback(e=>{if(null==e||!e.offsetParent)return;const s=e.getBoundingClientRect(),i=s.width;let o,l;if(n){const e=n.getBoundingClientRect(),t=s.top-e.top;l=e.height-Math.max(0,t),o=t+n.scrollTop}else{const e=a.current.ownerDocument.defaultView;l=e.innerHeight-Math.max(0,s.top),o=s.top+e.scrollY}r.current={offsetTop:o,visibleHeight:l,visibleWidth:i},t(r.current)},[t,n]),{callbackRef:o,ref:a}=Ve(i,!0,s),l=e.useCallback(()=>{i(a.current)},[i,a]);return e.useEffect(()=>{var e;if(n){n.addEventListener("scroll",l);const e=new ResizeObserver(()=>{requestAnimationFrame(l)});return e.observe(n),()=>{n.removeEventListener("scroll",l),e.unobserve(n)}}{const t=null==(e=a.current)?void 0:e.ownerDocument.defaultView;return null==t||t.addEventListener("scroll",l),null==t||t.addEventListener("resize",l),()=>{null==t||t.removeEventListener("scroll",l),null==t||t.removeEventListener("resize",l)}}},[l,n,a]),o}const Ke=Le(()=>{const e=Oe(),t=Oe(),n=Ae(0),s=Oe(),r=Ae(0),i=Oe(),o=Oe(),a=Ae(0),l=Ae(0),c=Ae(0),d=Ae(0),u=Oe(),h=Oe(),g=Ae(!1),m=Ae(!1),p=Ae(!1);return we(ze(e,Te(({scrollTop:e})=>e)),t),we(ze(e,Te(({scrollHeight:e})=>e)),o),we(t,r),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:l,footerHeight:d,headerHeight:a,horizontalDirection:m,scrollBy:h,scrollContainerState:e,scrollHeight:o,scrollingInProgress:g,scrollTo:u,scrollTop:t,skipAnimationFrameInResizeObserver:p,smoothScrollTargetReached:s,statefulScrollTop:r,viewportHeight:i}},[],{singleton:!0}),Je={lvl:0};function Ye(e,t){const n=e.length;if(0===n)return[];let{index:s,value:r}=t(e[0]);const i=[];for(let o=1;n>o;o++){const{index:n,value:a}=t(e[o]);i.push({end:n-1,start:s,value:r}),s=n,r=a}return i.push({end:1/0,start:s,value:r}),i}function Qe(e){return e===Je}function Xe(e,t){if(!Qe(e))return t===e.k?e.v:Xe(e.k>t?e.l:e.r,t)}function Ze(e,t,n="k"){if(Qe(e))return[-1/0,void 0];if(+e[n]===t)return[e.k,e.v];if(t>+e[n]){const s=Ze(e.r,t,n);return s[0]===-1/0?[e.k,e.v]:s}return Ze(e.l,t,n)}function et(e,t,n){return Qe(e)?ut(t,n,1):t===e.k?at(e,{k:t,v:n}):function(e){return gt(ht(e))}(at(e,e.k>t?{l:et(e.l,t,n)}:{r:et(e.r,t,n)}))}function tt(){return Je}function nt(e,t,n){return Qe(e)?[]:function(e){return Ye(e,({k:e,v:t})=>({index:e,value:t}))}(it(e,Ze(e,t)[0],n))}function st(e,t){if(Qe(e))return Je;const{k:n,l:s,r:r}=e;if(t===n){if(Qe(s))return r;if(Qe(r))return s;{const[t,n]=dt(s);return ot(at(e,{k:t,l:lt(s),v:n}))}}return ot(at(e,n>t?{l:st(s,t)}:{r:st(r,t)}))}function rt(e){return Qe(e)?[]:[...rt(e.l),{k:e.k,v:e.v},...rt(e.r)]}function it(e,t,n){if(Qe(e))return[];const{k:s,l:r,r:i,v:o}=e;let a=[];return s>t&&(a=a.concat(it(r,t,n))),s>=t&&n>=s&&a.push({k:s,v:o}),n>=s&&(a=a.concat(it(i,t,n))),a}function ot(e){const{l:t,lvl:n,r:s}=e;if(s.lvl>=n-1&&t.lvl>=n-1)return e;if(n>s.lvl+1){if(ct(t))return ht(at(e,{lvl:n-1}));if(!Qe(t)&&!Qe(t.r))return at(t.r,{l:at(t,{r:t.r.l}),lvl:n,r:at(e,{l:t.r.r,lvl:n-1})});throw Error("Unexpected empty nodes")}if(ct(e))return gt(at(e,{lvl:n-1}));if(Qe(s)||Qe(s.l))throw Error("Unexpected empty nodes");{const t=s.l,r=ct(t)?s.lvl-1:s.lvl;return at(t,{l:at(e,{lvl:n-1,r:t.l}),lvl:t.lvl+1,r:gt(at(s,{l:t.r,lvl:r}))})}}function at(e,t){return ut(void 0!==t.k?t.k:e.k,void 0!==t.v?t.v:e.v,void 0!==t.lvl?t.lvl:e.lvl,void 0!==t.l?t.l:e.l,void 0!==t.r?t.r:e.r)}function lt(e){return Qe(e.r)?e.l:ot(at(e,{r:lt(e.r)}))}function ct(e){return Qe(e)||e.lvl>e.r.lvl}function dt(e){return Qe(e.r)?[e.k,e.v]:dt(e.r)}function ut(e,t,n,s=Je,r=Je){return{k:e,l:s,lvl:n,r:r,v:t}}function ht(e){const{l:t}=e;return Qe(t)||t.lvl!==e.lvl?e:at(t,{r:at(e,{l:t.r})})}function gt(e){const{lvl:t,r:n}=e;return Qe(n)||Qe(n.r)||n.lvl!==t||n.r.lvl!==t?e:at(n,{l:at(e,{r:n.l}),lvl:t+1})}function mt(e,t){return!(!e||e.startIndex!==t.startIndex||e.endIndex!==t.endIndex)}function pt(e,t){return!(!e||e[0]!==t[0]||e[1]!==t[1])}const ft=Le(()=>({recalcInProgress:Ae(!1)}),[],{singleton:!0});function xt(e,t,n){return e[vt(e,t,n)]}function vt(e,t,n,s=0){let r=e.length-1;for(;r>=s;){const i=Math.floor((s+r)/2),o=n(e[i],t);if(0===o)return i;if(-1===o){if(2>r-s)return i-1;r=i-1}else{if(r===s)return i;s=i+1}}throw Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function yt(e,t){return Math.round(e.getBoundingClientRect()[t])}function wt(e){return!Qe(e.groupOffsetTree)}function bt({index:e},t){return t===e?0:e>t?-1:1}function It({offset:e},t){return t===e?0:e>t?-1:1}function St(e,t,n){if(0===t.length)return 0;const{index:s,offset:r,size:i}=xt(t,e,bt),o=e-s,a=i*o+(o-1)*n+r;return a>0?a+n:a}function kt(e,t){if(!wt(t))return e;let n=0;for(;e+n>=t.groupIndices[n];)n++;return e+n}function Ct(e,t,n){if(function(e){return"u">typeof e.groupIndex}(e))return t.groupIndices[e.groupIndex]+1;{let s=kt("LAST"===e.index?n:e.index,t);return s=Math.max(0,s,Math.min(n,s)),s}}function Tt(e,[t,n,s,r]){t.length>0&&s("received item sizes",t,qe.DEBUG);const i=e.sizeTree;let o=i,a=0;if(n.length>0&&Qe(i)&&2===t.length){const e=t[0].size,s=t[1].size;o=n.reduce((t,n)=>et(et(t,n,e),n+1,s),o)}else[o,a]=function(e,t){let n=Qe(e)?0:1/0;for(const s of t){const{endIndex:t,size:r,startIndex:i}=s;if(n=Math.min(n,i),Qe(e)){e=et(e,0,r);continue}const o=nt(e,i-1,t+1);if(o.some(Rt(s)))continue;let a=!1,l=!1;for(const{end:n,start:s,value:c}of o)a?(t>=s||r===c)&&(e=st(e,s)):(l=c!==r,a=!0),n>t&&t>=s&&c!==r&&(e=et(e,t+1,c));l&&(e=et(e,i,r))}return[e,n]}(o,t);if(o===i)return e;const{lastIndex:l,lastOffset:c,lastSize:d,offsetTree:u}=zt(e.offsetTree,a,o,r);return{groupIndices:n,groupOffsetTree:n.reduce((e,t)=>et(e,t,St(t,u,r)),tt()),lastIndex:l,lastOffset:c,lastSize:d,offsetTree:u,sizeTree:o}}function Mt(e,t){let n=0,s=0;for(;e>n;)n+=t[s+1]-t[s]-1,s++;return s-(n===e?0:1)}function zt(e,t,n,s){let r=e,i=0,o=0,a=0,l=0;if(0!==t){l=vt(r,t-1,bt),a=r[l].offset;const e=Ze(n,t-1);i=e[0],o=e[1],r.length&&r[l].size===Ze(n,t)[1]&&(l-=1),r=r.slice(0,l+1)}else r=[];for(const{start:c,value:d}of nt(n,t,1/0)){const e=c-i,t=e*o+a+e*s;r.push({index:c,offset:t,size:d}),i=c,a=t,o=d}return{lastIndex:i,lastOffset:a,lastSize:o,offsetTree:r}}function Ht(e){return{index:e.index,value:e}}function Rt(e){const{endIndex:t,size:n,startIndex:s}=e;return e=>e.start===s&&(e.end===t||e.end===1/0)&&e.value===n}const Nt={offsetHeight:"height",offsetWidth:"width"},Et=Le(([{log:e},{recalcInProgress:t}])=>{const n=Oe(),s=Oe(),r=Fe(s,0),i=Oe(),o=Oe(),a=Ae(0),l=Ae([]),c=Ae(void 0),d=Ae(void 0),u=Ae(void 0),h=Ae(void 0),g=Ae((e,t)=>yt(e,Nt[t])),m=Ae(void 0),p=Ae(0),f={groupIndices:[],groupOffsetTree:tt(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:tt()},x=Fe(ze(n,Ee(l,e,p),He(Tt,f),ke()),f),v=Fe(ze(l,ke(),He((e,t)=>({current:t,prev:e.current}),{current:[],prev:[]}),Te(({prev:e})=>e)),[]);we(ze(l,Ce(e=>e.length>0),Ee(x,p),Te(([e,t,n])=>{const s=e.reduce((e,s,r)=>et(e,s,St(s,t.offsetTree,n)||r),tt());return{...t,groupIndices:e,groupOffsetTree:s}})),x),we(ze(s,Ee(x),Ce(([e,{lastIndex:t}])=>t>e),Te(([e,{lastIndex:t,lastSize:n}])=>[{endIndex:t,size:n,startIndex:e}])),n),we(c,d);const y=Fe(ze(c,Te(e=>void 0===e)),!0);we(ze(d,Ce(e=>void 0!==e&&Qe(ye(x).sizeTree)),Te(e=>{const t=ye(u),n=ye(l).length>0;return t?n?[{endIndex:0,size:t,startIndex:0},{endIndex:1,size:e,startIndex:1}]:[]:[{endIndex:0,size:e,startIndex:0}]})),n),we(ze(h,Ce(e=>void 0!==e&&e.length>0&&Qe(ye(x).sizeTree)),Te(e=>{const t=[];let n=e[0],s=0;for(let r=1;e.length>r;r++){const i=e[r];i!==n&&(t.push({endIndex:r-1,size:n,startIndex:s}),n=i,s=r)}return t.push({endIndex:e.length-1,size:n,startIndex:s}),t})),n),we(ze(l,Ee(u,d),Ce(([,e,t])=>void 0!==e&&void 0!==t),Te(([e,t,n])=>{const s=[];for(let r=0;e.length>r;r++){const i=e[r],o=e[r+1];s.push({startIndex:i,endIndex:i,size:t}),void 0!==o&&s.push({startIndex:i+1,endIndex:o-1,size:n})}return s})),n);const w=Be(ze(n,Ee(x),He(({sizes:e},[t,n])=>({changed:n!==e,sizes:n}),{changed:!1,sizes:f}),Te(e=>e.changed)));fe(ze(a,He((e,t)=>({diff:e.prev-t,prev:t}),{diff:0,prev:0}),Te(e=>e.diff)),e=>{const{groupIndices:n}=ye(x);if(e>0)xe(t,!0),xe(i,e+Mt(e,n));else if(0>e){const t=ye(v);t.length>0&&(e-=Mt(-e,t)),xe(o,e)}}),fe(ze(a,Ee(e)),([e,t])=>{0>e&&t("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:a},qe.ERROR)});const b=Be(i);we(ze(i,Ee(x),Te(([e,t])=>{const n=[],s=t.lastSize;if(t.groupIndices.length>0){const r=Xe(t.sizeTree,0);let i=0,o=0;for(;e>i;){const e=t.groupIndices[o],a=t.groupIndices.length===o+1?1/0:t.groupIndices[o+1]-e-1;n.push({endIndex:e,size:r,startIndex:e}),n.push({endIndex:e+1+a-1,size:s,startIndex:e+1}),o++,i+=a+1}const a=rt(t.sizeTree);return i!==e&&a.shift(),a.reduce((t,{k:n,v:s})=>{let r=t.ranges;return 0!==t.prevSize&&(r=[...t.ranges,{endIndex:n+e-1,size:t.prevSize,startIndex:t.prevIndex}]),{prevIndex:n+e,prevSize:s,ranges:r}},{prevIndex:e,prevSize:0,ranges:n}).ranges}return rt(t.sizeTree).reduce((t,{k:n,v:s})=>({prevIndex:n+e,prevSize:s,ranges:[...t.ranges,{endIndex:n+e-1,size:t.prevSize,startIndex:t.prevIndex}]}),{prevIndex:0,prevSize:s,ranges:[]}).ranges})),n);const I=Be(ze(o,Ee(x,p),Te(([e,{offsetTree:t},n])=>St(-e,t,n))));return we(ze(o,Ee(x,p),Te(([e,t,n])=>{if(t.groupIndices.length>0){if(Qe(t.sizeTree))return t;let s=tt();const r=ye(v);let i=0,o=0,a=0;for(;-e>i;){a=r[o];const e=r[o+1]-a-1;o++,i+=e+1}return s=rt(t.sizeTree).reduce((t,{k:n,v:s})=>et(t,Math.max(0,n+e),s),s),i!==-e&&(s=et(s,0,Xe(t.sizeTree,a)),s=et(s,1,Ze(t.sizeTree,1-e)[1])),{...t,sizeTree:s,...zt(t.offsetTree,0,s,n)}}{const s=rt(t.sizeTree).reduce((t,{k:n,v:s})=>et(t,Math.max(0,n+e),s),tt());return{...t,sizeTree:s,...zt(t.offsetTree,0,s,n)}}})),x),{beforeUnshiftWith:b,data:m,defaultItemSize:d,firstItemIndex:a,fixedItemSize:c,fixedGroupSize:u,gap:p,groupIndices:l,heightEstimates:h,itemSize:g,listRefresh:w,shiftWith:o,shiftWithOffset:I,sizeRanges:n,sizes:x,statefulTotalCount:r,totalCount:s,trackItemSizes:y,unshiftWith:i}},pe(je,ft),{singleton:!0});function At(e){return e.reduce((e,t)=>(e.groupIndices.push(e.totalCount),e.totalCount+=t+1,e),{groupIndices:[],totalCount:0})}const Ft=Le(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:s,scrollTop:r}])=>{const i=Oe(),o=Oe(),a=Be(ze(i,Te(At)));return we(ze(a,Te(e=>e.totalCount)),n),we(ze(a,Te(e=>e.groupIndices)),e),we(ze(De(r,t,s),Ce(([e,t])=>wt(t)),Te(([e,t,n])=>Ze(t.groupOffsetTree,Math.max(e-n,0),"v")[0]),ke(),Te(e=>[e])),o),{groupCounts:i,topItemsIndexes:o}},pe(Et,Ke)),Ot=Le(([{log:e}])=>{const t=Ae(!1),n=Be(ze(t,Ce(e=>e),ke()));return fe(t,t=>{t&&ye(e)("props updated",{},qe.DEBUG)}),{didMount:n,propsReady:t}},pe(je),{singleton:!0}),Bt="u">typeof document&&"scrollBehavior"in document.documentElement.style;function Lt(e){const t="number"==typeof e?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!Bt)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const _t=Le(([{gap:e,listRefresh:t,sizes:n,totalCount:s},{fixedFooterHeight:r,fixedHeaderHeight:i,footerHeight:o,headerHeight:a,scrollingInProgress:l,scrollTo:c,smoothScrollTargetReached:d,viewportHeight:u},{log:h}])=>{const g=Oe(),m=Oe(),p=Ae(0);let f=null,x=null,v=null;function y(){f&&(f(),f=null),v&&(v(),v=null),x&&(clearTimeout(x),x=null),xe(l,!1)}return we(ze(g,Ee(n,u,s,p,a,o,h),Ee(e,i,r),Te(([[e,n,s,r,i,o,a,c],u,h,p])=>{const w=Lt(e),{align:b,behavior:I,offset:S}=w,k=r-1,C=Ct(w,n,k);let T=St(C,n.offsetTree,u)+o;"end"===b?(T+=h+Ze(n.sizeTree,C)[1]-s+p,C===k&&(T+=a)):"center"===b?T+=(h+Ze(n.sizeTree,C)[1]-s+p)/2:T-=i,S&&(T+=S);const M=t=>{y(),t?(c("retrying to scroll to",{location:e},qe.DEBUG),xe(g,e)):(xe(m,!0),c("list did not change, scroll successful",{},qe.DEBUG))};if(y(),"smooth"===I){let e=!1;v=fe(t,t=>{e=e||t}),f=be(d,()=>{M(e)})}else f=be(ze(t,e=>{const t=setTimeout(()=>{e(!1)},150);return n=>{n&&(e(!0),clearTimeout(t))}}),M);return x=setTimeout(()=>{y()},1200),xe(l,!0),c("scrolling from index to",{behavior:I,index:C,top:T},qe.DEBUG),{behavior:I,top:T}})),c),{scrollTargetReached:m,scrollToIndex:g,topListHeight:p}},pe(Et,Ke,je),{singleton:!0});function Dt(e,t){0==e?t():requestAnimationFrame(()=>{Dt(e-1,t)})}function Pt(e,t){return"number"==typeof e?e:"LAST"===e.index?t-1:e.index}const Wt=Le(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:s},{scrollTargetReached:r,scrollToIndex:i},{didMount:o}])=>{const a=Ae(!0),l=Ae(0),c=Ae(!0);return we(ze(o,Ee(l),Ce(([e,t])=>!!t),Me(!1)),a),we(ze(o,Ee(l),Ce(([e,t])=>!!t),Me(!1)),c),fe(ze(De(t,o),Ee(a,n,e,c),Ce(([[,e],t,{sizeTree:n},s,r])=>e&&(!Qe(n)||ue(s))&&!t&&!r),Ee(l)),([,e])=>{be(r,()=>{xe(c,!0)}),Dt(4,()=>{be(s,()=>{xe(a,!0)}),xe(i,e)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:l,scrolledToInitialItem:a}},pe(Et,Ke,_t,Ot),{singleton:!0});function qt(e,t){return 1.01>Math.abs(e-t)}const jt="up",Ut="down",Vt={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},$t=Le(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:s,scrollTop:r,viewportHeight:i}])=>{const o=Ae(!1),a=Ae(!0),l=Oe(),c=Oe(),d=Ae(4),u=Ae(0),h=Fe(ze(We(ze(Pe(r),Re(1),Me(!0)),ze(Pe(r),Re(1),Me(!1),Ie(100))),ke()),!1),g=Fe(ze(We(ze(n,Me(!0)),ze(n,Me(!1),Ie(200))),ke()),!1);we(ze(De(Pe(r),Pe(u)),Te(([e,t])=>t>=e),ke()),a),we(ze(a,Ne(50)),c);const m=Be(ze(De(s,Pe(i),Pe(t),Pe(e),Pe(d)),He((e,[{scrollHeight:t,scrollTop:n},s,r,i,o])=>{const a={scrollHeight:t,scrollTop:n,viewportHeight:s};if(n+s-t>-o){let t,s;return n>e.state.scrollTop?(t="SCROLLED_DOWN",s=e.state.scrollTop-n):(t="SIZE_DECREASED",s=e.state.scrollTop-n||e.scrollTopDelta),{atBottom:!0,atBottomBecause:t,scrollTopDelta:s,state:a}}let l;return l=a.scrollHeight>e.state.scrollHeight?"SIZE_INCREASED":e.state.viewportHeight>s?"VIEWPORT_HEIGHT_DECREASING":e.state.scrollTop>n?"SCROLLING_UPWARDS":"NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:l,state:a}},Vt),ke((e,t)=>e&&e.atBottom===t.atBottom))),p=Fe(ze(s,He((e,{scrollHeight:t,scrollTop:n,viewportHeight:s})=>qt(e.scrollHeight,t)?{changed:!1,jump:0,scrollHeight:t,scrollTop:n}:e.scrollTop!==n&&1>t-(n+s)?{changed:!0,jump:e.scrollTop-n,scrollHeight:t,scrollTop:n}:{changed:!0,jump:0,scrollHeight:t,scrollTop:n},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Ce(e=>e.changed),Te(e=>e.jump)),0);we(ze(m,Te(e=>e.atBottom)),o),we(ze(o,Ne(50)),l);const f=Ae(Ut);we(ze(s,Te(({scrollTop:e})=>e),ke(),He((e,t)=>ye(g)?{direction:e.direction,prevScrollTop:t}:{direction:e.prevScrollTop>t?jt:Ut,prevScrollTop:t},{direction:Ut,prevScrollTop:0}),Te(e=>e.direction)),f),we(ze(s,Ne(50),Me("none")),f);const x=Ae(0);return we(ze(h,Ce(e=>!e),Me(0)),x),we(ze(r,Ne(100),Ee(h),Ce(([e,t])=>t),He(([e,t],[n])=>[t,n],[0,0]),Te(([e,t])=>t-e)),x),{atBottomState:m,atBottomStateChange:l,atBottomThreshold:d,atTopStateChange:c,atTopThreshold:u,isAtBottom:o,isAtTop:a,isScrolling:h,lastJumpDueToItemResize:p,scrollDirection:f,scrollVelocity:x}},pe(Ke)),Gt="top",Kt="bottom",Jt="none";function Yt(e,t,n){return"number"==typeof e?n===jt&&t===Gt||n===Ut&&t===Kt?e:0:n===jt?t===Gt?e.main:e.reverse:t===Kt?e.main:e.reverse}function Qt(e,t){var n;return"number"==typeof e?e:null!=(n=e[t])?n:0}const Xt=Le(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:s,viewportHeight:r}])=>{const i=Oe(),o=Ae(0),a=Ae(0),l=Ae(0);return{increaseViewportBy:a,listBoundary:i,overscan:l,topListHeight:o,visibleRange:Fe(ze(De(Pe(s),Pe(r),Pe(n),Pe(i,pt),Pe(l),Pe(o),Pe(t),Pe(e),Pe(a)),Te(([e,t,n,[s,r],i,o,a,l,c])=>{const d=e-l,u=o+a,h=Math.max(n-d,0);let g=Jt;const m=Qt(c,Gt),p=Qt(c,Kt);return s-=l,r+=n+a,(s+=n+a)>e+u-m&&(g=jt),e-h+t+p>(r-=l)&&(g=Ut),g!==Jt?[Math.max(d-n-Yt(i,Gt,g)-m,0),d-h-a+t+Yt(i,Kt,g)+p]:null}),Ce(e=>null!=e),ke(pt)),[0,0])}},pe(Ke),{singleton:!0}),Zt={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function en(e,t,n,s,r,i){const{lastIndex:o,lastOffset:a,lastSize:l}=r;let c=0,d=0;if(e.length>0){c=e[0].offset;const t=e[e.length-1];d=t.offset+t.size}const u=n-o,h=c,g=a+u*l+(u-1)*s-d;return{bottom:d,firstItemIndex:i,items:nn(e,r,i),offsetBottom:g,offsetTop:c,top:h,topItems:nn(t,r,i),topListHeight:t.reduce((e,t)=>t.size+e,0),totalCount:n}}function tn(e,t,n,s,r,i){let o=0;if(n.groupIndices.length>0)for(const c of n.groupIndices){if(c-o>=e)break;o++}const a=e+o,l=Pt(t,a);return en(Array.from({length:a}).map((e,t)=>({data:i[t+l],index:t+l,offset:0,size:0})),[],a,r,n,s)}function nn(e,t,n){if(0===e.length)return[];if(!wt(t))return e.map(e=>({...e,index:e.index+n,originalIndex:e.index}));const s=[],r=nt(t.groupOffsetTree,e[0].index,e[e.length-1].index);let i,o=0;for(const a of e){let e;(!i||a.index>i.end)&&(i=r.shift(),o=t.groupIndices.indexOf(i.start)),e=a.index===i.start?{index:o,type:"group"}:{groupIndex:o,index:a.index-(o+1)+n},s.push({...e,data:a.data,offset:a.offset,originalIndex:a.index,size:a.size})}return s}function sn(e,t){var n;return void 0===e?0:"number"==typeof e?e:null!=(n=e[t])?n:0}const rn=Le(([{data:e,firstItemIndex:t,gap:n,sizes:s,totalCount:r},i,{listBoundary:o,topListHeight:a,visibleRange:l},{initialTopMostItemIndex:c,scrolledToInitialItem:d},{topListHeight:u},h,{didMount:g},{recalcInProgress:m}])=>{const p=Ae([]),f=Ae(0),x=Oe(),v=Ae(0);we(i.topItemsIndexes,p);const y=Fe(ze(De(g,m,Pe(l,pt),Pe(r),Pe(s),Pe(c),d,Pe(p),Pe(t),Pe(n),Pe(v),e),Ce(([e,t,,n,,,,,,,,s])=>e&&!t&&!(s&&s.length!==n)),Te(([,,[e,t],n,s,r,i,o,a,l,c,d])=>{var u,h,g,m;const p=s,{offsetTree:x,sizeTree:v}=p,y=ye(f);if(0===n)return{...Zt,totalCount:n};if(0===e&&0===t)return 0===y?{...Zt,totalCount:n}:tn(y,r,s,a,l,d||[]);if(Qe(v))return y>0?null:en(function(e,t,n){if(wt(t)){const s=kt(e,t);return[{index:Ze(t.groupOffsetTree,s)[0],offset:0,size:0},{data:null==n?void 0:n[0],index:s,offset:0,size:0}]}return[{data:null==n?void 0:n[0],index:e,offset:0,size:0}]}(Pt(r,n),p,d),[],n,l,p,a);const w=[];if(o.length>0){const e=o[0],t=o[o.length-1];let n=0;for(const s of nt(v,e,t)){const r=s.value,i=Math.max(s.start,e),o=Math.min(s.end,t);for(let e=i;o>=e;e++)w.push({data:null==d?void 0:d[e],index:e,offset:n,size:r}),n+=r}}if(!i)return en([],w,n,l,p,a);const b=o.length>0?o[o.length-1]+1:0,I=function(e,t,n,s=0){return s>0&&(t=Math.max(t,xt(e,s,bt).offset)),Ye(function(e,t,n,s){const r=vt(e,t,s),i=vt(e,n,s,r);return e.slice(r,i+1)}(e,t,n,It),Ht)}(x,e,t,b);if(0===I.length)return null;const S=n-1,k=ge([],n=>{for(const s of I){const r=s.value;let i=r.offset,o=s.start;const a=r.size;if(e>r.offset){o+=Math.floor((e-r.offset+l)/(a+l));const t=o-s.start;i+=t*a+t*l}b>o&&(i+=(b-o)*a,o=b);const c=Math.min(s.end,S);for(let e=o;c>=e&&t>i;e++)n.push({data:null==d?void 0:d[e],index:e,offset:i,size:a}),i+=a+l}}),C=sn(c,Gt),T=sn(c,Kt);if(k.length>0&&(C>0||T>0)){const e=k[0],t=k[k.length-1];if(C>0&&e.index>b){const t=Math.min(C,e.index-b),n=[];let s=e.offset;for(let r=e.index-1;r>=e.index-t;r--){const t=null!=(h=null==(u=nt(v,r,r)[0])?void 0:u.value)?h:e.size;s-=t+l,n.unshift({data:null==d?void 0:d[r],index:r,offset:s,size:t})}k.unshift(...n)}if(T>0&&S>t.index){const e=Math.min(T,S-t.index);let n=t.offset+t.size+l;for(let s=t.index+1;t.index+e>=s;s++){const e=null!=(m=null==(g=nt(v,s,s)[0])?void 0:g.value)?m:t.size;k.push({data:null==d?void 0:d[s],index:s,offset:n,size:e}),n+=e+l}}}return en(k,w,n,l,p,a)}),Ce(e=>null!==e),ke()),Zt);we(ze(e,Ce(ue),Te(e=>null==e?void 0:e.length)),r),we(ze(y,Te(e=>e.topListHeight)),u),we(u,a),we(ze(y,Te(e=>[e.top,e.bottom])),o),we(ze(y,Te(e=>e.items)),x);const w=Be(ze(y,Ce(({items:e})=>e.length>0),Ee(r,e),Ce(([{items:e},t])=>e[e.length-1].originalIndex===t-1),Te(([,e,t])=>[e-1,t]),ke(pt),Te(([e])=>e))),b=Be(ze(y,Ne(200),Ce(({items:e,topItems:t})=>e.length>0&&e[0].originalIndex===t.length),Te(({items:e})=>e[0].index),ke())),I=Be(ze(y,Ce(({items:e})=>e.length>0),Te(({items:e})=>{let t=0,n=e.length-1;for(;"group"===e[t].type&&n>t;)t++;for(;"group"===e[n].type&&n>t;)n--;return{endIndex:e[n].index,startIndex:e[t].index}}),ke(mt)));return{endReached:w,initialItemCount:f,itemsRendered:x,listState:y,minOverscanItemCount:v,rangeChanged:I,startReached:b,topItemsIndexes:p,...h}},pe(Et,Ft,Xt,Wt,_t,$t,Ot,ft),{singleton:!0}),on=Le(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:s},{listState:r}])=>{const i=Oe(),o=Fe(ze(De(n,e,s,t,r),Te(([e,t,n,s,r])=>e+t+n+s+r.offsetBottom+r.bottom)),0);return we(Pe(o),i),{totalListHeight:o,totalListHeightChanged:i}},pe(Ke,rn),{singleton:!0}),an=Le(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Ae(!1);return{alignToBottom:n,paddingTopAddition:Fe(ze(De(n,e,t),Ce(([e])=>e),Te(([,e,t])=>Math.max(0,e-t)),Ne(0),ke()),0)}},pe(Ke,on),{singleton:!0}),ln=Le(()=>({context:Ae(null)})),cn=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:s,...r},viewportBottom:i,viewportTop:o})=>o>t?{...r,align:null!=n?n:"start",behavior:s}:e>i?{...r,align:null!=n?n:"end",behavior:s}:null,dn=Le(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:s,fixedHeaderHeight:r,headerHeight:i,scrollingInProgress:o,scrollTop:a,viewportHeight:l},{scrollToIndex:c}])=>{const d=Oe();return we(ze(d,Ee(t,l,n,i,r,s,a),Ee(e),Te(([[e,t,n,s,r,i,a,l],c])=>{const{align:d,behavior:u,calculateViewLocation:h=cn,done:g,...m}=e,p=Ct(e,t,s-1),f=St(p,t.offsetTree,c)+r+i,x=h({itemBottom:f+Ze(t.sizeTree,p)[1],itemTop:f,locationParams:{align:d,behavior:u,...m},viewportBottom:l+n-a,viewportTop:l+i});return x?g&&be(ze(o,Ce(e=>!e),Re(ye(o)?1:2)),g):null==g||g(),x}),Ce(e=>null!==e)),c),{scrollIntoView:d}},pe(Et,Ke,_t,rn,je),{singleton:!0});function un(e){return!!e&&("smooth"===e?"smooth":"auto")}const hn=Le(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:s},{atBottomState:r,isAtBottom:i},{scrollToIndex:o},{scrolledToInitialItem:a},{didMount:l,propsReady:c},{log:d},{scrollingInProgress:u},{context:h},{scrollIntoView:g}])=>{const m=Ae(!1),p=Oe();let f=null;function x(e){xe(o,{align:"end",behavior:e,index:"LAST"})}function v(e){const t=be(r,t=>{e&&!t.atBottom&&"SIZE_INCREASED"===t.notAtBottomBecause&&!f&&(ye(d)("scrolling to bottom due to increased size",{},qe.DEBUG),x("auto"))});setTimeout(t,100)}fe(ze(De(ze(Pe(t),Re(1)),l),Ee(Pe(m),i,a,u),Te(([[e,t],n,s,r,i])=>{let o=t&&r,a="auto";return o&&(a=((e,t)=>"function"==typeof e?un(e(t)):t&&un(e))(n,s||i),o=o&&!!a),{followOutputBehavior:a,shouldFollow:o,totalCount:e}}),Ce(({shouldFollow:e})=>e)),({followOutputBehavior:t,totalCount:s})=>{f&&(f(),f=null),ye(n)?requestAnimationFrame(()=>{ye(d)("following output to ",{totalCount:s},qe.DEBUG),x(t)}):f=be(e,()=>{ye(d)("following output to ",{totalCount:s},qe.DEBUG),x(t),f=null})}),fe(ze(De(Pe(m),t,c),Ce(([e,,t])=>e&&t),He(({value:e},[,t])=>({refreshed:e===t,value:t}),{refreshed:!1,value:0}),Ce(({refreshed:e})=>e),Ee(m,t)),([,e])=>{ye(a)&&v(!1!==e)}),fe(p,()=>{v(!1!==ye(m))}),fe(De(Pe(m),r),([e,t])=>{e&&!t.atBottom&&"VIEWPORT_HEIGHT_DECREASING"===t.notAtBottomBecause&&x("auto")});const y=Ae(null),w=Oe();return we(We(ze(Pe(s),Te(e=>{var t;return null!=(t=null==e?void 0:e.length)?t:0})),ze(Pe(t))),w),fe(ze(De(ze(w,Re(1)),l),Ee(Pe(y),a,u,h),Te(([[e,t],n,s,r,i])=>t&&s&&(null==n?void 0:n({context:i,totalCount:e,scrollingInProgress:r}))),Ce(e=>!!e),Ne(0)),t=>{f&&(f(),f=null),ye(n)?requestAnimationFrame(()=>{ye(d)("scrolling into view",{}),xe(g,t)}):f=be(e,()=>{ye(d)("scrolling into view",{}),xe(g,t),f=null})}),{autoscrollToBottom:p,followOutput:m,scrollIntoViewOnChange:y}},pe(Et,$t,_t,Wt,Ot,je,Ke,ln,dn)),gn=Le(([{data:e,firstItemIndex:t,gap:n,sizes:s},{initialTopMostItemIndex:r},{initialItemCount:i,listState:o},{didMount:a}])=>(we(ze(a,Ee(i),Ce(([,e])=>0!==e),Ee(r,s,t,n,e),Te(([[,e],t,n,s,r,i=[]])=>tn(e,t,n,s,r,i))),o),{}),pe(Et,Wt,rn,Ot),{singleton:!0}),mn=Le(([{didMount:e},{scrollTo:t},{listState:n}])=>{const s=Ae(0);return fe(ze(e,Ee(s),Ce(([,e])=>0!==e),Te(([,e])=>({top:e}))),e=>{be(ze(n,Re(1),Ce(e=>e.items.length>1)),()=>{requestAnimationFrame(()=>{xe(t,e)})})}),{initialScrollTop:s}},pe(Ot,Ke,rn),{singleton:!0}),pn=Le(([{scrollVelocity:e}])=>{const t=Ae(!1),n=Oe(),s=Ae(!1);return we(ze(e,Ee(s,t,n),Ce(([e,t])=>!!t),Te(([e,t,n,s])=>{const{enter:r,exit:i}=t;if(n){if(i(e,s))return!1}else if(r(e,s))return!0;return n}),ke()),t),fe(ze(De(t,e,n),Ee(s)),([[e,t,n],s])=>{e&&s&&s.change&&s.change(t,n)}),{isSeeking:t,scrollSeekConfiguration:s,scrollSeekRangeChanged:n,scrollVelocity:e}},pe($t),{singleton:!0}),fn=Le(([{scrollContainerState:e,scrollTo:t}])=>{const n=Oe(),s=Oe(),r=Oe(),i=Ae(!1),o=Ae(void 0);return we(ze(De(n,s),Te(([{scrollHeight:e,scrollTop:t,viewportHeight:n},{offsetTop:s}])=>({scrollHeight:e,scrollTop:Math.max(0,t-s),viewportHeight:n}))),e),we(ze(t,Ee(s),Te(([e,{offsetTop:t}])=>({...e,top:e.top+t}))),r),{customScrollParent:o,useWindowScroll:i,windowScrollContainerState:n,windowScrollTo:r,windowViewportRect:s}},pe(Ke)),xn=Le(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:s},{initialTopMostItemIndex:r},{didMount:i},{useWindowScroll:o,windowScrollContainerState:a,windowViewportRect:l}])=>{const c=Oe(),d=Ae(void 0),u=Ae(null),h=Ae(null);return we(a,u),we(l,h),fe(ze(c,Ee(t,s,o,u,h,n)),([e,t,n,s,r,i,o])=>{const a=function(e){return rt(e).map(({k:e,v:t},n,s)=>{const r=s[n+1];return{endIndex:r?r.k-1:1/0,size:t,startIndex:e}})}(t.sizeTree);s&&null!==r&&null!==i&&(n=r.scrollTop-i.offsetTop),e({ranges:a,scrollTop:n-=o})}),we(ze(d,Ce(ue),Te(vn)),r),we(ze(i,Ee(d),Ce(([,e])=>void 0!==e),ke(),Te(([,e])=>e.ranges)),e),{getState:c,restoreStateFrom:d}},pe(Et,Ke,Wt,Ot,fn));function vn(e){return{align:"start",index:0,offset:e.scrollTop}}const yn=Le(([{topItemsIndexes:e}])=>{const t=Ae(0);return we(ze(t,Ce(e=>e>=0),Te(e=>Array.from({length:e}).map((e,t)=>t))),e),{topItemCount:t}},pe(rn));function wn(e){let t,n=!1;return()=>(n||(n=!0,t=e()),t)}const bn=wn(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),In=Le(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:s},{isAtBottom:r,isScrolling:i,lastJumpDueToItemResize:o,scrollDirection:a},{listState:l},{beforeUnshiftWith:c,gap:d,shiftWithOffset:u,sizes:h},{log:g},{recalcInProgress:m}])=>{const p=Be(ze(l,Ee(o),He(([,e,t,n],[{bottom:s,items:r,offsetBottom:i,totalCount:o},a])=>{const l=s+i;let c=0;return t===o&&e.length>0&&r.length>0&&(0===r[0].originalIndex&&0===e[0].originalIndex||(c=l-n,0!==c&&(c+=a))),[c,r,o,l]},[0,[],0,0]),Ce(([e])=>0!==e),Ee(s,a,n,r,g,m),Ce(([,e,t,n,,,s])=>!s&&!n&&0!==e&&t===jt),Te(([[e],,,,,t])=>(t("Upward scrolling compensation",{amount:e},qe.DEBUG),e))));function f(n){n>0?(xe(t,{behavior:"auto",top:-n}),xe(e,0)):(xe(e,0),xe(t,{behavior:"auto",top:-n}))}return fe(ze(p,Ee(e,i)),([t,n,s])=>{s&&bn()?xe(e,n-t):f(-t)}),fe(ze(De(Fe(i,!1),e,m),Ce(([e,t,n])=>!e&&!n&&0!==t),Te(([e,t])=>t),Ne(1)),f),we(ze(u,Te(e=>({top:-e}))),t),fe(ze(c,Ee(h,d),Te(([e,{groupIndices:t,lastSize:n,sizeTree:s},r])=>{function i(e){return e*(n+r)}if(0===t.length)return i(e);{let n=0;const r=Xe(s,0);let o=0,a=0;for(;e>o;){o++,n+=r;let s=t.length===a+1?1/0:t[a+1]-t[a]-1;o+s>e&&(n-=r,s=e-o+1),o+=s,n+=i(s),a++}return n}})),n=>{xe(e,n),requestAnimationFrame(()=>{xe(t,{top:n}),requestAnimationFrame(()=>{xe(e,0),xe(m,!1)})})}),{deviation:e}},pe(Ke,$t,rn,Et,je,ft)),Sn=Le(([e,t,n,s,r,i,o,a,l,c,d])=>({...e,...t,...n,...s,...r,...i,...o,...a,...l,...c,...d}),pe(Xt,gn,Ot,pn,on,mn,an,fn,dn,je,ln)),kn=Le(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:s,fixedGroupSize:r,gap:i,groupIndices:o,heightEstimates:a,itemSize:l,sizeRanges:c,sizes:d,statefulTotalCount:u,totalCount:h,trackItemSizes:g},{initialItemFinalLocationReached:m,initialTopMostItemIndex:p,scrolledToInitialItem:f},x,v,y,w,{scrollToIndex:b},I,{topItemCount:S},{groupCounts:k},C])=>{const{listState:T,minOverscanItemCount:M,topItemsIndexes:z,rangeChanged:H,...R}=w;return we(H,C.scrollSeekRangeChanged),we(ze(C.windowViewportRect,Te(e=>e.visibleHeight)),x.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:s,fixedGroupHeight:r,gap:i,groupCounts:k,heightEstimates:a,initialItemFinalLocationReached:m,initialTopMostItemIndex:p,scrolledToInitialItem:f,sizeRanges:c,topItemCount:S,topItemsIndexes:z,totalCount:h,...y,groupIndices:o,itemSize:l,listState:T,minOverscanItemCount:M,scrollToIndex:b,statefulTotalCount:u,trackItemSizes:g,rangeChanged:H,...R,...C,...x,sizes:d,...v}},pe(Et,Wt,Ke,xn,hn,rn,_t,In,yn,Ft,Sn));function Cn(e,t){const n={},s={};let r=0;const i=e.length;for(;i>r;)s[e[r]]=1,r+=1;for(const o in t)Object.hasOwn(s,o)||(n[o]=t[o]);return n}const Tn="u">typeof document?e.useLayoutEffect:e.useEffect;function Mn(t,n,s){const r=Object.keys(n.required||{}),i=Object.keys(n.optional||{}),o=Object.keys(n.methods||{}),a=Object.keys(n.events||{}),l=e.createContext({});function c(e,t){e.propsReady&&xe(e.propsReady,!1);for(const s of r)xe(e[n.required[s]],t[s]);for(const s of i)s in t&&xe(e[n.optional[s]],t[s]);e.propsReady&&xe(e.propsReady,!0)}function d(e){return a.reduce((t,s)=>(t[s]=function(e){let t,n;const s=()=>null==t?void 0:t();return function(r,i){switch(r){case 1:return i?n===i?void 0:(s(),n=i,t=fe(e,i),t):(s(),he);case 2:return s(),void(n=null)}}}(e[n.events[s]]),t),{})}const u=e.forwardRef((u,h)=>{const{children:m,...p}=u,[f]=e.useState(()=>ge(function(e){const t=new Map,n=({constructor:e,dependencies:s,id:r,singleton:i})=>{if(i&&t.has(r))return t.get(r);const o=e(s.map(e=>n(e)));return i&&t.set(r,o),o};return n(e)}(t),e=>{c(e,p)})),[x]=e.useState(de(d,f));return Tn(()=>{for(const e of a)e in p&&fe(x[e],p[e]);return()=>{Object.values(x).map(ve)}},[p,x,f]),Tn(()=>{c(f,p)}),e.useImperativeHandle(h,ae(function(e){return o.reduce((t,s)=>(t[s]=t=>{xe(e[n.methods[s]],t)},t),{})}(f))),g(l.Provider,{value:f,children:s?g(s,{...Cn([...r,...i,...a],p),children:m}):m})});return{Component:u,useEmitter:(t,n)=>{const s=e.useContext(l)[t];Tn(()=>fe(s,n),[n,s])},useEmitterValue:e.version.startsWith("18")?t=>{const n=e.useContext(l)[t],s=e.useCallback(e=>fe(n,e),[n]);return e.useSyncExternalStore(s,()=>ye(n),()=>ye(n))}:t=>{const n=e.useContext(l)[t],[s,r]=e.useState(de(ye,n));return Tn(()=>fe(n,e=>{e!==s&&r(ae(e))}),[n,s]),s},usePublisher:t=>{const n=e.useContext(l);return e.useCallback(e=>{xe(n[t],e)},[n,t])}}}const zn=e.createContext(void 0),Hn=e.createContext(void 0),Rn="u">typeof document?e.useLayoutEffect:e.useEffect;function Nn(e){return"self"in e}function En(t,n,s,r=he,i,o){const a=e.useRef(null),l=e.useRef(null),c=e.useRef(null),d=e.useCallback(e=>{let s,r,i;const a=e.target;if(function(e){return"body"in e}(a)||Nn(a)){const e=Nn(a)?a:a.defaultView;i=o?e.scrollX:e.scrollY,s=o?e.document.documentElement.scrollWidth:e.document.documentElement.scrollHeight,r=o?e.innerWidth:e.innerHeight}else i=o?a.scrollLeft:a.scrollTop,s=o?a.scrollWidth:a.scrollHeight,r=o?a.offsetWidth:a.offsetHeight;const d=()=>{t({scrollHeight:s,scrollTop:Math.max(i,0),viewportHeight:r})};e.suppressFlushSync?d():f.flushSync(d),null!==l.current&&(i===l.current||0>=i||i===s-r)&&(l.current=null,n(!0),c.current&&(clearTimeout(c.current),c.current=null))},[t,n,o]);return e.useEffect(()=>{const e=i||a.current;return r(i||a.current),d({suppressFlushSync:!0,target:e}),e.addEventListener("scroll",d,{passive:!0}),()=>{r(null),e.removeEventListener("scroll",d)}},[a,d,s,r,i]),{scrollByCallback:function(e){o&&(e={behavior:e.behavior,left:e.top}),a.current.scrollBy(e)},scrollerRef:a,scrollToCallback:function(e){const s=a.current;if(!s||(o?"offsetWidth"in s&&0===s.offsetWidth:"offsetHeight"in s&&0===s.offsetHeight))return;const r="smooth"===e.behavior;let i,d,u;if(Nn(s)?(d=Math.max(yt(s.document.documentElement,o?"width":"height"),o?s.document.documentElement.scrollWidth:s.document.documentElement.scrollHeight),i=o?s.innerWidth:s.innerHeight,u=o?window.scrollX:window.scrollY):(d=s[o?"scrollWidth":"scrollHeight"],i=yt(s,o?"width":"height"),u=s[o?"scrollLeft":"scrollTop"]),e.top=Math.ceil(Math.max(Math.min(d-i,e.top),0)),qt(i,d)||e.top===u)return t({scrollHeight:d,scrollTop:u,viewportHeight:i}),void(r&&n(!0));r?(l.current=e.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,l.current=null,n(!0)},1e3)):l.current=null,o&&(e={behavior:e.behavior,left:e.top}),s.scrollTo(e)}}}const An="-webkit-sticky",Fn="sticky",On=wn(()=>{if(typeof document>"u")return Fn;const e=document.createElement("div");return e.style.position=An,e.style.position===An?An:Fn});function Bn(e){return e}const Ln=Le(([e,t])=>({...e,...t}),pe(kn,Le(()=>{const e=Ae(e=>"Item "+e),t=Ae(e=>"Group "+e),n=Ae({}),s=Ae(Bn),r=Ae("div"),i=Ae(he),o=(e,t=null)=>Fe(ze(n,Te(t=>t[e]),ke()),t);return{components:n,computeItemKey:s,EmptyPlaceholder:o("EmptyPlaceholder"),FooterComponent:o("Footer"),GroupComponent:o("Group","div"),groupContent:t,HeaderComponent:o("Header"),HeaderFooterTag:r,ItemComponent:o("Item","div"),itemContent:e,ListComponent:o("List","div"),ScrollerComponent:o("Scroller","div"),scrollerRef:i,ScrollSeekPlaceholder:o("ScrollSeekPlaceholder"),TopItemListComponent:o("TopItemList")}}))),_n=({height:e})=>g("div",{style:{height:e}}),Dn={overflowAnchor:"none",position:On(),zIndex:1},Pn={overflowAnchor:"none"},Wn={...Pn,display:"inline-block",height:"100%"},qn=e.memo(function({showTopList:t=!1}){const n=is("listState"),s=os("sizeRanges"),r=is("useWindowScroll"),i=is("customScrollParent"),o=os("windowScrollContainerState"),a=os("scrollContainerState"),c=i||r?o:a,d=is("itemContent"),u=is("context"),h=is("groupContent"),m=is("trackItemSizes"),p=is("itemSize"),f=is("log"),x=os("gap"),v=is("horizontalDirection"),{callbackRef:y}=function(t,n,s,r,i,o,a,l,c){const d=e.useCallback(e=>{const s=function(e,t,n,s){const r=e.length;if(0===r)return null;const i=[];for(let o=0;r>o;o++){const r=e.item(o);if(void 0===r.dataset.index)continue;const a=parseInt(r.dataset.index),l=parseFloat(r.dataset.knownSize),c=t(r,n);if(0===c&&s("Zero-sized element, this should not happen",{child:r},qe.ERROR),c===l)continue;const d=i[i.length-1];0===i.length||d.size!==c||d.endIndex!==a-1?i.push({endIndex:a,size:c,startIndex:a}):i[i.length-1].endIndex++}return i}(e.children,n,l?"offsetWidth":"offsetHeight",i);let c=e.parentElement;for(;!c.dataset.virtuosoScroller;)c=c.parentElement;const d="window"===c.lastElementChild.dataset.viewportType;let u;d&&(u=c.ownerDocument.defaultView);const h=a?l?a.offsetWidth:a.offsetHeight:d?l?u.innerWidth:u.innerHeight:l?c.offsetWidth:c.offsetHeight;r({scrollHeight:a?l?a.scrollWidth:a.scrollHeight:d?l?u.document.documentElement.scrollWidth:u.document.documentElement.scrollHeight:l?c.scrollWidth:c.scrollHeight,scrollTop:Math.max(a?l?a.scrollLeft:a.scrollTop:d?l?u.scrollX||u.document.documentElement.scrollLeft:u.scrollY||u.document.documentElement.scrollTop:l?c.scrollLeft:c.scrollTop,0),viewportHeight:h}),null==o||o(l?$e("column-gap",getComputedStyle(e).columnGap,i):$e("row-gap",getComputedStyle(e).rowGap,i)),null!==s&&t(s)},[t,n,i,o,a,r,l]);return Ve(d,s,c)}(s,p,m,t?he:c,f,x,i,v,is("skipAnimationFrameInResizeObserver")),[w,b]=e.useState(0);rs("deviation",e=>{w!==e&&b(e)});const I=is("EmptyPlaceholder"),S=is("ScrollSeekPlaceholder")||_n,k=is("ListComponent"),C=is("ItemComponent"),T=is("GroupComponent"),M=is("computeItemKey"),z=is("isSeeking"),H=is("groupIndices").length>0,R=is("alignToBottom"),N=is("initialItemFinalLocationReached"),E=t?{}:{boxSizing:"border-box",...v?{display:"inline-block",height:"100%",marginLeft:0!==w?w:R?"auto":0,paddingLeft:n.offsetTop,paddingRight:n.offsetBottom,whiteSpace:"nowrap"}:{marginTop:0!==w?w:R?"auto":0,paddingBottom:n.offsetBottom,paddingTop:n.offsetTop},...N?{}:{visibility:"hidden"}};return!t&&0===n.totalCount&&I?g(I,{...Gn(I,u)}):g(k,{...Gn(k,u),"data-testid":t?"virtuoso-top-item-list":"virtuoso-item-list",ref:y,style:E,children:(t?n.topItems:n.items).map(e=>{const t=e.originalIndex,s=M(t+n.firstItemIndex,e.data,u);return z?l(S,{...Gn(S,u),height:e.size,index:e.index,key:s,type:e.type||"item",..."group"===e.type?{}:{groupIndex:e.groupIndex}}):"group"===e.type?l(T,{...Gn(T,u),"data-index":t,"data-item-index":e.index,"data-known-size":e.size,key:s,style:Dn},h(e.index,u)):l(C,{...Gn(C,u),...Kn(C,e.data),"data-index":t,"data-item-group-index":e.groupIndex,"data-item-index":e.index,"data-known-size":e.size,key:s,style:v?Wn:Pn},H?d(e.index,e.groupIndex,e.data,u):d(e.index,e.data,u))})})}),jn={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},Un={outline:"none",overflowX:"auto",position:"relative"},Vn=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:{}}),$n={position:On(),top:0,width:"100%",zIndex:1};function Gn(e,t){if("string"!=typeof e)return{context:t}}function Kn(e,t){return{item:"string"==typeof e?void 0:t}}const Jn=e.memo(function(){const t=is("HeaderComponent"),n=os("headerHeight"),s=is("HeaderFooterTag"),r=Ue(e.useMemo(()=>e=>{n(yt(e,"height"))},[n]),!0,is("skipAnimationFrameInResizeObserver")),i=is("context");return t?g(s,{ref:r,children:g(t,{...Gn(t,i)})}):null}),Yn=e.memo(function(){const t=is("FooterComponent"),n=os("footerHeight"),s=is("HeaderFooterTag"),r=Ue(e.useMemo(()=>e=>{n(yt(e,"height"))},[n]),!0,is("skipAnimationFrameInResizeObserver")),i=is("context");return t?g(s,{ref:r,children:g(t,{...Gn(t,i)})}):null});function Qn({useEmitter:t,useEmitterValue:n,usePublisher:s}){return e.memo(function({children:e,style:r,context:i,...o}){const a=s("scrollContainerState"),l=n("ScrollerComponent"),c=s("smoothScrollTargetReached"),d=n("scrollerRef"),u=n("horizontalDirection")||!1,{scrollByCallback:h,scrollerRef:m,scrollToCallback:p}=En(a,c,l,d,void 0,u);return t("scrollTo",p),t("scrollBy",h),g(l,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:m,style:{...u?Un:jn,...r},tabIndex:0,...o,...Gn(l,i),children:e})})}function Xn({useEmitter:t,useEmitterValue:n,usePublisher:s}){return e.memo(function({children:r,style:i,context:o,...a}){const l=s("windowScrollContainerState"),c=n("ScrollerComponent"),d=s("smoothScrollTargetReached"),u=n("totalListHeight"),h=n("deviation"),m=n("customScrollParent"),p=e.useRef(null),f=n("scrollerRef"),{scrollByCallback:x,scrollerRef:v,scrollToCallback:y}=En(l,d,c,f,m);return Rn(()=>{var e;return v.current=m||(null==(e=p.current)?void 0:e.ownerDocument.defaultView),()=>{v.current=null}},[v,m]),t("windowScrollTo",y),t("scrollBy",x),g(c,{ref:p,"data-virtuoso-scroller":!0,style:{position:"relative",...i,...0!==u?{height:u+h}:{}},...a,...Gn(c,o),children:r})})}const Zn=({children:t})=>{const n=e.useContext(zn),s=os("viewportHeight"),r=os("fixedItemHeight"),i=is("alignToBottom"),o=is("horizontalDirection"),a=Ue(e.useMemo(()=>ce(s,e=>yt(e,o?"width":"height")),[s,o]),!0,is("skipAnimationFrameInResizeObserver"));return e.useEffect(()=>{n&&(s(n.viewportHeight),r(n.itemHeight))},[n,s,r]),g("div",{"data-viewport-type":"element",ref:a,style:Vn(i),children:t})},es=({children:t})=>{const n=e.useContext(zn),s=os("windowViewportRect"),r=os("fixedItemHeight"),i=is("customScrollParent"),o=Ge(s,i,is("skipAnimationFrameInResizeObserver")),a=is("alignToBottom");return e.useEffect(()=>{n&&(r(n.itemHeight),s({offsetTop:0,visibleHeight:n.viewportHeight,visibleWidth:100}))},[n,s,r]),g("div",{"data-viewport-type":"window",ref:o,style:Vn(a),children:t})},ts=({children:e})=>{const t=is("TopItemListComponent")||"div",n=is("headerHeight"),s={...$n,marginTop:n+"px"},r=is("context");return g(t,{style:s,...Gn(t,r),children:e})},ns=e.memo(function(e){const t=is("useWindowScroll"),n=is("topItemsIndexes").length>0,s=is("customScrollParent"),r=is("context");return m(s||t?ls:as,{...e,context:r,children:[n&&g(ts,{children:g(qn,{showTopList:!0})}),m(s||t?es:Zn,{children:[g(Jn,{}),g(qn,{}),g(Yn,{})]})]})}),{Component:ss,useEmitter:rs,useEmitterValue:is,usePublisher:os}=Mn(Ln,{required:{},optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",minOverscanItemCount:"minOverscanItemCount",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedGroupHeight:"fixedGroupHeight",fixedItemHeight:"fixedItemHeight",heightEstimates:"heightEstimates",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},ns),as=Qn({useEmitter:rs,useEmitterValue:is,usePublisher:os}),ls=Xn({useEmitter:rs,useEmitterValue:is,usePublisher:os}),cs=ss;On();const ds={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},us={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:hs,floor:gs,max:ms,min:ps,round:fs}=Math;function xs(e,t,n){return Array.from({length:t-e+1}).map((t,s)=>({data:null===n?null:n[s+e],index:s+e}))}function vs(e,t){return e&&e.width===t.width&&e.height===t.height}function ys(e,t){return e&&e.column===t.column&&e.row===t.row}const ws=Le(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:s},{footerHeight:r,headerHeight:i,scrollBy:o,scrollContainerState:a,scrollTo:l,scrollTop:c,smoothScrollTargetReached:d,viewportHeight:u},h,g,{didMount:m,propsReady:p},{customScrollParent:f,useWindowScroll:x,windowScrollContainerState:v,windowScrollTo:y,windowViewportRect:w},b])=>{const I=Ae(0),S=Ae(0),k=Ae(ds),C=Ae({height:0,width:0}),T=Ae({height:0,width:0}),M=Oe(),z=Oe(),H=Ae(0),R=Ae(null),N=Ae({column:0,row:0}),E=Oe(),A=Oe(),F=Ae(!1),O=Ae(0),B=Ae(!0),L=Ae(!1),_=Ae(!1);fe(ze(m,Ee(O),Ce(([e,t])=>!!t)),()=>{xe(B,!1)}),fe(ze(De(m,B,T,C,O,L),Ce(([e,t,n,s,,r])=>e&&!t&&0!==n.height&&0!==s.height&&!r)),([,,,,e])=>{xe(L,!0),Dt(1,()=>{xe(M,e)}),be(ze(c),()=>{xe(t,[0,0]),xe(B,!0)})}),we(ze(A,Ce(e=>null!=e&&e.scrollTop>0),Me(0)),S),fe(ze(m,Ee(A),Ce(([,e])=>null!=e)),([,e])=>{e&&(xe(C,e.viewport),xe(T,e.item),xe(N,e.gap),e.scrollTop>0&&(xe(F,!0),be(ze(c,Re(1)),e=>{xe(F,!1)}),xe(l,{top:e.scrollTop})))}),we(ze(C,Te(({height:e})=>e)),u),we(ze(De(Pe(C,vs),Pe(T,vs),Pe(N,(e,t)=>e&&e.column===t.column&&e.row===t.row),Pe(c)),Te(([e,t,n,s])=>({gap:n,item:t,scrollTop:s,viewport:e}))),E),we(ze(De(Pe(I),s,Pe(N,ys),Pe(T,vs),Pe(C,vs),Pe(R),Pe(S),Pe(F),Pe(B),Pe(O)),Ce(([,,,,,,,e])=>!e),Te(([e,[t,n],s,r,i,o,a,,l,c])=>{const{column:d,row:u}=s,{height:h,width:g}=r,{width:m}=i;if(0===a&&(0===e||0===m))return ds;if(0===g){const t=Pt(c,e);return function(e){return{...us,items:e}}(xs(t,t+Math.max(a-1,0),o))}const p=bs(m,g,d);let f,x;l?0===t&&0===n&&a>0?(f=0,x=a-1):(f=p*gs((t+u)/(h+u)),x=p*hs((n+u)/(h+u))-1,x=ps(e-1,ms(x,p-1)),f=ps(x,ms(0,f))):(f=0,x=-1);const v=xs(f,x,o),{bottom:y,top:w}=Is(i,s,r,v),b=hs(e/p);return{bottom:y,itemHeight:h,items:v,itemWidth:g,offsetBottom:b*h+(b-1)*u-y,offsetTop:w,top:w}})),k),we(ze(R,Ce(e=>null!==e),Te(e=>e.length)),I),we(ze(De(C,T,k,N),Ce(([e,t,{items:n}])=>n.length>0&&0!==t.height&&0!==e.height),Te(([e,t,{items:n},s])=>{const{bottom:r,top:i}=Is(e,s,t,n);return[i,r]}),ke(pt)),t);const D=Ae(!1);we(ze(c,Ee(D),Te(([e,t])=>t||0!==e)),D);const P=Be(ze(De(k,I),Ce(([{items:e}])=>e.length>0),Ee(D),Ce(([[e,t],n])=>(n||e.bottom>0&&e.itemHeight>0&&0===e.offsetBottom&&e.items.length===t)&&e.items[e.items.length-1].index===t-1),Te(([[,e]])=>e-1),ke())),W=Be(ze(Pe(k),Ce(({items:e})=>e.length>0&&0===e[0].index),Me(0),ke())),q=Be(ze(Pe(k),Ee(F),Ce(([{items:e},t])=>e.length>0&&!t),Te(([{items:e}])=>({endIndex:e[e.length-1].index,startIndex:e[0].index})),ke(mt),Ne(0)));we(q,g.scrollSeekRangeChanged),we(ze(M,Ee(C,T,I,N),Te(([e,t,n,s,r])=>{const i=Lt(e),{align:o,behavior:a,offset:l}=i;let c=i.index;"LAST"===c&&(c=s-1),c=ms(0,c,ps(s-1,c));let d=Ss(t,r,n,c);return"end"===o?d=fs(d-t.height+n.height):"center"===o&&(d=fs(d-t.height/2+n.height/2)),l&&(d+=l),{behavior:a,top:d}})),l);const j=Fe(ze(k,Te(e=>e.offsetBottom+e.bottom)),0);return we(ze(w,Te(e=>({height:e.visibleHeight,width:e.visibleWidth}))),C),{customScrollParent:f,data:R,deviation:H,footerHeight:r,gap:N,headerHeight:i,increaseViewportBy:e,initialItemCount:S,itemDimensions:T,overscan:n,restoreStateFrom:A,scrollBy:o,scrollContainerState:a,scrollHeight:z,scrollTo:l,scrollToIndex:M,scrollTop:c,smoothScrollTargetReached:d,totalCount:I,useWindowScroll:x,viewportDimensions:C,windowScrollContainerState:v,windowScrollTo:y,windowViewportRect:w,...g,gridState:k,horizontalDirection:_,initialTopMostItemIndex:O,totalListHeight:j,...h,endReached:P,propsReady:p,rangeChanged:q,startReached:W,stateChanged:E,stateRestoreInProgress:F,...b}},pe(Xt,Ke,$t,pn,Ot,fn,je));function bs(e,t,n){return ms(1,gs((e+n)/(gs(t)+n)))}function Is(e,t,n,s){const{height:r}=n;if(void 0===r||0===s.length)return{bottom:0,top:0};const i=Ss(e,t,n,s[0].index);return{bottom:Ss(e,t,n,s[s.length-1].index)+r,top:i}}function Ss(e,t,n,s){const r=bs(e.width,n.width,t.column),i=gs(s/r),o=i*n.height+ms(0,i-1)*t.row;return o>0?o+t.row:o}const ks=Le(([e,t])=>({...e,...t}),pe(ws,Le(()=>{const e=Ae(e=>"Item "+e),t=Ae({}),n=Ae(null),s=Ae("virtuoso-grid-item"),r=Ae("virtuoso-grid-list"),i=Ae(Bn),o=Ae("div"),a=Ae(he),l=(e,n=null)=>Fe(ze(t,Te(t=>t[e]),ke()),n),c=Ae(!1),d=Ae(!1);return we(Pe(d),c),{components:t,computeItemKey:i,context:n,FooterComponent:l("Footer"),HeaderComponent:l("Header"),headerFooterTag:o,itemClassName:s,ItemComponent:l("Item","div"),itemContent:e,listClassName:r,ListComponent:l("List","div"),readyStateChanged:c,reportReadyState:d,ScrollerComponent:l("Scroller","div"),scrollerRef:a,ScrollSeekPlaceholder:l("ScrollSeekPlaceholder","div")}}))),Cs=e.memo(function(){const t=Es("gridState"),n=Es("listClassName"),s=Es("itemClassName"),r=Es("itemContent"),i=Es("computeItemKey"),o=Es("isSeeking"),a=As("scrollHeight"),c=Es("ItemComponent"),d=Es("ListComponent"),u=Es("ScrollSeekPlaceholder"),h=Es("context"),m=As("itemDimensions"),p=As("gap"),f=Es("log"),x=Es("stateRestoreInProgress"),v=As("reportReadyState"),y=Ue(e.useMemo(()=>e=>{a(e.parentElement.parentElement.scrollHeight);const t=e.firstChild;if(t){const{height:e,width:n}=t.getBoundingClientRect();m({height:e,width:n})}p({column:Bs("column-gap",getComputedStyle(e).columnGap,f),row:Bs("row-gap",getComputedStyle(e).rowGap,f)})},[a,m,p,f]),!0,!1);return Rn(()=>{t.itemHeight>0&&t.itemWidth>0&&v(!0)},[t]),x?null:g(d,{className:n,ref:y,...Gn(d,h),"data-testid":"virtuoso-item-list",style:{paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},children:t.items.map(e=>{const n=i(e.index,e.data,h);return o?g(u,{...Gn(u,h),height:t.itemHeight,index:e.index,width:t.itemWidth},n):l(c,{...Gn(c,h),className:s,"data-index":e.index,key:n},r(e.index,e.data,h))})})}),Ts=e.memo(function(){const t=Es("HeaderComponent"),n=As("headerHeight"),s=Es("headerFooterTag"),r=Ue(e.useMemo(()=>e=>{n(yt(e,"height"))},[n]),!0,!1),i=Es("context");return t?g(s,{ref:r,children:g(t,{...Gn(t,i)})}):null}),Ms=e.memo(function(){const t=Es("FooterComponent"),n=As("footerHeight"),s=Es("headerFooterTag"),r=Ue(e.useMemo(()=>e=>{n(yt(e,"height"))},[n]),!0,!1),i=Es("context");return t?g(s,{ref:r,children:g(t,{...Gn(t,i)})}):null}),zs=({children:t})=>{const n=e.useContext(Hn),s=As("itemDimensions"),r=As("viewportDimensions"),i=Ue(e.useMemo(()=>e=>{r(e.getBoundingClientRect())},[r]),!0,!1);return e.useEffect(()=>{n&&(r({height:n.viewportHeight,width:n.viewportWidth}),s({height:n.itemHeight,width:n.itemWidth}))},[n,r,s]),g("div",{ref:i,style:Vn(!1),children:t})},Hs=({children:t})=>{const n=e.useContext(Hn),s=As("windowViewportRect"),r=As("itemDimensions"),i=Es("customScrollParent"),o=Ge(s,i,!1);return e.useEffect(()=>{n&&(r({height:n.itemHeight,width:n.itemWidth}),s({offsetTop:0,visibleHeight:n.viewportHeight,visibleWidth:n.viewportWidth}))},[n,s,r]),g("div",{ref:o,style:Vn(!1),children:t})},Rs=e.memo(function({...e}){const t=Es("useWindowScroll"),n=Es("customScrollParent"),s=n||t?Os:Fs,r=n||t?Hs:zs,i=Es("context");return g(s,{...e,...Gn(s,i),children:m(r,{children:[g(Ts,{}),g(Cs,{}),g(Ms,{})]})})}),{useEmitter:Ns,useEmitterValue:Es,usePublisher:As}=Mn(ks,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},Rs),Fs=Qn({useEmitter:Ns,useEmitterValue:Es,usePublisher:As}),Os=Xn({useEmitter:Ns,useEmitterValue:Es,usePublisher:As});function Bs(e,t,n){return"normal"!==t&&!(null!=t&&t.endsWith("px"))&&n(e+" was not resolved to pixel value correctly",t,qe.WARN),"normal"===t?0:parseInt(null!=t?t:"0",10)}const Ls=({message:e,allowEdit:t=!0})=>{const n=[];return t&&n.push({icon:"edit",text:"Edit",onClick:()=>{}}),e.snapshot&&n.push({icon:"refresh",text:"Restore checkpoint",onClick:()=>{}}),m("div",{className:"react-ai-agent-user-message flex flex-col mb-2",children:[g("div",{className:"react-ai-agent-user-message-bubble-wrapper flex justify-end mb-2",children:g("div",{className:"react-ai-agent-user-message-bubble bg-secondary text-theme-primary px-4 py-2 rounded-[20px] max-w-xs md:max-w-md",style:{wordBreak:"break-word"},children:g("p",{className:"react-ai-agent-user-message-text text-[16px] leading-[22px] tracking-wide",children:e.text})})}),g("div",{className:"react-ai-agent-user-message-actions flex justify-end gap-4",children:n.map((e,t)=>m("button",{className:`react-ai-agent-user-message-action react-ai-agent-user-message-action-${e.icon} flex items-center gap-1 opacity-25`,onClick:e.onClick,children:[g("span",{className:"react-ai-agent-user-message-action-icon",children:te(e.icon,16,"currentColor")}),g("span",{className:"react-ai-agent-user-message-action-label text-[12px] font-[300] text-theme-primary",children:e.text})]},t))})]})};var _s=c(({message:e})=>{const t=Q(),[n,s]=i("");return r(()=>{const t=L(e.messageId);if(t)return t.subscribe(e=>{s(e)});s(e.text||"")},[e.messageId,e.text]),g("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",children:g("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",style:{wordBreak:"break-word"},children:g(x,{parseIncompleteMarkdown:!0,mode:"streaming",components:t,children:n})})})}),Ds=c(({text:e})=>{const t=Q(),n=e||"";return g("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",style:{minHeight:"20px"},children:g("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",style:{wordBreak:"break-word",minHeight:"20px"},children:n?g(x,{parseIncompleteMarkdown:!0,mode:"static",components:t,children:n}):g("span",{style:{opacity:.5},children:"..."})})})}),Ps=c(({message:e,animationConfig:t})=>e.isLive&&!e.finalized?g(_s,{message:e,animationConfig:t}):g(Ds,{text:e.text}));const Ws={'code[class*="language-"]':{color:"#d7d5d1",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",fontSize:"14px",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"white",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0.5em 0",overflow:"auto",background:"#1e1e1e",borderRadius:"15px"},'pre[class*="language-"]::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'pre[class*="language-"] ::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"]::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"] ::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'pre[class*="language-"]::selection':{textShadow:"none",background:"#0e0c0a"},'pre[class*="language-"] ::selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"]::selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"] ::selection':{textShadow:"none",background:"#0e0c0a"},':not(pre) > code[class*="language-"]':{color:"white",background:"#222222",padding:"0.1em",borderRadius:"0.3em",whiteSpace:"normal"},comment:{color:"#545053"},string:{color:"#838083"},number:{color:"#838083"},builtin:{color:"#838083"},char:{color:"#838083"},constant:{color:"#838083"},variable:{color:"#838083"},"class-name":{color:"#D7D5D1"},function:{color:"#D7D5D1"},tag:{color:"#838083"},"attr-name":{color:"#D7D5D1"},selector:{color:"#838083"},important:{fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"}},qs=c(({message:e,isInCurrentSession:t})=>{const n=s(null),l=s(e.finalized),c=s(null),[d,u]=i(!e.finalized),[h,p]=i(!1),[f,x]=i(""),w=e.isLive||!e.finalized,b=e.finalized||!t,I=e.duration||0,S=o(()=>e.text||"",[e.text]);r(()=>{requestAnimationFrame(()=>{p(!0)})},[]),r(()=>{if(!w||!d)return void x(S);const e=f.length,t=S.length;if(e>=t)return;const n=Math.min(5,t-e),s=setTimeout(()=>{x(S.slice(0,e+n))},20);return()=>clearTimeout(s)},[S,f,w,d]),r(()=>{if(n.current&&d&&w)return c.current&&cancelAnimationFrame(c.current),c.current=requestAnimationFrame(()=>{n.current&&(n.current.scrollTop=n.current.scrollHeight)}),()=>{c.current&&cancelAnimationFrame(c.current)}},[f,d,w]),r(()=>{if(b&&!l.current&&d){const e=setTimeout(()=>{u(!1)},800);return()=>clearTimeout(e)}},[b,d]);const k=a(()=>{u(e=>!e)},[]),C=o(()=>({code({node:e,inline:t,className:n,children:s,...r}){const i=/language-(\w+)/.exec(n||""),o=(s+"").replace(/\n$/,""),a=!t&&o.includes("\n");return t||!a?g("code",{className:"react-ai-agent-thinking-code-inline px-1 py-0.5 bg-secondary rounded text-xs font-mono whitespace-pre-wrap",...r,children:s}):g("div",{className:"react-ai-agent-thinking-code-block rounded-[15px] overflow-hidden my-3",children:g(v,{language:i?.[1]||"javascript",style:Ws,children:o})})},p:({children:e})=>g("p",{className:"react-ai-agent-thinking-paragraph mb-2 leading-5 text-sm",children:e}),ul:({children:e})=>g("ul",{className:"react-ai-agent-thinking-list react-ai-agent-thinking-list-unordered list-disc pl-5 mb-3 grid text-sm",children:e}),ol:({children:e})=>g("ol",{className:"react-ai-agent-thinking-list react-ai-agent-thinking-list-ordered list-decimal pl-5 mb-3 grid text-sm",children:e}),li:({children:e})=>g("li",{className:"react-ai-agent-thinking-list-item mb-1 text-sm",children:e}),h1:({children:e})=>g("h1",{className:"react-ai-agent-thinking-heading react-ai-agent-thinking-heading-1 text-lg font-semibold mb-2 mt-3",children:e}),h2:({children:e})=>g("h2",{className:"react-ai-agent-thinking-heading react-ai-agent-thinking-heading-2 text-base font-semibold mb-2 mt-3",children:e}),h3:({children:e})=>g("h3",{className:"react-ai-agent-thinking-heading react-ai-agent-thinking-heading-3 text-sm font-semibold mb-1 mt-2",children:e}),blockquote:({children:e})=>g("blockquote",{className:"react-ai-agent-thinking-blockquote border-l-4 border-gray-600 pl-3 italic my-3 text-theme-quaternary text-sm",children:e})}),[]);return m("div",{className:"react-ai-agent-thinking-message mb-4 mx-auto opacity-50 transition-all duration-300 ease-out",style:{opacity:h?.5:0,transform:h?"translateY(0)":"translateY(-10px)"},children:[b?m("button",{onClick:k,className:"react-ai-agent-thinking-toggle react-ai-agent-thinking-toggle-finished text-theme-tertiary text-sm hover:text-theme-secondary transition-colors mb-2 flex items-center gap-2",children:[g("span",{className:"react-ai-agent-thinking-toggle-icon transition-transform duration-300",children:te(d?"brain-10-1663078315.png":"brain-11-1663755045.png",20,"currentColor")}),m("span",{className:"react-ai-agent-thinking-toggle-text",children:["Thought for ",I," second",1!==I?"s":""]})]}):m("div",{className:"react-ai-agent-thinking-header text-theme-tertiary text-sm mb-2 flex items-center gap-2",children:[g("span",{className:"react-ai-agent-thinking-icon animate-pulse",children:te("brain-11-1663755045.png",20,"currentColor")}),g("span",{className:"react-ai-agent-thinking-label",children:"Thinking..."})]}),g("div",{style:{maxHeight:d?"150px":"0px",opacity:d?1:0,overflow:"hidden",transition:"max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s ease-out"},children:f&&g("div",{ref:n,className:"react-ai-agent-thinking-content-scroll overflow-y-auto scrollbar-thin scrollbar-track-transparent",style:{maxHeight:"150px",scrollBehavior:"smooth",WebkitMaskImage:"linear-gradient(to top, transparent 0%, black 60%, transparent 98%)",maskImage:"linear-gradient(to top, transparent 0%, black 60%, transparent 98%)"},children:g("div",{className:"react-ai-agent-thinking-content text-theme-primary prose prose-invert max-w-none whitespace-pre-wrap text-sm pt-10",style:{wordBreak:"break-word",opacity:w?.8:1,transition:"opacity 0.15s ease"},children:g(y,{components:C,children:f})})})})]})},(e,t)=>e.message.text===t.message.text&&e.message.finalized===t.message.finalized&&e.message.isLive===t.message.isLive&&e.message.duration===t.message.duration&&e.isInCurrentSession===t.isInCurrentSession);qs.displayName="ThinkingMessage";const js=({text:e,style:t,fontSize:n="1em",paddingRight:s="140px",backgroundSize:r="125px",isDark:i=!1})=>{let o=1;"string"==typeof n?o=parseFloat(n)||3:"number"==typeof n&&(o=n);let a=r;"125px"===r&&"3em"!==n&&(a=o/3*125+"px");const l={fontSize:n,paddingRight:s,WebkitBackgroundSize:a+" 100%",MozBackgroundSize:a+" 100%",backgroundSize:a+" 100%",...t};return g("div",{className:"react-ai-agent-shimmer-text shimmer "+(i?"dark":"light"),style:l,children:e})},Us=({message:e,title:t,isProcessing:n,isFinished:s,icon:r,iconComponent:i,isFlat:a=!0,onClick:l,isDark:c=!1,unmountOnExit:d,action:u,data:h,className:p,style:f,metadata:x})=>{const v=u||e?.action,y=h||e?.data,w=void 0!==s?s:e?.isFinished,b=void 0!==n?n:!w,I=x||e?.metadata,S=t||I?.name||e?.title,k=i||e?.iconComponent,C=void 0!==a?a:void 0===e?.isFlat||e.isFlat,T=void 0!==d?d:e?.unmountOnExit,M=l,z=I?.icon||r,H=o(()=>S?b?`Processing ${S}...`:"Finished "+S:v?(({data:e,action:t,isFinished:n})=>{if(!t||"string"!=typeof t)return"Processing...";try{const s=t.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ");return n?s:`${s}${e?.tool?" "+e?.tool:""}...`}catch(s){return t}})({data:y,action:v,isFinished:w}):"Processing...",[S,v,w,y]);return g("div",C?{className:"mb-[-2px] mx-auto "+p,style:{cursor:M?"pointer":"default",...f},onClick:M,children:m("div",{className:`flex items-center gap-3 px-0 rounded-[12px] text-${c?"white":"black"} relative overflow-auto`,children:[T?g("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${c?"white":"black"} rounded-full border-t-transparent opacity-50`}):k?k():te(z||"check circle-3-1660219236.png",20,c?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)",{position:"absolute"}),b?g(js,{isDark:c,text:H,style:{fontSize:"14px",marginLeft:"30px"}}):g("span",{style:{color:c?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)"},className:"text-[14px] ml-[30px] "+(k?"!ml-0":""),children:H})]})}:{className:"mb-[10px] mx-auto "+p,style:{cursor:M?"pointer":"default",...f},onClick:M,children:m("div",{className:`flex items-center p-3 rounded-[12px] text-${c?"white":"black"} relative overflow-hidden`,style:{backgroundColor:c?"rgba(255,255,255,0.02)":"rgba(0,0,0,0.02)"},children:[b?g("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${c?"white":"black"} rounded-full border-t-transparent opacity-50`}):k?k():te(icon||"check circle-3-1660219236.png",20,c?"rgba(255,255,255,0.8)":"rgba(0,0,0,0.8)",{position:"absolute"}),g("div",{className:"flex-1",children:b?g(js,{isDark:c,text:H,style:{marginLeft:"28px",marginTop:"-2px",color:c?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.2)"}}):g("span",{className:`text-[14px] text-${c?"white":"black"}/50 ml-[30px]`,children:H})})]})})};var Vs=c(({item:e,removeMessage:t,allowEditMessage:n,animationConfig:s,isInCurrentSession:r})=>g("div","user"===e.sender?{className:"react-ai-agent-message-item react-ai-agent-message-user",children:g(Ls,{message:e,allowEdit:n})}:"status"===e.type&&e.action?{className:"react-ai-agent-message-item react-ai-agent-message-status",children:g(J[e.action]||Us,{message:e})}:"thinking"===e.type?{className:"react-ai-agent-message-item react-ai-agent-message-thinking",children:g(qs,{message:e,removeMessage:t,isInCurrentSession:r})}:{className:"react-ai-agent-message-item react-ai-agent-message-ai",children:g(Ps,{message:e,animationConfig:s,isInCurrentSession:r})}));const $s=({type:e})=>{const t=["w-1.5 h-1.5","w-2.5 h-2.5","w-1.5 h-1.5"],n="text"===e?["L","O","A","D","I","N","G"]:Array.from({length:3}).fill(""),s=.6+.1*(n.length-1);return g("div",{className:"react-ai-agent-loading-response flex",children:g("div",{className:"react-ai-agent-loading-content flex justify-center items-center "+("text"===e?"text-7xl font-extrabold font-[Montserrat]":"gap-1.5"),children:n.map((n,r)=>g(w.span,{className:`react-ai-agent-loading-item react-ai-agent-loading-item-${e} inline-block ${"text"===e?"mx-[-0.05em]":t[r]+" rounded-full bg-inverse"}`,animate:{scale:[.75,1.5,.75],opacity:[.75,1,.75],filter:["blur(4px)","blur(0px)","blur(4px)"]},transition:{repeat:1/0,duration:.6,ease:"easeInOut",repeatDelay:s-.6,delay:.1*r},children:"text"===e?n:""},r))})})},Gs=({messages:e,isLoading:t,isResponseStarted:n,showLoadingIndicator:s,showSpacer:r=!1,spacerKey:i=0,onSpacerComplete:a})=>o(()=>{const o=[...e];return r&&o.push({type:"viewport-spacer",messageId:"viewport-spacer-"+i,onComplete:a,isResponseStarted:n}),s&&t&&!n&&o.push({type:"loading-indicator",messageId:"loading-indicator"}),o},[e,s,t,n,r,i,a]),Ks=e=>o(()=>{for(let t=e.length-1;t>=0;t--)if("user"===e[t].sender)return t;return-1},[e]),Js=({item:e,index:t,lastUserIndex:n,removeMessage:s,allowEditMessage:r,animationConfig:i,isLastItem:o=!1,isFirstItem:a=!1})=>{if(!e)return null;if("viewport-spacer"===e.type)return g(oe,{onComplete:e.onComplete,isResponseStarted:e.isResponseStarted});if("loading-indicator"===e.type)return g($s,{});if("empty-message"===e.type)return g("div",{style:{paddingTop:"100px"}});const l=g(Vs,{item:e,removeMessage:s,allowEditMessage:r,animationConfig:i,isInCurrentSession:t>n});return o?g("div",{style:{paddingBottom:"200px"},children:l}):a?g("div",{style:{paddingTop:"100px"},children:l}):l},Ys=({messages:e,removeMessage:t,allowEditMessage:n,animationConfig:r,height:i,width:o,shouldAutoScrollRef:l,isLoading:c,isResponseStarted:d,showLoadingIndicator:u,showSpacer:h,spacerKey:m,onSpacerComplete:p})=>{const f=s(!0),x=Gs({messages:e,isLoading:c,isResponseStarted:d,showLoadingIndicator:u,showSpacer:h,spacerKey:m,onSpacerComplete:p}),v=Ks(e),y=a(e=>{f.current=e,l&&(l.current=e)},[l]);a(()=>"smooth",[]);const w=a(e=>Js({item:x[e],index:e,lastUserIndex:v,removeMessage:t,allowEditMessage:n,isLastItem:e===x.length-1,animationConfig:r}),[x,v,t,n,r]);return g(cs,{style:{height:i,width:o},data:x,totalCount:x.length,itemContent:w,initialTopMostItemIndex:x.length-1,atBottomStateChange:y,alignToBottom:!0})},Qs="u">typeof window?d:r;function Xs(e){if(void 0!==e)switch(typeof e){case"number":return e;case"string":if(e.endsWith("px"))return parseFloat(e)}}function Zs(e){const t=s(()=>{throw Error("Cannot call during render.")});return Qs(()=>{t.current=e},[e]),a(e=>t.current?.(e),[t])}function er({scrollOffset:e}){return e}function tr(e,t="Assertion error"){if(!e)throw Error(t)}function nr(e,t){if(e===t)return!0;if(!!e!=!!t||(tr(void 0!==e),tr(void 0!==t),Object.keys(e).length!==Object.keys(t).length))return!1;for(const n in e)if(!Object.is(t[n],e[n]))return!1;return!0}function sr({cachedBounds:e,itemCount:t,itemSize:n}){if(0===t)return 0;if("number"==typeof n)return t*n;{const n=e.get(0===e.size?0:e.size-1);return tr(void 0!==n,"Unexpected bounds cache miss"),t*((n.scrollOffset+n.size)/e.size)}}function rr({cachedBounds:e,containerScrollOffset:t,containerSize:n,itemCount:s,overscanCount:r}){const i=s-1;let o=0,a=-1,l=0,c=-1,d=0;for(;i>d;){const n=e.get(d);if(n.scrollOffset+n.size>t)break;d++}for(o=d,l=Math.max(0,o-r);i>d;){const s=e.get(d);if(s.scrollOffset+s.size>=t+n)break;d++}return a=Math.min(i,d),c=Math.min(s-1,a+r),0>o&&(o=0,a=-1,l=0,c=-1),{startIndexVisible:o,stopIndexVisible:a,startIndexOverscan:l,stopIndexOverscan:c}}function ir(e,t){const{ariaAttributes:n,style:s,...r}=e,{ariaAttributes:i,style:o,...a}=t;return nr(n,i)&&nr(s,o)&&nr(r,a)}const or="data-react-window-index";function ar({children:e,className:t,defaultHeight:n=0,listRef:h,onResize:m,onRowsRendered:p,overscanCount:f=3,rowComponent:x,rowCount:v,rowHeight:y,rowProps:w,tagName:b="div",style:I,...S}){const k=function(e){return o(()=>e,Object.values(e))}(w),C=o(()=>c(x,ir),[x]),[T,M]=i(null),z=function(e){return null!=e&&"object"==typeof e&&"getAverageRowHeight"in e&&"function"==typeof e.getAverageRowHeight}(y),H=o(()=>z?e=>y.getRowHeight(e)??y.getAverageRowHeight():y,[z,y]),{getCellBounds:R,getEstimatedSize:N,scrollToIndex:E,startIndexOverscan:A,startIndexVisible:F,stopIndexOverscan:O,stopIndexVisible:B}=function({containerElement:e,containerStyle:t,defaultContainerSize:n=0,direction:r,isRtl:l=!1,itemCount:c,itemProps:u,itemSize:h,onResize:g,overscanCount:m}){const{height:p=n,width:f=n}=function({box:e,defaultHeight:t,defaultWidth:n,disabled:s,element:r,mode:a,style:l}){const{styleHeight:c,styleWidth:d}=o(()=>({styleHeight:Xs(l?.height),styleWidth:Xs(l?.width)}),[l?.height,l?.width]),[u,h]=i({height:t,width:n}),g=s||void 0!==c||"only-width"===a||void 0!==c&&void 0!==d;return Qs(()=>{if(null===r||g)return;const t=new ResizeObserver(e=>{for(const t of e){const{contentRect:e,target:n}=t;r===n&&h(t=>t.height===e.height&&t.width===e.width?t:{height:e.height,width:e.width})}});return t.observe(r,{box:e}),()=>{t?.unobserve(r)}},[e,g,r,c,d]),o(()=>({height:c??u.height,width:d??u.width}),[u,c,d])}({defaultHeight:n,defaultWidth:void 0,element:e,mode:"only-height",style:t}),x=s({height:0,width:0}),v=p,y=function({containerSize:e,itemSize:t}){let n;return"string"==typeof t?(tr(t.endsWith("%"),`Invalid item size: "${t}"; string values must be percentages (e.g. "100%")`),tr(void 0!==e,"Container size must be defined if a percentage item size is specified"),n=e*parseInt(t)/100):n=t,n}({containerSize:v,itemSize:h});d(()=>{if("function"==typeof g){const e=x.current;(e.height!==p||e.width!==f)&&(g({height:p,width:f},{...e}),e.height=p,e.width=f)}},[p,g,f]);const w=function({itemCount:e,itemProps:t,itemSize:n}){return o(()=>function({itemCount:e,itemProps:t,itemSize:n}){const s=new Map;return{get(r){for(tr(e>r,"Invalid index "+r);r>s.size-1;){const e=s.size;let i;switch(typeof n){case"function":i=n(e,t);break;case"number":i=n}if(0===e)s.set(e,{size:i,scrollOffset:0});else{const t=s.get(e-1);tr(void 0!==t,"Unexpected bounds cache miss for index "+r),s.set(e,{scrollOffset:t.scrollOffset+t.size,size:i})}}const i=s.get(r);return tr(void 0!==i,"Unexpected bounds cache miss for index "+r),i},set(e,t){s.set(e,t)},get size(){return s.size}}}({itemCount:e,itemProps:t,itemSize:n}),[e,t,n])}({itemCount:c,itemProps:u,itemSize:y}),b=a(e=>w.get(e),[w]),[I,S]=i(()=>rr({cachedBounds:w,containerScrollOffset:0,containerSize:v,itemCount:c,overscanCount:m})),{startIndexVisible:k,startIndexOverscan:C,stopIndexVisible:T,stopIndexOverscan:M}={startIndexVisible:Math.min(c-1,I.startIndexVisible),startIndexOverscan:Math.min(c-1,I.startIndexOverscan),stopIndexVisible:Math.min(c-1,I.stopIndexVisible),stopIndexOverscan:Math.min(c-1,I.stopIndexOverscan)},z=a(()=>sr({cachedBounds:w,itemCount:c,itemSize:y}),[w,c,y]),H=a(t=>{const n=er({containerElement:e,direction:r,isRtl:l,scrollOffset:t});return rr({cachedBounds:w,containerScrollOffset:n,containerSize:v,itemCount:c,overscanCount:m})},[w,e,v,r,l,c,m]);Qs(()=>{S(H(e?.scrollTop??0))},[e,r,H]),Qs(()=>{if(!e)return;const t=()=>{S(t=>{const{scrollTop:n}=e,s=er({containerElement:e,direction:r,isRtl:l,scrollOffset:n}),i=rr({cachedBounds:w,containerScrollOffset:s,containerSize:v,itemCount:c,overscanCount:m});return nr(i,t)?t:i})};return e.addEventListener("scroll",t),()=>{e.removeEventListener("scroll",t)}},[w,e,v,r,c,m]);const R=Zs(({align:t="auto",containerScrollOffset:n,index:s})=>{let i=function({align:e,cachedBounds:t,index:n,itemCount:s,itemSize:r,containerScrollOffset:i,containerSize:o}){if(0>n||n>=s)throw RangeError("Invalid index specified: "+n,{cause:`Index ${n} is not within the range of 0 - ${s-1}`});const a=sr({cachedBounds:t,itemCount:s,itemSize:r}),l=t.get(n),c=Math.max(0,Math.min(a-o,l.scrollOffset)),d=Math.max(0,l.scrollOffset-o+l.size);switch("smart"===e&&(e=d>i||i>c?"center":"auto"),e){case"start":return c;case"end":return d;case"center":return l.scrollOffset>o/2?a-o/2>l.scrollOffset+l.size/2?l.scrollOffset+l.size/2-o/2:a-o:0;default:return d>i||i>c?d>i?d:c:i}}({align:t,cachedBounds:w,containerScrollOffset:n,containerSize:v,index:s,itemCount:c,itemSize:y});if(e){if(i=er({containerElement:e,direction:r,isRtl:l,scrollOffset:i}),"function"!=typeof e.scrollTo){const e=H(i);nr(I,e)||S(e)}return i}});return{getCellBounds:b,getEstimatedSize:z,scrollToIndex:R,startIndexOverscan:C,startIndexVisible:k,stopIndexOverscan:M,stopIndexVisible:T}}({containerElement:T,containerStyle:I,defaultContainerSize:n,direction:"vertical",itemCount:v,itemProps:k,itemSize:H,onResize:m,overscanCount:f});u(h,()=>({get element(){return T},scrollToRow({align:e="auto",behavior:t="auto",index:n}){const s=E({align:e,containerScrollOffset:T?.scrollTop??0,index:n});"function"==typeof T?.scrollTo&&T.scrollTo({behavior:t,top:s})}}),[T,E]),Qs(()=>{if(!T)return;const e=Array.from(T.children).filter((e,t)=>!e.hasAttribute("aria-hidden")&&(e.setAttribute(or,""+(A+t)),!0));return z?y.observeRowElements(e):void 0},[T,z,y,A,O]),r(()=>{A>=0&&O>=0&&p&&p({startIndex:F,stopIndex:B},{startIndex:A,stopIndex:O})},[p,A,F,O,B]);const L=o(()=>{const e=[];if(v>0)for(let t=A;O>=t;t++){const n=R(t);e.push(l(C,{...k,ariaAttributes:{"aria-posinset":t+1,"aria-setsize":v,role:"listitem"},key:t,index:t,style:{position:"absolute",left:0,transform:`translateY(${n.scrollOffset}px)`,height:z?void 0:n.size,width:"100%"}}))}return e},[C,R,z,v,k,A,O]),_=g("div",{"aria-hidden":!0,style:{height:N(),width:"100%",zIndex:-1}});return l(b,{role:"list",...S,className:t,ref:M,style:{position:"relative",maxHeight:"100%",flexGrow:1,overflowY:"auto",...I}},L,e,_)}const lr=({dynamicHeight:e,messages:t,removeMessage:n,allowEditMessage:r,animationConfig:i,height:l,width:c,overscan:d,listRef:u,isLoading:h,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:x,onSpacerComplete:v})=>{const y=Gs({messages:t,isLoading:h,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:x,onSpacerComplete:v}),w=Ks(t),b=s(new Map),I=o(()=>({itemsData:y,removeMessage:n,allowEditMessage:r,animationConfig:i,dynamicHeight:e,lastUserIndex:w,heightCacheRef:b}),[y,n,r,i,e,w]),S=a(({index:e,style:t,ariaAttributes:n,...s})=>{const{itemsData:r,removeMessage:i,allowEditMessage:o,animationConfig:a,dynamicHeight:l,lastUserIndex:c,heightCacheRef:d}=s;return g("div",{style:t,ref:t=>{if(t){const n=r[e],s=n?.uniqueKey||n?.messageId||e;d.current.has(s)||requestAnimationFrame(()=>{const n=t.getBoundingClientRect().height;n!==l.getRowHeight(e)&&(l.setRowHeight(e,n),d.current.set(s,n))})}},...n,children:Js({item:r[e],index:e,lastUserIndex:c,removeMessage:i,isLastItem:e===r.length-1,allowEditMessage:o,animationConfig:a})})},[]);return g("div",{style:{height:l,width:c,overflow:"hidden"},children:g(ar,{listRef:u,rowComponent:S,rowCount:y.length,rowHeight:e,rowProps:I,overscanCount:d})})},cr=({itemsData:e,scrollToBottom:t,shouldAutoScrollRef:n,isStreaming:i})=>{const o=s(0),a=s(!1);r(()=>{!a.current&&e.length>0&&(a.current=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{t(!1)})}))},[]),r(()=>{e.length>o.current&&(o.current=e.length,!1!==n?.current&&t(!0))},[e.length,t,n]),r(()=>{if(!i)return;const e=setInterval(()=>{!1!==n?.current&&t(!1)},100);return()=>clearInterval(e)},[i,t,n])},dr=({messages:e,removeMessage:t,allowEditMessage:n,animationConfig:r,height:i,width:o,isStreaming:l,shouldAutoScrollRef:c})=>{const d=s(null),u=[{type:"empty-message",messageId:"empty-message"},...e],h=Ks(e),m=b({count:u.length,getScrollElement:()=>d.current,estimateSize:()=>200,overscan:10,measureElement:"undefined"!=typeof window&&-1===navigator.userAgent.indexOf("Firefox")?e=>e?.getBoundingClientRect().height:void 0}),{handleScroll:p}=(e=>{const t=s(!1),n=s(null),r=a(s=>{n.current&&clearTimeout(n.current),t.current=!0,n.current=setTimeout(()=>{t.current=!1},150),s&&e&&(e.current=50>Math.abs(s.scrollHeight-s.scrollTop-s.clientHeight))},[e]);return{isUserScrollingRef:t,handleScroll:r}})(c),f=a((e=!0)=>{const t=d.current;t&&t.scrollTo({top:t.scrollHeight,behavior:e?"smooth":"auto"})},[]);cr({itemsData:u,scrollToBottom:f,shouldAutoScrollRef:c,isStreaming:l});const x=m.getVirtualItems();return g("div",{ref:d,onScroll:()=>p(d.current),className:"tanstack-virtual-container",style:{height:i,width:o,overflowY:"auto",contain:"strict"},children:g("div",{style:{height:m.getTotalSize()+"px",width:"100%",position:"relative"},children:x.map(e=>g("div",{"data-index":e.index,ref:m.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${e.start}px)`},children:Js({item:u[e.index],index:e.index,lastUserIndex:h,removeMessage:t,allowEditMessage:n,animationConfig:r,isLastItem:e.index===u.length-1,isFirstItem:0===e.index})},e.key))})})},ur=({messages:e,removeMessage:t,allowEditMessage:n,animationConfig:s,scrollToBottom:r,shouldAutoScrollRef:i,isStreaming:o,scrollContainerRef:a,height:l,width:c,isLoading:d,isResponseStarted:u,showLoadingIndicator:h,showSpacer:m,spacerKey:p,onSpacerComplete:f})=>{const x=Gs({messages:e,isLoading:d,isResponseStarted:u,showLoadingIndicator:h,showSpacer:m,spacerKey:p,onSpacerComplete:f}),v=Ks(e);return cr({itemsData:x,scrollToBottom:e=>r(),shouldAutoScrollRef:i,isStreaming:o}),g("div",{ref:a,className:"react-chat-core-simple-container overflow-y-auto scrollbar-hide",style:{height:l,width:c,overflowY:"auto"},children:x.map((e,r)=>e?g("div",{children:Js({item:e,index:r,lastUserIndex:v,removeMessage:t,allowEditMessage:n,animationConfig:s})},e.uniqueKey||e.messageId||r):null)})},hr=h(({virtualization:e="tanstack",estimateSize:t=150,overscan:n=10,isDark:l=!1,className:c="",containerStyle:d={},useGradientMask:h=!0,gradientMaskStyle:p="linear-gradient(to bottom, transparent 6.5%, black 18%)",allowEditMessage:f=!1,showWelcome:x=!0,showLoadMore:v=!0,showLoadingIndicator:y=!0,keepUserMessageInView:w=!0,welcomeComponent:b,loadingComponent:I,initialAnimation:S=null,height:k="100%",width:C="100%"},T)=>{const[M,z]=i(!1),[H,R]=i(!1),N=s(null),{sendMsg:E,messages:A,messageManager:F,isLoading:O,isStreaming:B,isPanelOpen:L,error:_,isInitialLoading:D,isResponseStarted:P,abort:W,loadMoreMessages:q,isLoadingMore:j,hasMoreMessages:U,enableHistory:V,animationConfig:$,loadingComponent:G}=K(),J=I||G,{showSpacer:Y,spacerKey:Q,triggerSpacer:X,handleSpacerComplete:Z}=(()=>{const[e,t]=i(!1),[n,s]=i(0);return{showSpacer:e,spacerKey:n,triggerSpacer:()=>{t(!0),s(e=>e+1)},handleSpacerComplete:()=>{t(!1)}}})(),{scrollContainerRef:ee,shouldAutoScrollRef:te,scrollToBottom:se,isAtBottom:oe}=(({onGradientChange:e,isStreaming:t})=>{const n=s(null),i=s(!0),o=s(!1),l=a(()=>{const e=n.current;e&&(e.scrollTop=e.scrollHeight)},[]),c=a(()=>{const e=n.current;return!!e&&50>e.scrollHeight-e.scrollTop-e.clientHeight},[]),d=a(()=>{const t=n.current;if(!t)return;const s=t.scrollTop>20;s!==o.current&&(o.current=s,e&&e(s)),i.current=c()},[c,e]),u=a((e=>{let t=0;return function(...n){const s=Date.now();100>s-t||(t=s,e(...n))}})(d),[d]);return r(()=>{const e=n.current;if(e)return e.addEventListener("scroll",u),()=>e.removeEventListener("scroll",u)},[u]),r(()=>{if(!t)return;const e=setInterval(()=>{i.current&&l()},100);return()=>clearInterval(e)},[t,l]),{scrollContainerRef:n,shouldAutoScrollRef:i,scrollToBottom:l,isAtBottom:c}})({onGradientChange:z,isStreaming:"none"===e&&B}),ae="react-window"===e?(({estimateSize:e})=>function({defaultRowHeight:e,key:t}){const[n,s]=i({key:t,map:new Map});n.key!==t&&s({key:t,map:new Map});const{map:l}=n,c=a(()=>{let t=0;return l.forEach(e=>{t+=e}),0===t?e:t/l.size},[e,l]),d=a(t=>{const n=l.get(t);return void 0!==n?n:(l.set(t,e),e)},[e,l]),u=a((e,t)=>{s(n=>{if(n.map.get(e)===t)return n;const s=new Map(n.map);return s.set(e,t),{...n,map:s}})},[]),h=Zs(e=>{0!==e.length&&e.forEach(e=>{const{borderBoxSize:t,target:n}=e,s=n.getAttribute(or);tr(null!==s,`Invalid ${or} attribute value`);const r=parseInt(s),{blockSize:i}=t[0];i&&u(r,i)})}),[g]=i(()=>new ResizeObserver(h));r(()=>()=>{g.disconnect()},[g]);const m=a(e=>(e.forEach(e=>g.observe(e)),()=>{e.forEach(e=>g.unobserve(e))}),[g]);return o(()=>({getAverageRowHeight:c,getRowHeight:d,setRowHeight:u,observeRowElements:m}),[c,d,u,m])}({defaultRowHeight:e}))({estimateSize:t}):null,le=a(()=>{"virtuoso"!==e&&"tanstack"!==e&&("react-window"===e&&N.current?.scrollToBottomCustom?N.current.scrollToBottomCustom():"none"===e&&se())},[e,se]),ce=a(()=>{w&&setTimeout(()=>{X()},200)},[w,X]),{removeMessage:de,handleSendMessage:ue}=(({messageManager:e,sendMsg:t,shouldAutoScrollRef:n,onUserMessageSent:s})=>({removeMessage:a(t=>{e?.removeMessage&&e.removeMessage(t)},[e]),handleSendMessage:a(async e=>{n&&(n.current=!0),s&&s(),await t(e)},[t,n,s])}))({messageManager:F,sendMsg:E,scrollToBottom:le,shouldAutoScrollRef:te,onUserMessageSent:ce});return r(()=>{if(D)R(!1);else{if(A&&A.length>0&&!H){const e=setTimeout(()=>{R(!0)},100);return()=>clearTimeout(e)}A&&0!==A.length||R(!0)}},[D,A,H]),u(T,()=>({scrollToBottom:le,isAtBottom:oe,scrollContainer:ee.current,dynamicHeight:ae,listRef:N.current,sendMessage:ue,abort:W,isStreaming:B,isLoading:O,messages:A,messageManager:F}),[le,oe,ae,ue,W,B,O,A,F]),g("div",{className:"react-ai-agent-chat-core "+c,"data-theme":l?"dark":"light",style:{WebkitMaskImage:p,...d},children:D?g(J||ie,{}):A&&0!==A.length?m("div",{className:"react-chat-core-messages h-full w-full",style:{opacity:H?1:0,transition:"opacity 0.3s ease-out"},children:[g(ne,{showLoadMore:v,enableHistory:V,hasMoreMessages:U,messagesLength:A.length,error:_,isInitialLoading:D,loadMoreMessages:q,isLoadingMore:j}),(()=>{const t={messages:A,removeMessage:de,allowEditMessage:f,animationConfig:$,isLoading:O,isResponseStarted:P,showLoadingIndicator:y,isStreaming:B,showSpacer:w&&Y,spacerKey:Q,onSpacerComplete:Z};switch(e){case"virtuoso":return g(Ys,{height:k,width:C,listRef:N,shouldAutoScrollRef:te,...t});case"react-window":return g(lr,{dynamicHeight:ae,height:k,width:C,overscan:n,listRef:N,isStreaming:B,shouldAutoScrollRef:te,...t});case"tanstack":return g(dr,{height:k,width:C,isStreaming:B,shouldAutoScrollRef:te,...t});default:return g(ur,{scrollToBottom:le,shouldAutoScrollRef:te,isStreaming:B,scrollContainerRef:ee,height:k,width:C,...t})}})()]}):x&&g("div",{style:{opacity:H?1:0,height:"100%",width:"100%",transition:"opacity 0.3s ease-out"},children:g(re,{WelcomeComponent:b,error:_,isPanelOpen:L})})})});hr.displayName="ChatCore";var gr=c(hr);const mr=({todos:e=[]})=>e&&0!==e?.length?g("div",{className:"react-ai-agent-queue-manager flex w-[calc(100%-50px)] ml-[5px] items-end gap-2 top-0 z-9 absolute h-0",children:m("div",{className:"react-ai-agent-queue-manager-wrapper flex items-center w-full relative bottom-0",children:[g("div",{className:"react-ai-agent-queue-manager-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay border-b-0 rounded-t-[15px] "}),g("div",{className:"react-ai-agent-queue-manager-content flex items-center gap-2 w-full p-1 py-[5px] z-99"})]})}):null,pr=({children:e,content:t,visible:n})=>n?m("div",{className:"react-ai-agent-tooltip-wrapper relative",children:[e,m("div",{className:"react-ai-agent-tooltip absolute bottom-full right-0 mb-2 w-64 p-3 bg-theme-surface rounded-lg shadow-lg z-50 backdrop-blur-sm",children:[g("div",{className:"react-ai-agent-tooltip-content text-theme-secondary text-sm space-y-2",children:t}),g("div",{className:"react-ai-agent-tooltip-arrow absolute top-full right-4 w-2 h-2 bg-theme-surface transform rotate-45 translate-y-[-4px]"})]})]}):e,fr=()=>{const[e,t]=i(!1),{sessionMetrics:n,usedTokens:s,contextLimit:r}=K(),o=(100*(s/r||0)).toFixed(2),a=e=>e?1e6>e?1e3>e?""+e:(e/1e3).toFixed(1)+"K":(e/1e6).toFixed(1)+"M":"0",l=m("div",{className:"space-y-2",children:[g("div",{className:"font-medium text-theme-primary border-b border-theme-tertiary pb-1",children:"Session Info"}),m("div",{className:"space-y-1 text-xs",children:[m("div",{className:"flex justify-between",children:[g("span",{className:"text-theme-quaternary",children:"Context size:"}),m("span",{children:[a(n?.contextUsed)," / ",a(n?.contextLimit)]})]}),m("div",{className:"flex justify-between",children:[g("span",{className:"text-theme-quaternary",children:"Session Tokens:"}),g("span",{children:a(n?.tokensUsed)})]}),m("div",{className:"flex justify-between",children:[g("span",{className:"text-theme-quaternary",children:"All time tokens:"}),g("span",{children:a(n?.allTimeTokens)})]}),m("div",{className:"flex justify-between",children:[g("span",{className:"text-theme-quaternary",children:"Requests:"}),g("span",{children:a(n?.requests)})]})]})]});return g(pr,{content:l,visible:e,children:m("div",{className:"react-ai-agent-progress-bar flex items-center gap-2 cursor-pointer",onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[m("span",{className:"react-ai-agent-progress-percentage text-theme-ghost font-light text-[12px] leading-[18px]",children:[o,"%"]}),m("div",{className:"react-ai-agent-progress-circle-wrapper relative w-4 h-4 flex items-center justify-center",children:[g("div",{className:"react-ai-agent-progress-circle-bg absolute inset-0 rounded-full bg-theme-muted"}),g("div",{className:"react-ai-agent-progress-circle-fill absolute inset-0 rounded-full",style:{background:`conic-gradient(var(--rca-text-faint) ${o}%, transparent 0)`}}),g("div",{className:"react-ai-agent-progress-circle-inner absolute inset-0.5 rounded-full bg-secondary"})]})]})})},xr=({attachedFiles:e=[],removeFile:t})=>{const{currentSelectedFile:n,setIsHoldEnabled:s,setCurrentSelectedFile:r,manuallyAddedFiles:i=[],setManuallyAddedFiles:o=()=>{}}=K(),a=[...n?[n]:[],...i,...e];return m("div",{className:"react-ai-agent-chat-bar flex items-center w-full mb-2 justify-between",children:[m("div",{className:"react-ai-agent-chat-bar-left flex items-center",children:[a.length>0&&g(yr,{files:a,handleRemoveFile:e=>{"object"==typeof e&&e.id?t&&t(e.id):e===n?(r(null),s(!1)):o(t=>t.filter(t=>t!==e))}}),m("button",{className:"react-ai-agent-context-button text-theme-primary hover:opacity-100 opacity-25 mr-2 flex items-center gap-1 whitespace-nowrap right-0 z-9 text-[12px] leading-relaxed ",children:[g("span",{className:"react-ai-agent-context-button-icon",children:te("add",20,"currentColor",{marginLeft:"-5px"})}),0===a.length&&g("span",{className:"react-ai-agent-context-button-label",children:"Context"})]})]}),g("div",{className:"react-ai-agent-chat-bar-right",children:g(fr,{})})]})},vr=({file:e,handleRemoveFile:t})=>{const[n,s]=i(!1),r="object"==typeof e&&e.id,o=r?e.name:e.split("/").pop(),a=r?e.id:e;return m("div",{className:"react-ai-agent-file-item flex items-center gap-2 px-2 py-[2px] bg-theme-subtle rounded-full cursor-pointer relative border border-theme-subtle",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),children:[n?g("button",{className:"react-ai-agent-file-item-remove w-[16px] opacity-50 hover:opacity-100 -ml-[2px] -mr-[2px] h-[16px]",onClick:n=>{n.stopPropagation(),t(e)},children:g("span",{className:"react-ai-agent-file-item-remove-icon",children:te("close",16,"currentColor")})}):g("div",{className:"react-ai-agent-file-item-icon-wrapper",children:r&&e.preview?g("img",{src:e.preview,alt:o,className:"react-ai-agent-file-item-preview w-3 h-4 object-cover rounded",style:{marginRight:0,width:"12px",height:"16px"}}):g(FileIcon,{fileName:o,style:{marginRight:0,width:"12px",height:"16px"}})}),g("div",{className:"react-ai-agent-file-item-name text-theme-quaternary hover:text-theme-primary text-[12px] leading-relaxed whitespace-nowrap truncate max-w-[100px]",children:o})]},a)},yr=({files:e,handleRemoveFile:t})=>g("div",{className:"react-ai-agent-file-items flex items-center gap-2 mr-2",children:e.map(e=>g(vr,{file:e,handleRemoveFile:t},"object"==typeof e&&e.id?e.id:e))}),wr=()=>{const[e,t]=i(0),n=s(),o=s(0),a=s(0),l=s(null),c=s(1);return r(()=>{const e=()=>{if(l.current){const{width:e,height:t}=l.current.getBoundingClientRect();c.current=e/t}};e();const t=new ResizeObserver(e);return l.current&&t.observe(l.current),()=>{t.disconnect()}},[]),r(()=>{a.current=performance.now(),o.current=e;const s=r=>{const i=r-a.current;a.current=r,o.current+=i/1e3*360,360>o.current||(o.current-=360);const l=o.current*(Math.PI/180),d=c.current,u=Math.round((Math.atan2(Math.sin(l),Math.cos(l)/d)*(180/Math.PI)+360)%360);3>Math.abs(u-e)||t(u),n.current=requestAnimationFrame(s)};return n.current=requestAnimationFrame(s),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[]),g("div",{ref:l,className:"react-ai-agent-loader-animation w-full h-full absolute inset-0 rounded-[inherit]",children:g("div",{className:"glowing pointer-events-none absolute inset-0 rounded-[inherit] opacity-100 transition-opacity safari:!hidden style_glowingEffect__yGXeX",style:{"--blur":"1px","--spread":"30","--active":"1","--start":e,display:"flex"},children:g("div",{className:"style_glow__i4Qpo"})})})},br="image/*,video/*,audio/*,.pdf,.doc,.docx,.txt,.md,.json,.js,.ts,.jsx,.tsx,.py,.html,.css,.xml,.csv";function Ir(){const[e,t]=i([]),n=s(null),r=a(async e=>{const t=await e.arrayBuffer(),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")},[]),o=a(async n=>{const s=[];for(const t of n){if(e.some(e=>e.name===t.name&&e.size===t.size&&e.type===t.type))continue;let n=!1;if(5242880>t.size)try{const i=await r(t);e.some(e=>e.hash===i)||(s.push({file:t,id:Date.now()+Math.random(),name:t.name,size:t.size,type:t.type,hash:i,preview:t.type.startsWith("image/")?URL.createObjectURL(t):null}),n=!0)}catch(i){}n||s.push({file:t,id:Date.now()+Math.random(),name:t.name,size:t.size,type:t.type,preview:t.type.startsWith("image/")?URL.createObjectURL(t):null})}s.length>0&&t(e=>[...e,...s])},[e,r]),l=a(e=>{const t=Array.from(e.target.files||[]);t.length>0&&o(t),e.target.value=""},[o]),c=a(e=>{const t=Array.from(e.clipboardData?.items||[]).filter(e=>"file"===e.kind).map(e=>e.getAsFile()).filter(Boolean);t.length>0&&(e.preventDefault(),o(t))},[o]),d=a(e=>{t(t=>{const n=t.filter(t=>t.id!==e),s=t.find(t=>t.id===e);return s?.preview&&URL.revokeObjectURL(s.preview),n})},[]),u=a(()=>{t(e=>(e.forEach(e=>{e.preview&&URL.revokeObjectURL(e.preview)}),[]))},[]);return{attachedFiles:e,fileInputRef:n,onFileSelect:l,onPaste:c,removeFile:d,clearFiles:u}}const Sr=()=>{const{streamError:e,clearStreamError:t,retryLastMessage:n,sendRequestCallback:s,triggerLoadingStates:r}=K(),[o]=i(e?.choices||[{id:"retry",label:"Retry"},{id:"cancel",label:"Cancel"}]);return e?g("div",{className:"react-ai-agent-stream-error w-full mb-3",children:m("div",{className:"react-ai-agent-error-content flex w-full justify-between items-center gap-3 px-3 py-2 bg-theme-faint rounded-lg border-l-2 border-[#ef4444]",children:[g("div",{className:"react-ai-agent-error-message-wrapper",children:g("div",{className:"react-ai-agent-error-message text-[12px] text-theme-primary font-medium",children:e.message||"An error occurred during streaming"})}),g("div",{className:"react-ai-agent-error-actions flex gap-2 items-center",children:o&&o.length>0&&o.map(i=>g("button",{onClick:()=>(async i=>{"retry"===i?"connection_error"===e.errorType?await n():(r(),s({type:"stream_error",callback:"retry",requestId:e.requestId})):"cancel"===i&&(e.requestId&&s({type:"stream_error",callback:"cancel",requestId:e.requestId}),t())})(i.id),className:`react-ai-agent-error-action react-ai-agent-error-action-${i.id} text-[11px] font-medium px-3 py-1 rounded-md transition-all duration-200\n ${"retry"===i.id?"text-theme-primary hover:text-theme-secondary underline underline-offset-2":"cancel"===i.id?"text-theme-subtle hover:text-theme-tertiary":"text-theme-tertiary hover:text-theme-primary"}\n `,children:i.label},i.id))})]})}):null},kr=h(({onSendMessage:e,miniMode:t=!1,isStreaming:n,abort:o,todos:a},l)=>{const[c,d]=i(""),h=s(null),{attachedFiles:p,fileInputRef:f,onFileSelect:x,onPaste:v,removeFile:y,clearFiles:w}=Ir();r(()=>{h.current&&(h.current.style.height="auto",h.current.style.height=Math.min(h.current.scrollHeight,150)+"px")},[c]),u(l,()=>({focus:()=>{h.current?.focus()}}),[]);const b=t=>{t.preventDefault(),(c.trim()||p.length>0)&&(e({message:c,attachedFiles:p}),d(""),w(),h.current&&(h.current.style.height="auto"))};return g("div",{className:"react-ai-agent-input absolute mx-auto bottom-0 w-full p-[15px] right-0 left-0 max-w-[600px] z-2",children:m("div",{className:"react-ai-agent-input-wrapper mx-auto min-h-[120px] relative",style:t?{minHeight:"110px"}:{},children:[n&&g("div",{className:"absolute inset-0 pointer-events-none rounded-[15px]",style:{zIndex:1},children:g(wr,{})}),g("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay rounded-[15px]"}),m("div",{className:"react-ai-agent-input-content pt-[15px] px-[20px] mx-auto min-h-[120px] relative z-99",style:{zIndex:2},children:[g(mr,{todos:a}),g(Sr,{}),g(xr,{attachedFiles:p,removeFile:y}),g("div",{className:"react-ai-agent-input-textarea-wrapper relative pb-[50px]",children:g("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:h,value:c,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),b(e))},onPaste:v,placeholder:"Type a message...",className:"react-ai-agent-textarea w-full text-[14px] text-theme-primary pr-12 min-h-[40px] max-h-[150px] resize-none outline-none bg-transparent",rows:1})}),m("div",{className:"react-ai-agent-input-actions flex items-center justify-between mt-auto bottom-[15px] absolute w-[calc(100%-40px)]",children:[m("div",{className:"react-ai-agent-input-actions-left flex items-center",children:[g("input",{ref:f,type:"file",multiple:!0,accept:br,onChange:x,className:"react-ai-agent-file-input hidden"}),m("button",{type:"button",onClick:()=>f.current?.click(),className:"react-ai-agent-attach-button flex justify-center items-center cursor-pointer text-theme-primary rounded-full transition-colors hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed",children:[te("attach",18,"currentColor"),g("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})]}),m("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[m("button",{type:"button",className:"react-ai-agent-agent-button flex justify-center p-1 px-2 mr-2 items-center cursor-pointer text-theme-primary rounded-full transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[te("brain",18,"currentColor"),g("span",{className:"react-ai-agent-agent-label text-[12px] mx-2 text-theme-quaternary font-[300] -mt-[2px]",children:"Agent"}),te("arrowDown",16,"currentColor",{transform:"rotate(180deg)"})]}),g("button",{type:"button",onClick:e=>{n?o():b(e)},className:"react-ai-agent-send-button w-[30px] h-[30px] flex justify-center items-center cursor-pointer bg-inverse text-inverse rounded-full transition-colors disabled:opacity-50 disabled:cursor-not-allowed",disabled:!c.trim()&&!n,children:te(n?"square":"send",n?15:20,"currentColor")})]})]})]})]})})});kr.displayName="ChatInputDefault";var Cr=c(kr),Tr=c(({historyOpen:e,setHistoryOpen:t,isDark:n=!1,onCreateSession:s})=>{const[r,o]=i(!1),{headerComponent:a}=K();return m("div",{className:"react-ai-agent-header flex justify-between items-center py-2 px-5 absolute top-0 left-0 right-0 z-10",children:[m("div",{className:"react-ai-agent-header-left flex items-center gap-4 opacity-50",children:[g("button",{className:"react-ai-agent-header-new-chat flex items-center cursor-pointer hover:opacity-80",style:{opacity:r?.5:1,cursor:r?"progress":"pointer"},disabled:r,onClick:async({replace:e=!1}={})=>{if(s)try{o(!0),await s({replace:e})}catch(t){}finally{o(!1)}},children:te("add",25,n?"#fff":"#000")}),g("div",{className:"react-ai-agent-header-history flex items-center cursor-pointer hover:opacity-80",onClick:e?()=>t(!1):()=>t(!0),children:te(e?"close":"history",18,n?"#fff":"#000")})]}),a&&a(),g("div",{className:"react-ai-agent-header-right w-[80px]"})]})}),Mr=c(({isDark:e=!1,allowEditMessage:t=!1,useWebSocket:n=!1,children:r,onCreateSession:o,className:l="h-full w-full",coreProps:c={},inputProps:d={}})=>{const[u,h]=i(!1),p=s(null),{sendMsg:f,isStreaming:x,abort:v}=K(),y=a(async e=>{p.current?.sendMessage?await p.current.sendMessage(e):(await f(e),setTimeout(()=>{p.current?.scrollToBottom()},100))},[f]);return m("div",{className:"react-ai-agent flex flex-col h-full relative chat-panel "+l,"data-theme":e?"dark":"light",children:[g(Tr,{historyOpen:u,setHistoryOpen:h,useWebSocket:n,isDark:e,onCreateSession:o}),m("div",{className:"relative flex-grow w-full max-w-[600px] mx-auto h-full min-w-[300px]",children:[g(gr,{ref:p,isDark:e,allowEditMessage:t,className:"px-[15px]",...c}),g(Cr,{onSendMessage:y,isStreaming:x,abort:v,...d})]}),r]})});const zr={collapsed:{width:"280px",height:"60px",borderRadius:"50px",padding:"px-5 py-3",gap:"gap-2",showAttach:!1,showAgent:!1,showTopContent:!0,sendButtonSize:34,compact:!1},expanded:{width:"500px",height:"auto",minHeight:"120px",borderRadius:"20px",padding:"pt-[15px] px-[20px] pb-0",gap:"",showAttach:!0,showAgent:!0,showTopContent:!0,sendButtonSize:30,compact:!1},collapsedCompact:{width:"280px",height:"60px",borderRadius:"50px",padding:"px-3 py-3",gap:"gap-2",showAttach:!1,showAgent:!1,showTopContent:!1,sendButtonSize:34,compact:!0},expandedCompact:{width:"600px",height:"60px",minHeight:"60px",borderRadius:"50px",padding:"px-3 py-3",gap:"gap-2",showAttach:!0,showAgent:!1,showTopContent:!1,sendButtonSize:34,compact:!0}},Hr=h(({onSendMessage:e,miniMode:t=!1,isStreaming:n,abort:o,todos:a,variant:l="default",placeholder:c="Type a message...",collapsed:d=!1,onExpand:h,position:p="bottom-center",compact:f},x)=>{const[v,y]=i(""),[w,b]=i(!1),I=s(null),{attachedFiles:S,fileInputRef:k,onFileSelect:C,onPaste:T,removeFile:M,clearFiles:z}=Ir();r(()=>{!d&&I.current&&(I.current.style.height="auto",I.current.style.height=Math.min(I.current.scrollHeight,150)+"px")},[v,d]),u(x,()=>({focus:()=>{I.current?.focus()}}),[]);const H=t=>{t.preventDefault(),(v.trim()||S.length>0)&&(e({message:v,attachedFiles:S}),y(""),z(),!d&&I.current&&(I.current.style.height="auto"))},R=f?d?zr.collapsedCompact:zr.expandedCompact:d?zr.collapsed:zr.expanded;return m("div",{className:"react-ai-agent-input-morph",style:{width:R.width,transition:"width 0.4s cubic-bezier(0.4, 0, 0.2, 1)"},"data-theme":"dark",children:[n&&!d&&g("div",{className:"absolute inset-0 pointer-events-none",style:{height:R.height,minHeight:R.minHeight||R.height,borderRadius:R.borderRadius,zIndex:1,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, border-radius "+(d?"0.15s cubic-bezier(0.4, 0, 0.2, 1) 0.3s":"0.15s cubic-bezier(0.4, 0, 0.2, 1)")},children:g(wr,{})}),m("div",{className:"react-ai-agent-input-wrapper relative",style:{height:R.height,minHeight:R.minHeight||R.height,zIndex:2,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s",overflow:"hidden"},children:[g("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay",style:{borderRadius:R.borderRadius,transition:d?"border-radius 0.15s cubic-bezier(0.4, 0, 0.2, 1) 0.3s":"border-radius 0.15s cubic-bezier(0.4, 0, 0.2, 1)"}}),m("div",{className:"relative z-10 h-full "+R.padding,style:{transition:"padding 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},children:[R.showTopContent&&m("div",{style:{opacity:d?0:1,height:d?0:"auto",overflow:"hidden",pointerEvents:d?"none":"auto",transition:d?"opacity 0.12s ease-out, height 0.15s ease-out":"opacity 0.3s ease-out 0.4s, height 0.3s ease-out 0.15s"},children:[g(mr,{todos:a}),g(Sr,{}),g(xr,{attachedFiles:S,removeFile:M})]}),m("div",{className:"flex items-center w-full "+(R.compact||d?R.gap:""),style:{position:R.compact||d?"relative":"static"},children:[g("input",{ref:k,type:"file",multiple:!0,accept:br,onChange:C,className:"react-ai-agent-file-input hidden"}),R.compact&&R.showAttach&&g("div",{className:"flex-shrink-0",style:{opacity:d?0:1,width:d?0:"auto",overflow:"hidden",pointerEvents:d?"none":"auto",transition:d?"opacity 0.12s ease-out, width 0.12s ease-out":"opacity 0.3s ease-out 0.45s, width 0.3s ease-out 0.45s"},children:g("button",{type:"button",onClick:()=>k.current?.click(),className:(R.compact?"-mr-2":"")+" react-ai-agent-attach-button flex justify-center items-center cursor-pointer text-theme-primary rounded-full transition-colors hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed w-[30px] h-[30px]",children:te("attach",R.compact?20:18,"currentColor")})}),g("div",{className:R.compact||d?"flex-1":"relative pb-[50px] w-full",style:{transition:"padding 0.3s ease-out 0.15s",marginTop:d&&!R.compact?"2px":void 0},children:g("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:I,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),H(e))},onPaste:T,onFocus:()=>{b(!0),d&&h&&h()},onBlur:()=>{b(!1)},placeholder:c,className:"text-[14px] text-theme-primary resize-none outline-none bg-transparent "+(R.compact||d?"w-full pr-0 pl-3":"w-full min-h-[40px] max-h-[150px] pr-12"),style:{overflow:"auto",height:R.compact||d?"30px":void 0,maxHeight:R.compact||d?"30px":void 0,paddingTop:R.compact||d?"7px":void 0,paddingBottom:R.compact||d?"3px":void 0,lineHeight:R.compact||d?"16px":void 0,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},rows:1})}),m("div",{className:"flex items-center "+(R.compact||d?"flex-shrink-0":"justify-between"),style:{position:R.compact||d?"static":"absolute",bottom:R.compact||d?"auto":"15px",left:R.compact||d?"auto":"20px",right:R.compact||d?"auto":"20px",width:R.compact||d?"auto":"calc(100% - 40px)"},children:[!R.compact&&g("div",{className:"react-ai-agent-input-actions-left flex items-center",style:{opacity:d||!R.showAttach?0:1,width:d||!R.showAttach?0:"auto",overflow:"hidden",pointerEvents:d||!R.showAttach?"none":"auto",transition:d?"opacity 0.12s ease-out, width 0.12s ease-out":"opacity 0.3s ease-out 0.45s, width 0.3s ease-out 0.45s"},children:m("button",{type:"button",onClick:()=>k.current?.click(),className:"react-ai-agent-attach-button flex justify-center items-center cursor-pointer text-theme-primary rounded-full transition-colors hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed",children:[te("attach",18,"currentColor"),g("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})}),m("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[g("div",{style:{opacity:d||!R.showAgent?0:1,width:d||!R.showAgent?0:"auto",overflow:"hidden",transition:d?"opacity 0.12s ease-out, width 0.12s ease-out":"opacity 0.3s ease-out 0.45s, width 0.3s ease-out 0.45s"},children:R.showAgent&&m("button",{type:"button",className:"react-ai-agent-agent-button flex justify-center p-1 px-2 mr-2 items-center cursor-pointer text-theme-primary rounded-full transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap",children:[te("brain",18,"currentColor"),g("span",{className:"react-ai-agent-agent-label text-[12px] mx-2 text-theme-quaternary font-[300] -mt-[2px]",children:"Agent"}),te("arrowDown",16,"currentColor",{transform:"rotate(180deg)"})]})}),g("button",{type:"button",onClick:e=>{n?o():H(e)},className:"react-ai-agent-send-button flex justify-center items-center cursor-pointer bg-inverse text-inverse rounded-full hover:scale-110",disabled:!v.trim()&&!n,style:{width:R.sendButtonSize+"px",height:R.sendButtonSize+"px",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, transform 0.2s ease-out"},children:te(n?"square":"send",n?15:d?18:20,"currentColor")})]})]})]})]})]})]})});Hr.displayName="ChatInput";var Rr=c(Hr),Nr=c(({allowEditMessage:e=!1,children:t,placeholder:n="Ask me anything...",position:o="bottom-center",isDark:l,compact:c,coreProps:d={},inputProps:u={}})=>{const[h,p]=i(!1),[f,x]=i(!1),[v,y]=i(!1),[w,b]=i(!1),I=s(null),S=s(null),k=s([]),{isStreaming:C,abort:T}=K(),M=a(()=>{k.current.forEach(e=>clearTimeout(e)),k.current=[]},[]),z=a(async e=>{I.current?.sendMessage?await I.current.sendMessage(e):setTimeout(()=>{I.current?.scrollToBottom()},100)},[]),H=a(()=>{M(),x(!1),y(!1),p(!0),b(!1);const e=setTimeout(()=>{b(!0)},350);k.current.push(e);const t=setTimeout(()=>{S.current?.focus()},400);k.current.push(t)},[M]),R=a(()=>{M(),x(!0),p(!1);const e=setTimeout(()=>{y(!0)},250);k.current.push(e);const t=setTimeout(()=>{b(!1),x(!1),y(!1)},500);k.current.push(t)},[M]);r(()=>{const e=e=>{"Escape"===e.key&&h&&R()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[h,R]),r(()=>()=>{M()},[M]);const N=h||f;return m("div",{className:"react-ai-agent","data-theme":l?"dark":"light",children:[N&&g("div",{className:"fixed inset-0 bg-black/80 z-40 transition-opacity duration-300 ease-in-out "+(v?"opacity-0":"opacity-100"),style:{backdropFilter:"blur(20px)"},onClick:R}),N&&g("div",{className:"fixed inset-0 z-45 flex items-center justify-center p-8",style:{pointerEvents:"none"},children:m("div",{className:"relative w-full max-w-3xl rounded-3xl",style:{height:"100vh",pointerEvents:"auto"},children:[w&&g("div",{className:"absolute inset-0 px-4 py-4 rounded-3xl overflow-hidden",style:{opacity:f?0:1,transition:"opacity 0.25s ease-out"},children:g(gr,{ref:I,isDark:l,allowEditMessage:e,className:"h-full w-full",...d})}),t]})}),g("div",{className:"fixed bottom-8 z-50 "+(()=>{switch(o){case"bottom-right":return"right-8";case"bottom-left":return"left-8";default:return"left-1/2 -translate-x-1/2"}})(),children:g(Rr,{ref:S,collapsed:!h,onExpand:H,onSendMessage:z,isStreaming:C,abort:T,variant:h?"pill":"collapsed",placeholder:n,position:o,compact:c,...u})})]})});class Er{constructor(e){this.tokenManager=e||new z,this.createSessionCallback=null,this.onSessionCreated=null}setCreateSessionCallback(e){this.createSessionCallback=e}setOnSessionCreated(e){this.onSessionCreated=e}async createSession(e={}){if(!this.createSessionCallback)throw Error("No session creation callback provided. Use SessionManager.setCreateSessionCallback()");try{const t=await this.createSessionCallback(e);if(!t||!t.sessionId)throw Error("Invalid session data: missing sessionId");if(!t.accessToken)throw Error("Invalid session data: missing accessToken");return tokenManager.setAuth(t),this.onSessionCreated&&this.onSessionCreated(t),t}catch(t){throw t}}getSessionId(){return tokenManager.getSessionId()}clearSession(){tokenManager.clear()}}function Ar(e,t){return JSON.stringify({event:e,data:t})}function Fr(e,t,n=!0){return Ar("ai_response",{messageId:e,content:t,isLive:n})}function Or(e,t,n,s=null){return Ar("status_update",{messageId:e,action:t,status:n,data:s})}function Br(e,t,n=!0){return Ar("ai_thinking",{messageId:e,content:t,isLive:n})}function Lr(e,t,n){return Ar("tool_call",{messageId:e,toolName:t,args:n})}function _r(){return Ar("ai_response_end",{status:"end"})}function Dr(e,t=""){return Ar("stream_error",{errorType:"error",error:e,message:t})}function Pr(e,t){try{if(e.startsWith("data: ")){const n=e.slice(6);if("[DONE]"===n)return _r();const s=JSON.parse(n),r=s.choices[0]?.delta?.content;if(r)return Fr(t,r,!0)}}catch(n){}return null}function Wr(e,t=null){return Array.isArray(e)?e.map(e=>t?t(e):{messageId:e.id||e.messageId||e.uuid||Date.now()+"",type:"assistant"===e.role||"agent"===e.type||"bot"===e.sender?"agent":"user",content:e.content||e.text||e.message||e.body||"",timestamp:e.timestamp||e.created_at||e.createdAt||Date.now()}):[]}function qr(e){try{const t=e.startsWith("data:")?e.slice(5).trim():e.trim();return t?JSON.parse(t):null}catch(t){return null}}function jr(e,t,n={}){const i=q(),o=s(new Map),l=!("string"!=typeof e||t||n&&0!==Object.keys(n).length),c=l?e:n.instanceId||null,d=s(t),u=s(n);r(()=>{d.current=t,u.current=n}),r(()=>{if(l)return;const n=[];if("object"!=typeof e||t){if("string"==typeof e&&t){const t=i.register(e,(...e)=>d.current(...e),{mode:u.current.mode||"dual",animated:!1!==u.current.animated,subscriptionMode:u.current.subscriptionMode||"delta",instanceId:u.current.instanceId||c});n.push(t)}}else Object.entries(e).forEach(([e,t])=>{const s=i.register(e,(...e)=>t.handler(...e),{mode:t.mode||"dual",animated:!1!==t.animated,subscriptionMode:t.subscriptionMode||"delta",instanceId:t.instanceId||c});n.push(s)});return()=>{n.forEach(e=>e())}},[e,i,c]);const h=a((e,t,n={})=>{const s={...n,instanceId:n.instanceId||c},r=i.register(e,t,s);return o.current.set(e,r),r},[i,c]),g=a(e=>{const t=o.current.get(e);t&&(t(),o.current.delete(e))},[]),m=a(()=>i.getActiveSessions(),[i]),p=a(e=>i.handlers[e],[i]),f=a(()=>Object.entries(i.handlers).map(([e,t])=>({action:e,...t})),[i]);return{register:h,unregister:g,getActiveSessions:m,getHandler:p,getAllHandlers:f}}const Ur=({modes:e=[],activeMode:t,onModeChange:n,isDark:s=!1})=>e&&e.length>1?g("div",{className:"react-ai-agent-mode-toggle toggle-container flex items-center bg-theme-faint rounded-full !ml-5 flex-shrink-0 h-[35px]",style:{padding:"4px"},children:e.map(e=>g("button",{onClick:()=>n(e.id),className:`react-ai-agent-mode-button ${t===e.id?"react-ai-agent-mode-button-active":"react-ai-agent-mode-button-inactive"} relative px-3 py-1 text-[12px] font-medium rounded-full transition-all duration-200\n ${t===e.id?"bg-background text-theme-primary":"text-theme-subtle hover:text-theme-tertiary hover:bg-theme-subtle"}\n `,children:m("div",{className:"react-ai-agent-mode-button-content flex items-center gap-1.5",children:[g("span",{className:"react-ai-agent-mode-button-icon",children:e.icon}),g("span",{className:"react-ai-agent-mode-button-label",children:e.label})]})},e.id))}):null;export{I as BaseApiHandler,gr as ChatCore,Tr as ChatHeader,Rr as ChatInput,V as ChatInstanceContext,ie as ChatLoadingMock,X as ChatProvider,S as DefaultApiHandler,Mr as DefaultPanel,Nr as FloatingPanel,W as ForwardingManager,$s as LoadingResponse,Vs as MessageItem,H as MessageManager,Ur as ModeToggle,Er as SessionManager,js as ShimmerText,se as StartChat,Us as StatusBlock,N as StatusHandlerRegistry,M as StreamService,z as TokenManager,k as WebSocketService,Wr as adaptHistoryMessages,Pr as adaptOpenAIStream,Fr as createAIResponse,_r as createEndEvent,Dr as createErrorEvent,Ar as createSSEEvent,Or as createStatusUpdate,Br as createThinkingEvent,Lr as createToolCallEvent,q as getGlobalForwardingManager,A as getGlobalStatusRegistry,qr as parseSSEChunk,U as resetGlobalForwardingManager,j as setGlobalForwardingManager,K as useChatContext,jr as useForwarding,$ as useStatusSubscription};
|
|
1
|
+
import e,{createContext as t,useContext as s,useRef as n,useEffect as a,useState as r,useMemo as i,useCallback as o,memo as c,forwardRef as l,useImperativeHandle as d}from"react";import{jsx as h,jsxs as u,Fragment as g}from"react/jsx-runtime";import{Virtuoso as m}from"react-virtuoso";import{Streamdown as p}from"streamdown";import{Prism as f}from"react-syntax-highlighter";import y from"react-markdown";import{motion as x}from"framer-motion";import{useDynamicRowHeight as w,List as b}from"react-window";import{useVirtualizer as v}from"@tanstack/react-virtual";class k{constructor(e={}){this.config=e,this.abortController=null}async sendMessage(e,t=null){throw Error("Implement sendMessage()")}async getHistory(e={}){throw Error("Implement getHistory()")}async uploadFiles(e,t){return null}abort(){this.abortController&&(this.abortController.abort(),this.abortController=null)}async abortRequest(e){}}class S extends k{constructor(e={}){super({chatUrl:"https://api.oblien.com/ai/chat/send",historyUrl:"https://api.oblien.com/ai/session/history",uploadUrl:"https://api.oblien.com/ai/chat/upload",abortUrl:"https://api.oblien.com/ai/chat/abort",...e}),this.tokenManager=e.tokenManager||null}async getHeaders(){const e={"Content-Type":"application/json"};return this.tokenManager?e.Authorization="Bearer "+await this.tokenManager.getAccessToken():this.config.token&&(e.Authorization="Bearer "+this.config.token),e}async sendMessage(e,t=null){this.abort(),this.abortController=new AbortController;try{const s=await this.getHeaders();t&&(s.Accept="text/event-stream");const n=await fetch(this.config.chatUrl,{method:"POST",headers:s,body:JSON.stringify(e),signal:this.abortController.signal,credentials:this.config.credentials||"same-origin"});if(!n.ok){const e=await n.json().catch(()=>({error:"Request failed"}));return t&&t(JSON.stringify({event:"stream_error",data:{errorType:"http_error",error:e.error,message:e.message}})),{status:!1,error:e.error}}if(!t)return{status:!0,data:await n.json()};const a=n.body.getReader(),r=new TextDecoder;let i="";for(;;){const{value:e,done:s}=await a.read();if(s){t(JSON.stringify({event:"ai_response_end",data:{status:"end"}}));break}i+=r.decode(e,{stream:!0});const n=i.split("\n");i=n.pop()||"";for(const a of n)a.trim()&&t(a)}return{status:!0}}catch(s){return t&&t(JSON.stringify({event:"stream_error",data:{errorType:"connection_error",error:s.message}})),{status:!1,error:s.message}}}async getHistory(e={}){try{const t=await this.getHeaders(),{offset:s=0,limit:n=20,sessionId:a}=e,r=`${this.config.historyUrl}?offset=${s}&limit=${n}&sessionId=${a}`,i=await fetch(r,{headers:t,credentials:this.config.credentials||"same-origin"});return i.ok?await i.json():{error:"Failed to load history"}}catch(t){return{error:t.message}}}async uploadFiles(e,t){if(!e?.length)return null;const s=new FormData;e.forEach(e=>s.append("files",e.file,e.name));const n={};this.tokenManager?n.Authorization="Bearer "+await this.tokenManager.getAccessToken():this.config.token&&(n.Authorization="Bearer "+this.config.token);const a=await fetch(this.config.uploadUrl,{method:"POST",headers:n,body:s,signal:t,credentials:this.config.credentials||"same-origin"});if(!a.ok)throw Error("Upload failed");return(await a.json()).uploadId}async abortRequest(e){if(e)try{const t=await this.getHeaders();await fetch(this.config.abortUrl,{method:"POST",headers:t,body:JSON.stringify({sessionId:e}),credentials:this.config.credentials||"same-origin"})}catch(t){}}}const M=new class{constructor({socketUrl:e}={}){this.socket=null,this.listeners=new Map,this.bufferedEvents=new Map,this.bufferableEventTypes=new Set([]),this.reconnectAttempts=0,this.maxReconnectAttempts=5e3,this.reconnectTimeout=3e3,this.socketUrl=e,this.requireAppRunning=null}setSocketUrl(e){this.socketUrl=e}_processBinaryData(e){this.notifyListeners("binary",{data:e})}async connect(e,t=[]){return this.socket&&this.disconnect(),e||(e=await getToken()),new Promise(async(s,n)=>{try{const n=new URL(this.socketUrl+"?token="+e+"&"+t.join("&"));this.socket=new WebSocket(n),this.socket.onopen=()=>{this.reconnectAttempts=0,this.reconnectTimeout=3e3,this.notifyListeners("connect",{connected:!0}),s(!0)},this.socket.onmessage=async e=>{try{if(e.data instanceof Blob){const t=new FileReader;return t.onload=()=>{this._processBinaryData(t.result)},void t.readAsArrayBuffer(e.data)}if(e.data instanceof ArrayBuffer)return void this._processBinaryData(e.data);if("string"==typeof e.data){const t=JSON.parse(e.data);if(this._checkPendingRequests(t))return;return this.notifyListeners("message",t),this.requireAppRunning?.events.includes(t.type)&&!this.listeners.has(t?.type)&&t?.type&&this.requireAppRunning&&"running"!==this.requireAppRunning?.status&&await this.requireAppRunning.callback(t),void(t.type&&this.notifyListeners(t.type,t))}}catch(t){}},this.socket.onclose=s=>{this.notifyListeners("disconnect",{code:s.code,reason:s.reason}),1e3!==s.code&&this.attemptReconnect(e,t)},this.socket.onerror=e=>{this.notifyListeners("error",e)}}catch(a){}})}disconnect(){this.socket&&(this.notifyListeners("close",{code:1e3,reason:"User disconnected"}),this.socket.close(1e3,"User disconnected"),this.socket=null)}attemptReconnect(e,t){this.maxReconnectAttempts>this.reconnectAttempts&&this.socket?(this.reconnectAttempts++,this.notifyListeners("reconnectAttempt",{attempts:this.reconnectAttempts}),setTimeout(()=>{this.connect(e,t)},this.reconnectTimeout)):this.notifyListeners("reconnectFailed",{attempts:this.reconnectAttempts})}isConnected(){return this.socket&&this.socket.readyState===WebSocket.OPEN}sendAsync(e,t=3e4){return new Promise((s,n)=>{if(!this.isConnected())return n(Error("WebSocket is not connected"));const a=e.requestId||`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r={...e,requestId:a};this.pendingRequests||(this.pendingRequests=new Map),this.pendingRequests.set(a,{resolve:s,reject:n,timeoutId:setTimeout(()=>{this.pendingRequests.has(a)&&(this.pendingRequests.delete(a),n(Error(`Request ${a} timed out after ${t}ms`)))},t)}),this.send(r)})}_checkPendingRequests(e){if(!this.pendingRequests||!e.requestId)return!1;const t=this.pendingRequests.get(e.requestId);return!!t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e),!0)}send(e){return!!this.isConnected()&&(this.socket.send(JSON.stringify(e)),!0)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t),this.bufferedEvents.has(e)&&(this.bufferedEvents.get(e).forEach(e=>{try{t(e)}catch(s){}}),this.bufferedEvents.delete(e)),()=>this.off(e,t)}off(e,t){if(!this.listeners.has(e))return;const s=this.listeners.get(e),n=s.indexOf(t);-1!==n&&s.splice(n,1),0===s.length&&this.listeners.delete(e)}notifyListeners(e,t){const s=this.listeners.has(e);if(!s&&this.bufferableEventTypes.has(e))return this.bufferedEvents.has(e)||this.bufferedEvents.set(e,[]),void this.bufferedEvents.get(e).push(t);s&&this.listeners.get(e).forEach(e=>{try{e(t)}catch(s){}})}setAppServerStatus(e){this.requireAppRunning.status=e}setRequireAppRunning(e,t,s){return this.requireAppRunning={events:e,callback:t,status:s},()=>{this.requireAppRunning=null}}};class C{constructor(){this.buffer=""}feed(e){if(!e)return[];const t=this._tryDirectJson(e);if(t.length)return t;const s=this._tryDirectSSE(e);return s.length?s:(this.buffer+=e,this._fallbackExtract())}_tryDirectJson(e){const t=[];try{const s=JSON.parse(e);return s&&"object"==typeof s&&t.push(s),t}catch{}return e.includes("{")&&e.includes("}")?this._fallbackExtractFromText(e):[]}_tryDirectSSE(e){const t=[];for(let s of e.split("\n")){if(s=s.trim(),!s.startsWith("data:"))continue;const e=s.slice(5).trim();try{const s=JSON.parse(e);s&&"object"==typeof s&&t.push(s)}catch{}}return t}_fallbackExtract(){const e=this._fallbackExtractFromText(this.buffer);for(const t of e){const e=JSON.stringify(t),s=this.buffer.indexOf(e);-1!==s&&(this.buffer=this.buffer.slice(0,s)+this.buffer.slice(s+e.length))}return e}_fallbackExtractFromText(e){const t=[];let s=-1,n=0,a=!1,r=!1;for(let i=0;e.length>i;i++){const o=e[i];if(r)r=!1;else if("\\"===o)r=!0;else if('"'===o)a=!a;else if(!a)if("{"===o)0===n&&(s=i),n++;else if("}"===o&&(n--,0===n&&-1!==s)){const n=e.slice(s,i+1);try{const e=JSON.parse(n);t.push(e)}catch{}s=-1}}return t}}class I{constructor(){this.jsonStreamParser=new C}parseJsonStream(e){return this.jsonStreamParser.feed(e)}processRawChunk(e,t){try{const s=this.parseJsonStream(e);if(!s.length)return;for(const e of s){let s,n=e.event||"response";s=e.type&&("started"===e.type||"finished"===e.type||"status"===e.type||e.taskId)?e:e.data||e,"ai_response"===n?n="response":"ai_response_end"===n&&(n="response_end"),t(n,s)}}catch(s){}}}class N{constructor(e){this.chatApi=e,this.streamProcessor=new I,this.eventHandlers=new Map,this.mode=null}setMode(e="sse",t=null){this.mode=e}on(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),()=>{const s=this.eventHandlers.get(e);if(s){const e=s.indexOf(t);e>-1&&s.splice(e,1)}}}off(e,t){const s=this.eventHandlers.get(e);if(s){const e=s.indexOf(t);e>-1&&s.splice(e,1)}}emit(e,t){const s=this.eventHandlers.get(e);s&&s.forEach(e=>{try{e(t)}catch(s){}})}abort(){}send(e){"websocket"===this.mode&&M&&M.send(e)}startStream(e,t,s){return this.chatApi.sendMessage(e,e=>{if(t&&s)try{t(e)}catch(n){}this.streamProcessor.processRawChunk(e,(a,r)=>{if(t&&!s)try{t(e)}catch(n){}this.emit(a,r)})})}clear(){this.eventHandlers.clear()}}class T{constructor(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.refreshCallback=null,this.sessionId=null}decodeJWT(e){try{const t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(s)}catch(t){return null}}isTokenExpired(e,t=30){if(!e)return!0;const s=this.decodeJWT(e);if(!s||!s.exp)return!0;const n=1e3*s.exp;return Date.now()>=n-1e3*t}setRefreshCallback(e){this.refreshCallback=e}async setAuth({accessToken:e,refreshToken:t,expiresIn:s,sessionId:n}){this.accessToken=e,this.refreshToken=t,this.sessionId=n;const a=this.decodeJWT(e);a&&a.exp?(this.tokenExpiry=1e3*a.exp,this.tokenExpiry<Date.now()+3e4&&await this.refreshTokens()):s&&(this.tokenExpiry=Date.now()+1e3*s)}async getAccessToken(){if(!this.accessToken)throw Error("No access token available. Initialize tokens first.");return this.isTokenExpired(this.accessToken,30)&&await this.refreshTokens(),this.accessToken}getSessionId(){return this.sessionId}async refreshTokens(){if(!this.refreshCallback)throw Error("No refresh callback provided");if(!this.refreshToken)throw Error("No refresh token available");try{const e=await this.refreshCallback(this.refreshToken);if(!e||!e.accessToken)throw Error("Invalid refresh response");return this.setAuth({accessToken:e.accessToken,refreshToken:e.refreshToken||this.refreshToken,expiresIn:e.expiresIn,sessionId:e.sessionId||this.sessionId}),this.accessToken}catch(e){throw this.clear(),e}}hasTokens(){return!!this.accessToken}clear(){this.accessToken=null,this.refreshToken=null,this.tokenExpiry=null,this.sessionId=null}}class A{constructor(){this.messages=[],this.messageIndex=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}_notify(){this.listeners.forEach(e=>e([...this.messages]))}_rebuildIndex(){this.messageIndex.clear(),this.messages.forEach((e,t)=>{this.messageIndex.set(e.messageId,t)})}addMessage(e){const t={...e,messageId:e.messageId||this._generateId(),timestamp:e.timestamp||Date.now(),uniqueKey:`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`};return this.messages.push(t),this.messageIndex.set(t.messageId,this.messages.length-1),this._notify(),t}updateMessage(e,t,s={}){const n=this.messageIndex.get(e);if(void 0===n)return null;const a=this.messages[n],r={};if(Object.entries(t).forEach(([e,t])=>{r[e]="function"==typeof t?t(a[e]):t}),s.silent)return Object.assign(this.messages[n],r),this.messages[n];const i=r.hasOwnProperty("isLive")||r.hasOwnProperty("isFinished")||r.hasOwnProperty("isThinkingFinished")||r.hasOwnProperty("statusType")||r.hasOwnProperty("sender")||r.hasOwnProperty("type")||r.hasOwnProperty("text");return this.messages[n]={...a,...r,...i&&{uniqueKey:`msg-${e}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}},this._notify(),this.messages[n]}insertMessage(e,t="end"){const s={...e,messageId:e.messageId||this._generateId(),timestamp:e.timestamp||Date.now(),uniqueKey:`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`};return"start"===t||0===t?this.messages.unshift(s):"end"!==t&&this.messages.length>t?this.messages.splice(t,0,s):this.messages.push(s),this._rebuildIndex(),this._notify(),s}insertMessages(e,t="end"){const s=e.map(e=>({...e,messageId:e.messageId||this._generateId(),timestamp:e.timestamp||Date.now(),uniqueKey:e.uniqueKey||`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,isLive:!1,isFinished:!0,text:e.content||e.text||""}));return"start"===t||0===t?this.messages.unshift(...s):"end"!==t&&this.messages.length>t?this.messages.splice(t,0,...s):this.messages.push(...s),this._rebuildIndex(),this._notify(),s}removeMessage(e){const t=this.messageIndex.get(e);return void 0!==t&&(this.messages.splice(t,1),this._rebuildIndex(),this._notify(),!0)}getMessage(e){const t=this.messageIndex.get(e);return void 0!==t?this.messages[t]:null}hasMessage(e){return this.messageIndex.has(e)}getAllMessages(){return[...this.messages]}clear(){this.messages=[],this.messageIndex.clear(),this._notify()}setMessages(e){this.messages=e.map(e=>({...e,uniqueKey:e.uniqueKey||`msg-${e.messageId}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`})),this._rebuildIndex(),this._notify()}_generateId(){return`msg-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}get count(){return this.messages.length}}class F{constructor(e,t){this.messageManager=e,this.statusRegistry=t,this.activeStreamingMessages=new Map}handleUserMessage({messageId:e,text:t,attachedFiles:s=[],...n}){return this.messageManager.addMessage({messageId:e||this.messageManager._generateId("user"),sender:"user",type:"user",text:t,attachedFiles:s,...n})}incrementChunkIndex(e){const t=this._getState(e);return t.chunkIndex+=1,t.chunkIndex}markTypeProcessed(e,t){this._getState(e).lastProcessedType=t}shouldFinishThinking(e){const t=this._getState(e);return t.hasChunk&&t.hasThinking&&!t.thinkingFinished}markThinkingFinished(e){const t=this._getState(e),s=e+"-thinking";t.thinkingFinished=!0,t.hasChunk=!0,t.hasThinking&&this.messageManager.hasMessage(s)&&this.messageManager.updateMessage(s,{isLive:!1,isThinkingFinished:!0})}}class E{constructor(){this.handlers=new Map,this.globalHandlers=[],this.streamForwarders=new Map}register(e,t,s={}){this.handlers.has(e)||this.handlers.set(e,[]);const n={handler:t,filter:s};return this.handlers.get(e).push(n),()=>{const t=this.handlers.get(e);if(t){const e=t.indexOf(n);e>-1&&t.splice(e,1)}}}registerGlobal(e,t={}){const s={handler:e,filter:t};return this.globalHandlers.push(s),()=>{const e=this.globalHandlers.indexOf(s);e>-1&&this.globalHandlers.splice(e,1)}}_matchesFilter(e,t){return!t.instanceId||e.instanceId===t.instanceId}async handle(e){const{status:t,messageId:s}=e,n=t?.type||e.type;await Promise.all(this.globalHandlers.filter(t=>this._matchesFilter(e,t.filter)).map(t=>Promise.resolve(t.handler(e)).catch(e=>{})));const a=this.handlers.get(n)||[];await Promise.all(a.filter(t=>this._matchesFilter(e,t.filter)).map(t=>Promise.resolve(t.handler(e)).catch(e=>{}))),"started"===t?.state||"in_progress"===t?.state?this._startStreamForwarding(s,n,e):"finished"!==t?.state&&"error"!==t?.state||this._stopStreamForwarding(s,n,e)}registerStreamForwarder(e){const t=Math.random().toString(36).substring(2,9);return this.streamForwarders.set(t,{forwarder:e,active:!1,messageId:null}),{id:t,stop:()=>this.streamForwarders.delete(t)}}forwardStream(e,t){this.streamForwarders.forEach(s=>{if(s.active&&s.messageId===e)try{"chunk"===t.type&&s.forwarder({...t,statusType:s.statusType})}catch(n){}})}_startStreamForwarding(e,t,s){this.streamForwarders.forEach(n=>{n.active=!0,n.messageId=e,n.statusType=t,n.forwarder.onStart&&n.forwarder.onStart({...s,statusType:t})})}_stopStreamForwarding(e,t,s){this.streamForwarders.forEach(n=>{n.messageId===e&&(n.active=!1,n.statusType=null,n.forwarder.onEnd&&n.forwarder.onEnd({...s,statusType:t}))})}clear(){this.handlers.clear(),this.globalHandlers=[],this.streamForwarders.clear()}}const R=new E;function z(){return R}const H={current:{}},_=new Map;class L{constructor(e){this.messageId=e,this.fullText="",this.displayIndex=0,this.previousDisplayIndex=0,this.isTyping=!1,this.isComplete=!1,this.isCleanedUp=!1,this.intervalId=null,this.mode=H.current.mode,this.speed=H.current.speed,this.batchSize=H.current.batchSize,this.listeners=new Set}setFullText(e,t){this.fullText+=e||"",!this.isTyping&&this.fullText.length>0&&this.startTyping(),t||!1!==this.isComplete||(this.isComplete=!0)}waitForAnimation(){return new Promise(e=>{if(this.displayIndex>=this.fullText.length)return void e();const t=setInterval(()=>{this.fullText.length>this.displayIndex||(clearInterval(t),e())},50)})}startTyping(){this.isTyping||(this.isTyping=!0,this.intervalId=setInterval(()=>{if(this.fullText.length>this.displayIndex){const e=this.getNextIncrement();this.previousDisplayIndex=this.displayIndex,this.displayIndex=Math.min(this.displayIndex+e,this.fullText.length),this.notifyListeners()}else this.isComplete&&(this.stopTyping(),this.onComplete&&(this.onComplete(),this.onComplete=null))},1e3/this.speed))}getNextIncrement(){switch(this.mode){case"char":case"chars":default:return 1;case"word":case"words":{let e=this.displayIndex+1;for(;this.fullText.length>e;){const t=this.fullText[e];if(" "===t||"\n"===t||/[.,!?;:]/.test(t))return e-this.displayIndex+1;e++}return this.fullText.length-this.displayIndex}case"batch":case"batches":return this.batchSize}}stopTyping(){this.isTyping=!1,this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}subscribe(e,t={}){const s={callback:e,newOnly:t.newOnly||!1};return this.listeners.add(s),()=>this.listeners.delete(s)}notifyListeners(){const e=this.fullText.slice(this.previousDisplayIndex,this.displayIndex),t=this.fullText.slice(0,this.displayIndex);this.listeners.forEach(s=>{s.callback(s.newOnly?e:t)})}cleanup(){this.isCleanedUp||(this.isCleanedUp=!0,this.stopTyping(),this.listeners.clear(),_.delete(this.messageId))}}function D(e){return _.get(e)}class q{constructor(){}async processChunk(e,t=null,s,n){const a=e.messageId,r=function(e){if(_.has(e))return _.get(e);const t=new L(e);return _.set(e,t),t}(e.messageId);if(r.setFullText(e.text||"",e.isLive),s){const s=e.from&&this.forwardingManager?.handlers[e.from],n=t&&this.forwardingManager?this.forwardingManager.getSession(t):null,r=s&&n&&e.from===n?.action;e.from&&!s&&this.forwardingManager&&(this._warnedActions||(this._warnedActions=new Set),this._warnedActions.has(e.from)||this._warnedActions.add(e.from));const i=s?this.forwardingManager.handlers[e.from]:null,o=e.from&&"replace"===(i?.mode||"replace");if(r){const s=this.forwardingManager.isAnimated(t),n=this.forwardingManager.getSubscriptionMode(t);if(s){const s=D(a);s.hasForwarder||(s.hasForwarder=!0,s.subscribe(s=>{this.forwardingManager.forwardChunk(t,s,e.isLive)},{newOnly:"delta"===n}),s.onComplete=()=>{this.forwardingManager.cleanupSession(t)})}else this.forwardingManager.forwardChunk(t,e.text||"",e.isLive)}if(o)return}this.messageHandlers.messageManager.hasMessage(a)?this.messageHandlers.messageManager.updateMessage(a,{text:t=>t+(e.text||"")},{silent:!0}):this.messageHandlers.messageManager.addMessage({messageId:a,sender:"ai",type:"chunk",text:e.text||"",isLive:!0,tokens:e.tokens}),await r.waitForAnimation()}async processHolding(e){}async processThinking(e){const t=e.messageId+"-thinking";this.messageHandlers.messageManager.hasMessage(t)?this.messageHandlers.messageManager.updateMessage(t,{text:t=>t+(e.text||"")}):this.messageHandlers.messageManager.addMessage({messageId:t,sender:"ai",type:"thinking",text:e.text||"",isLive:!0,timestamp:Date.now()})}async finishThinking(e){const t=e.messageId+"-thinking",s=this.messageHandlers.messageManager.getMessage(t);if(s){const e=Date.now();this.messageHandlers.messageManager.updateMessage(t,{isLive:!1,finalized:!0,duration:parseFloat(((e-(s.timestamp||e))/1e3).toFixed(1)),endTimestamp:e})}}async finishChunk(e){const t=e.messageId,s=this.messageHandlers.messageManager.getMessage(t);s&&this.messageHandlers.messageManager.updateMessage(t,{isLive:!1,finalized:!0,text:s.text||""})}async processStatus(e,t=null){const s=e.taskId||e.messageId;if(!s)return;if(this.messageHandlers.statusRegistry)try{await this.messageHandlers.statusRegistry.handle({...e,messageId:s,instanceId:t,status:{type:e.action||e.type,state:"started"===e.type?"started":"finished"===e.type?"finished":"in_progress",data:e.data}})}catch(a){}const n=this.messageHandlers.messageManager.hasMessage(s);"started"!==e.type&&"status"!==e.type?"finished"!==e.type?n?this.messageHandlers.messageManager.updateMessage(s,{statusType:e.type,data:e.data,metadata:e.metadata,isFinished:e.type.includes("end")||"finished"===e.type}):this.messageHandlers.messageManager.addMessage({messageId:s,sender:"ai",type:"status",action:e.action,statusType:e.type,data:e.data,metadata:e.metadata,isFinished:e.type.includes("end")||"finished"===e.type,isFlat:!0}):n&&this.messageHandlers.messageManager.updateMessage(s,{statusType:e.type,isFinished:!0}):n||this.messageHandlers.messageManager.addMessage({messageId:s,sender:"ai",type:"status",action:e.action,statusType:e.type,data:e.data,metadata:e.metadata,isFinished:!1,isFlat:!0})}}class O extends q{constructor(e,t,s,n=null){super(),this.messageHandlers=e,this.forwardingManager=t,this.queue=[],this.queueHistory=[],this.isProcessing=!1,this.lastMessageId=null,this.useForwarding=s,this.currentForwardingSession=null,this.onQueueComplete=null,this.instanceId=n}async process(){this.isProcessing=!0;const e=[...this.queue];this.queueHistory.push(...e),this.queue=[];for(let t=0;e.length>t;t++){const s=e[t],n=this.queueHistory.findIndex(e=>(e.messageId||e.taskId)==(s.messageId||s.taskId)),a=this.queueHistory[n-1];a&&!a.finalized&&(a.finalized=!0,await this.notifyPreviousItem(a)),await this.processItem(s)}this.isProcessing=!1,this.queue.length>0?this.process():(this.finalize(),this.onQueueComplete&&this.onQueueComplete())}filterData(e){return e}async addToQueue(e){const t=this.filterData(e);this.queue.push(t),this.isProcessing||this.process()}async notifyPreviousItem(e){"thinking"===e.type?await this.finishThinking(e):"chunk"===e.type&&await this.finishChunk(e)}async processItem(e){const{type:t}=e;e.messageId&&(this.lastMessageId=e.messageId);const s=e.action||e.data?.action,n=e.taskId||e.messageId;switch(this.forwardingManager&&this.useForwarding&&("started"===t&&s&&this.forwardingManager.startSession(n,s,this.instanceId)&&(this.currentForwardingSession=n),"finished"===t&&this.currentForwardingSession&&(this.forwardingManager.endSession(this.currentForwardingSession),this.currentForwardingSession=null),"end"===t&&this.currentForwardingSession&&(this.forwardingManager.endSession(this.currentForwardingSession),this.currentForwardingSession=null)),t){case"thinking":await this.processThinking(e);break;case"holding":await this.processHolding(e);break;case"chunk":await this.processChunk(e,this.currentForwardingSession,this.useForwarding,this.forwardingManager.newOnly);break;case"started":case"finished":case"status":case"status_start":case"status_end":case"status_error":case"error":case"action":await this.processStatus(e,this.instanceId);break;case"end":await this.finalize(e)}}async clear(){this.queue=[],this.queueHistory=[],this.isProcessing=!1,this.lastMessageId=null,_.forEach(e=>{e.stopTyping(),e.isComplete=!0,e.cleanup()}),_.clear(),this.currentForwardingSession&&this.forwardingManager&&(this.forwardingManager.endSession(this.currentForwardingSession),this.currentForwardingSession=null),this.onQueueComplete&&this.onQueueComplete()}async endResponse(){this.queueHistory=[]}async finalize(e){this.lastMessageId&&await this.finishChunk({messageId:this.lastMessageId}),this.isProcessing=!1,this.queue=[]}}let P=null;class j{constructor(e={}){this.initialHandlers={...e},this.dynamicHandlers={},this.handlers={...e},this.activeSessions=new Map}register(e,t,s={}){const n=s.instanceId?`${e}:${s.instanceId}`:e;return this.dynamicHandlers[n]={handler:t,mode:s.mode||"dual",animated:!1!==s.animated,subscriptionMode:s.subscriptionMode||"delta",instanceId:s.instanceId},this._rebuildHandlers(),()=>{delete this.dynamicHandlers[n],this._rebuildHandlers()}}_rebuildHandlers(){this.handlers={...this.initialHandlers},Object.assign(this.handlers,this.dynamicHandlers)}startSession(e,t,s=null){const n=s?`${t}:${s}`:null,a=n&&this.handlers[n]||this.handlers[t];return!(!a||a.instanceId&&a.instanceId!==s||(this.activeSessions.get(e)||this.activeSessions.set(e,{action:t,handler:a.handler,mode:a.mode,animated:a.animated,subscriptionMode:a.subscriptionMode,instanceId:a.instanceId,lastText:"",fullText:"",streamEnded:!1}),0))}endSession(e){const t=this.activeSessions.get(e);t&&(t.streamEnded=!0,t.animated||this.cleanupSession(e))}cleanupSession(e){const t=this.activeSessions.get(e);if(t){if(t.handler&&t.fullText)try{t.handler(null,t.fullText,{action:t.action,event:"end",isLive:!1})}catch(s){}this.activeSessions.delete(e)}}isActive(e){return this.activeSessions.has(e)}getSession(e){return this.activeSessions.get(e)}forwardChunk(e,t,s=!0){const n=this.activeSessions.get(e);if(!n)return!1;const a=t||"";if(0===a.length&&s)return!0;let r,i;"full"===n.subscriptionMode?(i=a,r=a):(n.fullText+=a,r=a,i=n.fullText);try{n.handler(r,i,{action:n.action,isLive:!n.streamEnded&&s,event:"chunk",subscriptionMode:n.subscriptionMode})}catch(o){}return!0}shouldReplace(e){const t=this.activeSessions.get(e);return t&&"replace"===t.mode}isAnimated(e){const t=this.activeSessions.get(e);return t&&t.animated}getSubscriptionMode(e){const t=this.activeSessions.get(e);return t?t.subscriptionMode:"delta"}getActiveSessions(){return Array.from(this.activeSessions.keys())}clearAll(){this.activeSessions.clear()}}function B(e){return P?e&&Object.keys(e).length>0&&(P.initialHandlers={...e},P._rebuildHandlers()):P=new j(e),P}function U(e){P=e}function $(){P=null}const W=t(null);function Y(e,t,r={}){const i=s(W),o=void 0!==r.instanceId?r.instanceId:i,c=o?{instanceId:o}:{},l=z(),d=n(t);a(()=>{d.current=t},[t]),a(()=>{const t=[];if("object"==typeof e&&null!==e)Object.entries(e).forEach(([e,s])=>{if("*"===e){const e=l.registerGlobal(s,c);t.push(e)}else{const n=l.register(e,s,c);t.push(n)}});else if("string"==typeof e){const s=e=>d.current?.(e);if("*"===e){const e=l.registerGlobal(s,c);t.push(e)}else{const n=l.register(e,s,c);t.push(n)}}return()=>{t.forEach(e=>e?.())}},[e,o])}const J=t({}),K=()=>s(J);let X={},G=null;const Q=()=>G;function V({children:t,initialWelcome:s={title:"Welcome to AI Chat Agent",description:"A perfect agent library for your needs, for docs visit oblien.com/docs/chat-agent"},refreshTokenCallback:c,markdownComponents:l,typingAnimation:d={mode:"chars",speed:400},statusComponents:h,forwardingHandlers:u={},authConfig:g,enableHistory:m=!0,loadingComponent:p,allowThinking:f=!0,headerComponent:y,config:x,apiHandler:w,agentId:b,className:v="h-full w-full",onError:k}){const M=n(b||"chat-"+Math.random().toString(36).substring(2,9)).current,[C,I]=r(!0),[E,R]=r(g?.sessionId),[_,L]=r(!1),[D,q]=r(!1),[P,j]=r(!1),[U,$]=r(null),[Y,K]=r(null),[Q,V]=r(!1),[Z,ee]=r(!1),[te,se]=r(null),ne=n(s).current,[ae,re]=r([]),ie=n(!1),oe=n(!1),ce=n(!1),le=n(new A),de=n(null),he=n(!1),ue=n(!1),ge=i(()=>z(),[]),me=n(c?new T:null),pe=n(w||new S({...x,...me.current&&{tokenManager:me.current},token:g?.accessToken,sessionId:g?.sessionId})),fe=n(new N(pe.current)),ye=n(B(u)),xe=n(new F(le.current,ge)),we=n(new O(xe.current,ye.current,Object.keys(u).length>0,M)),be=o(()=>{const e=ie.current||oe.current;q(e),e||L(!1)},[]),ve=o(()=>{if(he.current&&ue.current){const t=ye.current.handlers._loading_end;if(t?.handler)try{t.handler({messageId:de.current||null,instanceId:M,timestamp:Date.now()})}catch(e){}}},[M]);a(()=>{we.current.onQueueComplete=()=>{oe.current=!1,ue.current=!0,be(),ve()}},[be,ve]);const ke=n(l).current;a(()=>{G=ke},[ke]);const Se=n(p),Me=n(h),Ce=n(y);a(()=>{var e;p!==Se.current&&(Se.current=p),h!==Me.current&&(Me.current=h,e=h||{},X={...e}),y!==Ce.current&&(Ce.current=y),c&&me.current&&me.current.setRefreshCallback(c)},[p,h,y,c]);const Ie=n(!1),Ne=n(E),Te=n(null);H.current=d;const Ae=n(new Set);a(()=>{const e=le.current.subscribe(e=>{re(e)});return()=>{e()}},[]),a(()=>{Ne.current=E},[E]);const Fe=n(!1);a(()=>{(async()=>{if(g&&g.sessionId&&me.current)try{await me.current.setAuth(g)}catch(U){let t="Authentication failed. Please refresh the page.";U?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":U?.message&&(t=U.message),$({type:"auth_error",message:t,error:U}),I(!1)}else m||I(!1)})()},[!1,g,m]);const Ee=o(e=>{$(e.error)},[]),Re=o(async()=>{if(m)try{if(Ae.current.has(E))return void I(!1);Ae.current.add(E),I(!0);const e=await pe.current.getHistory();if(e.error)return Ee(e),void I(!1);e.history&&e.history.length>0&&le.current.insertMessages(e.history,"end"),ee(!!e.has_more),I(!1)}catch(e){let t="Could not load message history.";e?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":e?.message?.includes("Network")?t="Network error. Please check your connection.":e?.message&&(t=e.message),$({type:"history_error",message:t,error:e}),I(!1)}else I(!1)},[E,Ee,m]);a(()=>{(async()=>{E&&!Fe.current?(Fe.current=!0,await Re()):E||Fe.current||(Fe.current=!0,m?await Re():I(!1))})()},[E,Re,m]);const ze=o(async()=>{ce.current=!0,ie.current=!1,oe.current=!1,q(!1),L(!1),j(!1),he.current=!1,ue.current=!1;const e=xe.current.messageManager.getAllMessages(),t=[],s=[];for(const n of e)"thinking"!==n.type||!n.isLive&&n.finalized?"status"!==n.type||n.isFinished||s.push(n):t.push(n);t.length>0&&await Promise.all(t.map(e=>{const t=e.messageId.replace("-thinking","");return we.current.finishThinking({messageId:t})}));for(const n of s)xe.current.messageManager.updateMessage(n.messageId,{isFinished:!0,statusType:"finished"});we.current.clear(),de.current=null,pe.current.abort(),fe.current.abort(),Ne.current&&pe.current.abortRequest&&await pe.current.abortRequest(Ne.current),setTimeout(()=>{ce.current=!1},100)},[]),He=o(e=>{if(ce.current)return;const t={...e,id:e?.id||Math.random().toString(36).substring(2,9),timestamp:Date.now(),instanceId:M};K(t),k&&k(t);const s=ye.current.handlers._error;if(s?.handler)try{s.handler(t)}catch(n){}},[k,M]),_e=o(()=>{K(null)},[]),Le=o(()=>{ie.current=!1;const e=de.current;if(e){we.current.endResponse(),de.current=null,he.current=!0;const s=ye.current.handlers._response_end;if(s?.handler)try{s.handler({messageId:e,instanceId:M,timestamp:Date.now()})}catch(t){}}else he.current=!0;be(),ve()},[be,M,ve]),De=o(()=>{Ie.current=!1,ie.current=!1,be()},[be]),qe=o(e=>{const t=e?.data?.messageId||e?.messageId;if(t&&(de.current=t),!P){j(!0),he.current=!1,ue.current=!1;const e=ye.current.handlers._response_start;if(e?.handler)try{e.handler({messageId:t,instanceId:M,timestamp:Date.now()})}catch(s){}}oe.current=!0,we.current.addToQueue(e),be()},[P,be,M]);a(()=>(fe.current.on("stream_error",He),fe.current.on("response",qe),fe.current.on("response_end",Le),fe.current.on("disconnect",De),()=>{fe.current.off("stream_error",He),fe.current.off("response",qe),fe.current.off("response_end",Le),fe.current.off("disconnect",De)}),[He,qe,Le,De]);const Oe=async({messageId:e=Math.random().toString(36).substring(2,9),message:t="",attachedFiles:s=[],uploadId:n=null}={})=>{if(!t.trim())return;const a="user-"+e;try{Te.current&&Te.current?.messageId===a||xe.current.handleUserMessage({messageId:a,text:t,attachedFiles:s}),Te.current={messageId:a,message:t,attachedFiles:s,uploadId:n},L(!0),j(!1),he.current=!1,ue.current=!1,ce.current=!1,ie.current=!0,be();const e=ye.current.handlers._stream_feedback,r=e?.handler,i="raw"===e?.mode,o=await fe.current.startStream({message:t,attachedFiles:s,uploadId:n,sessionId:Ne.current,context:null,allowThinking:f},r,i);o.status||(ie.current=!1,be(),He({errorType:"connection_error",error:o.error||"Error occurred while connecting to server",message:o.message||"Failed to send message"}))}catch(r){ie.current=!1,be(),He({errorType:"send_error",error:r.message||"Unknown error",message:"Failed to send message"})}finally{L(!1)}},Pe=o(async()=>{Te.current&&await Oe(Te.current)},[]),je=i(()=>({addMessage:e=>le.current.addMessage(e),updateMessage:(e,t)=>le.current.updateMessage(e,t),removeMessage:e=>le.current.removeMessage(e),getMessage:e=>le.current.getMessage(e),clear:()=>le.current.clear()}),[]),Be=i(()=>({register:(e,t)=>ge.register(e,t,{instanceId:M}),registerGlobal:e=>ge.registerGlobal(e,{instanceId:M})}),[M,ge]);return e.createElement("div",{className:"react-ai-agent-root "+v},e.createElement(J.Provider,{value:{sendMsg:Oe,messages:ae,messageManager:je,isLoading:_,isStreaming:D,isResponseStarted:P,isInitialLoading:C,isLoadingMore:Q,error:U,streamError:Y,clearStreamError:_e,getHistory:Re,loadMoreMessages:async()=>{if(m&&!Q&&Z){V(!0);try{const e=le.current.count,t=await pe.current.getHistory({offset:e,limit:20});if(t.error)return Ee(t),void V(!1);t.history&&t.history.length>0?(le.current.insertMessages(t.history,"start"),ee(t.has_more)):ee(!1)}catch(e){$({type:"load_more_error",message:"Failed to load more messages",error:e})}finally{V(!1)}}},hasMoreMessages:Z,enableHistory:m,retryLastMessage:Pe,abort:ze,sessionId:E,setSessionId:R,instanceId:M,currentSelectedFile:te,setCurrentSelectedFile:se,welcome:ne,statusRegistry:Be,markdownComponents:ke,statusComponents:Me.current,loadingComponent:Se.current,headerComponent:Ce.current,typingAnimation:d}},e.createElement(W.Provider,{value:M},t)))}const Z={send:"/arrow up md-61-1696832363.png",attach:"/attach-1-1662364367.png",public:"/world-229-1658433759.png",arrowDown:"/chevron down-4-1696832126.png",close:"/close remove-802-1662363936.png",add:"/plus 4-12-1662493809.png",logs:"/website terminal-62-1658431404.png",terminal:"/terminal-184-1658431404.png",minimize:"/chevron down-4-1696832126.png",removeBold:"/delete-29-1661490994.png",info:"/info menu-42-1661490994.png",leftSidebar:"/grid interface-166-1658433281.png",file:"/document-180-1658431575.png",folder:"/folder file-32-1661323044.png",tick:"/check circle-3-1660219236.png",square:"/square-38-1666783764.png",search:"/search-123-1658435124.png",check:"/checkmark-7-1660219236.png",lock:"/lock-62-1691989601.png",discord:"/discord-141-1693375491.png",twitter:"/x.com-179-1693375584.png",refresh:"/refresh right-64-1696832204.png",back:"/arrow right md-49-1696832059.png",home:"/home-123-1658433759.png",forward:"/arrow left md-33-1696832059.png",newTab:"/new tab-123-1658433759.png",devTools:"/developer tools-123-1658433759.png",externalLink:"/External_link_HtLszLDBXqHilHK674zh2aKoSL7xUhyboAzP.png",deploy:"/space rocket-88-1687505465.png",projects:"/git fork-163-1658431404.png",settings:"/setting-100-1658432731.png",logout:"/Logout_q9Ri9V6YI29BipbKthCSXYDM0WoxMC05JTYO.png",notfound:"/search not found-92-1666688362.png",chatai:"/chat intelligence-6-1686046192.png",credit:"/bank card-91-1658234909.png",question:"/question mark circle-29-1662452248.png",blank:"/code-15-1658431404.png",react:"/react-native-29-1693375583.png",nextjs:"/next js circle-172-1693375539.png",vue:"/vue-160-1693375217.png",angular:"/angular-62-1693375491.png",node:"/npm-183-1693375539.png",python:"/python-122-1662819152.png",mobile:"/iphone-36-1658434492.png",laravel:"/laravel-108-1693375539.png",php:"/php-7-1693375216.png",url:"/link-68-1692683696.png",grid:"/gallery view-155-1658433281.png",list:"/bulleted list-15-1692683663.png",download:"/Download_61W5ztaZuYZoYEY7utQW7FU1y4lMiUO2rHjg.png",upload:"/upload-123-1658433759.png",starfilled:"/star-31-1660810259.png",edit:"/pen-304-1658238246.png",globe:"/earth-30-1687505545.png",minus:"/minus 4-9-1660810450.png",switch:"/changing-330-1658238246.png",history:"/counter clockwise undo-46-1658435834.png",golang:"/Go_Logo_Blue.svg.png",github:"/github-8-1693375538.png",pull:"/git pull-170-1658431404.png",sync:"/update left-39-1696832255.png",error:"/error triangle-16-1662499385.png",reload:"/flash refresh-94-1658434699.png",filter:"/filter-25-1662364403.png",sets:"/setting-41-1662364403.png",read:"/eye-20-1691989638.png",index:"/database-27-1658237565.png",debug:"/terminal-184-1658431404.png",brain:"/brain-41-1686045820.png",command:"/command-147-1658431404.png",pdf:"/document pdf-66-1662364367.png",websocket:"/power outlet-81-1689918655.png",ai:"/ai chip-118-1686045593.png",dashboard:"/dashboard 6-8-1662364403.png",store:"/store-30-1662820309.png",icons:"/ui8-139-1693375584.png",build:"/tools-58-1662364403.png",linkedin:"/linkedin-113-1693375539.png",support:"/headphone-24-1663753435.png",nofee:"/snow%20bag-318-1672139659.png",anytime:"/circle%20clock-39-1658435834.png",free:"/bird-106-1678249964.png",cloud:"/cloud%20connect-56-1658236831.png",code:"/code-12-1658431404.png",screenshot:"/scan%20image-226-1658434699.png",pagecontent:"/web%20page%20download-36-1658436291.png",improve:"/ai%20neural%20share-142-1686045754.png",roadmap:"/roadmap-159-1681196175.png"},ee={figma:"/icons/project/Figma-logo.svg.png",githubraw:"/icons/project/github-mark-white.png"},te=(e,t,s="#000",n={},a=!1)=>{if(a)return h("img",{src:ee[e]?.replace(/ /g,"%20"),alt:e,style:{width:t,height:t,objectFit:"contain",...n}});let r=Z[e]?.replace(/ /g,"%20")||e?.replace(/ /g,"%20");return r=e.startsWith("http")?e:"https://cdn.oblien.com/static/png-icons/"+r,h("div",{style:{maskImage:`url('${r}')`,maskSize:"contain",maskRepeat:"no-repeat",maskPosition:"center",WebkitMaskSize:"contain",WebkitMaskRepeat:"no-repeat",WebkitMaskPosition:"center",width:t,height:t,backgroundColor:s,...n}})},se=({showLoadMore:e,enableHistory:t,hasMoreMessages:s,messagesLength:n,error:a,isInitialLoading:r,loadMoreMessages:i,isLoadingMore:o})=>e&&t&&s&&0!==n&&!a&&!r?h("div",{className:"react-chat-core-load-more flex justify-center py-4",children:h("button",{onClick:i,disabled:o,className:"react-chat-core-load-more-button flex items-center gap-2 text-theme-tertiary hover:text-theme-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed opacity-50",children:u(g,o?{children:[h("div",{className:"react-chat-core-load-more-spinner w-4 h-4 border-2 border-theme-primary border-t-theme-tertiary rounded-full animate-spin"}),h("span",{className:"react-chat-core-load-more-text text-sm",children:"Loading..."})]}:{children:[te("refresh",18,"currentColor"),h("span",{className:"react-chat-core-load-more-text text-sm",children:"Load more messages"})]})})}):null,ne=({error:e})=>{const{welcome:t}=K(),s=(()=>{if(!e)return null;let t="";return t="string"==typeof e?e:e.message?e.message:e.error?"string"==typeof e.error?e.error:e.error.message||"An error occurred":"An unexpected error occurred",t})();return h("div",{className:"react-ai-agent-start-chat flex flex-col items-center justify-center h-full",children:"object"!=typeof t||t?.title?u("div",{className:"react-ai-agent-start-chat-content text-center mb-8 flex flex-col items-center justify-center gap-2",children:[e&&h("span",{className:"react-ai-agent-start-chat-error-icon",children:te("error",70,"currentColor",{marginBottom:"10px"})}),h("h2",{className:"react-ai-agent-start-chat-title text-2xl font-light text-theme-primary mb-4",children:e?"Something went wrong":t?.title}),h("p",{className:"react-ai-agent-start-chat-description text-theme-muted mb-6 max-w-md text-base leading-relaxed",children:e?s:t?.description}),e&&e.type&&h("p",{className:"react-ai-agent-start-chat-error-type text-xs text-theme-tertiary mt-2 opacity-50",children:e.type.replace("_"," ")})]}):t})},ae=({WelcomeComponent:e,error:t,isPanelOpen:s})=>e?h(e,{error:t}):h(ne,{error:t,miniMode:s}),re=()=>u("div",{className:"react-ai-agent-loading-mock mt-20 space-y-8 px-5 pt-20 pb-40 w-full max-w-[800px] mx-auto",children:[u("div",{className:"react-ai-agent-loading-mock-welcome flex items-start gap-4 mb-12",children:[h("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-welcome w-10 h-10 rounded-full shimmer-skeleton"}),u("div",{className:"react-ai-agent-loading-mock-content flex-1 space-y-3",children:[h("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-4 rounded-full shimmer-skeleton w-2/3"}),h("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-2 h-4 rounded-full shimmer-skeleton w-1/2"})]})]}),Array.from({length:2}).map((e,t)=>u("div",{className:"react-ai-agent-loading-mock-message-group space-y-6",children:[u("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-user flex items-start gap-4 justify-end",children:[h("div",{className:"react-ai-agent-loading-mock-message-content max-w-[70%] space-y-2",children:h("div",{className:"react-ai-agent-loading-mock-line h-3 rounded-full shimmer-skeleton w-full"})}),h("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-user w-8 h-8 rounded-full shimmer-skeleton"})]}),u("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-ai flex items-start gap-4",children:[h("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-ai w-8 h-8 rounded-full shimmer-skeleton"}),u("div",{className:"react-ai-agent-loading-mock-message-content flex-1 space-y-3",children:[h("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-3 rounded-full shimmer-skeleton w-4/5"}),h("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-2 h-3 rounded-full shimmer-skeleton w-3/4"})]})]})]},t))]}),ie=({onComplete:e,duration:t=800})=>{const[s,i]=r(0),[o,c]=r(!1),l=n(0);return a(()=>{l.current=300,requestAnimationFrame(()=>{i(l.current)});const s=setTimeout(()=>{c(!0),e?.()},t);return()=>clearTimeout(s)},[t,e]),o?null:h("div",{style:{height:s+"px",transition:`height ${t}ms cubic-bezier(0.4, 0, 0.2, 1)`,pointerEvents:"none"}})},oe=({message:e,allowEdit:t=!0})=>{const s=[];return t&&s.push({icon:"edit",text:"Edit",onClick:()=>{}}),e.snapshot&&s.push({icon:"refresh",text:"Restore checkpoint",onClick:()=>{}}),u("div",{className:"react-ai-agent-user-message flex flex-col mb-2",children:[h("div",{className:"react-ai-agent-user-message-bubble-wrapper flex justify-end mb-2",children:h("div",{className:"react-ai-agent-user-message-bubble bg-secondary text-theme-primary px-4 py-2 rounded-[20px] max-w-xs md:max-w-md",style:{wordBreak:"break-word"},children:h("p",{className:"react-ai-agent-user-message-text text-[16px] leading-[22px] tracking-wide",children:e.text})})}),h("div",{className:"react-ai-agent-user-message-actions flex justify-end gap-4",children:s.map((e,t)=>u("button",{className:`react-ai-agent-user-message-action react-ai-agent-user-message-action-${e.icon} flex items-center gap-1 opacity-25`,onClick:e.onClick,children:[h("span",{className:"react-ai-agent-user-message-action-icon",children:te(e.icon,16,"currentColor")}),h("span",{className:"react-ai-agent-user-message-action-label text-[12px] font-[300] text-theme-primary",children:e.text})]},t))})]})};var ce=c(({message:e})=>{const t=Q(),[s,n]=r("");return a(()=>{const t=D(e.messageId);if(t)return t.subscribe(e=>{n(e)});n(e.text||"")},[e.messageId,e.text]),h("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",children:h("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",style:{wordBreak:"break-word"},children:h(p,{parseIncompleteMarkdown:!0,mode:"streaming",components:t,children:s})})})}),le=c(({text:e})=>{const t=Q(),s=e||"";return h("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",style:{minHeight:"20px"},children:h("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",style:{wordBreak:"break-word",minHeight:"20px"},children:s?h(p,{parseIncompleteMarkdown:!0,mode:"static",components:t,children:s}):h("span",{style:{opacity:.5},children:"..."})})})}),de=c(({message:e,animationConfig:t})=>e.isLive&&!e.finalized?h(ce,{message:e,animationConfig:t}):h(le,{text:e.text}));const he={'code[class*="language-"]':{color:"#d7d5d1",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",fontSize:"14px",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"white",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0.5em 0",overflow:"auto",background:"#1e1e1e",borderRadius:"15px"},'pre[class*="language-"]::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'pre[class*="language-"] ::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"]::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"] ::-moz-selection':{textShadow:"none",background:"#0e0c0a"},'pre[class*="language-"]::selection':{textShadow:"none",background:"#0e0c0a"},'pre[class*="language-"] ::selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"]::selection':{textShadow:"none",background:"#0e0c0a"},'code[class*="language-"] ::selection':{textShadow:"none",background:"#0e0c0a"},':not(pre) > code[class*="language-"]':{color:"white",background:"#222222",padding:"0.1em",borderRadius:"0.3em",whiteSpace:"normal"},comment:{color:"#545053"},string:{color:"#838083"},number:{color:"#838083"},builtin:{color:"#838083"},char:{color:"#838083"},constant:{color:"#838083"},variable:{color:"#838083"},"class-name":{color:"#D7D5D1"},function:{color:"#D7D5D1"},tag:{color:"#838083"},"attr-name":{color:"#D7D5D1"},selector:{color:"#838083"},important:{fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"}},ue=c(({message:e,isInCurrentSession:t})=>{const s=n(null),c=n(e.finalized),l=n(null),[d,g]=r(!e.finalized),[m,p]=r(!1),[x,w]=r(""),b=e.isLive||!e.finalized,v=e.finalized||!t,k=e.duration||0,S=i(()=>e.text||"",[e.text]);a(()=>{requestAnimationFrame(()=>{p(!0)})},[]),a(()=>{if(!b||!d)return void w(S);const e=x.length,t=S.length;if(e>=t)return;const s=Math.min(5,t-e),n=setTimeout(()=>{w(S.slice(0,e+s))},20);return()=>clearTimeout(n)},[S,x,b,d]),a(()=>{if(s.current&&d&&b)return l.current&&cancelAnimationFrame(l.current),l.current=requestAnimationFrame(()=>{s.current&&(s.current.scrollTop=s.current.scrollHeight)}),()=>{l.current&&cancelAnimationFrame(l.current)}},[x,d,b]),a(()=>{if(v&&!c.current&&d){const e=setTimeout(()=>{g(!1)},800);return()=>clearTimeout(e)}},[v,d]);const M=o(()=>{g(e=>!e)},[]),C=i(()=>({code({node:e,inline:t,className:s,children:n,...a}){const r=/language-(\w+)/.exec(s||""),i=(n+"").replace(/\n$/,""),o=!t&&i.includes("\n");return t||!o?h("code",{className:"react-ai-agent-thinking-code-inline px-1 py-0.5 bg-secondary rounded text-xs font-mono whitespace-pre-wrap",...a,children:n}):h("div",{className:"react-ai-agent-thinking-code-block rounded-[15px] overflow-hidden my-3",children:h(f,{language:r?.[1]||"javascript",style:he,children:i})})},p:({children:e})=>h("p",{className:"react-ai-agent-thinking-paragraph mb-2 leading-5 text-sm",children:e}),ul:({children:e})=>h("ul",{className:"react-ai-agent-thinking-list react-ai-agent-thinking-list-unordered list-disc pl-5 mb-3 grid text-sm",children:e}),ol:({children:e})=>h("ol",{className:"react-ai-agent-thinking-list react-ai-agent-thinking-list-ordered list-decimal pl-5 mb-3 grid text-sm",children:e}),li:({children:e})=>h("li",{className:"react-ai-agent-thinking-list-item mb-1 text-sm",children:e}),h1:({children:e})=>h("h1",{className:"react-ai-agent-thinking-heading react-ai-agent-thinking-heading-1 text-lg font-semibold mb-2 mt-3",children:e}),h2:({children:e})=>h("h2",{className:"react-ai-agent-thinking-heading react-ai-agent-thinking-heading-2 text-base font-semibold mb-2 mt-3",children:e}),h3:({children:e})=>h("h3",{className:"react-ai-agent-thinking-heading react-ai-agent-thinking-heading-3 text-sm font-semibold mb-1 mt-2",children:e}),blockquote:({children:e})=>h("blockquote",{className:"react-ai-agent-thinking-blockquote border-l-4 border-gray-600 pl-3 italic my-3 text-theme-quaternary text-sm",children:e})}),[]);return u("div",{className:"react-ai-agent-thinking-message mb-4 mx-auto opacity-50 transition-all duration-300 ease-out",style:{opacity:m?.5:0,transform:m?"translateY(0)":"translateY(-10px)"},children:[v?u("button",{onClick:M,className:"react-ai-agent-thinking-toggle react-ai-agent-thinking-toggle-finished text-theme-tertiary text-sm hover:text-theme-secondary transition-colors mb-2 flex items-center gap-2",children:[h("span",{className:"react-ai-agent-thinking-toggle-icon transition-transform duration-300",children:te(d?"brain-10-1663078315.png":"brain-11-1663755045.png",20,"currentColor")}),u("span",{className:"react-ai-agent-thinking-toggle-text",children:["Thought for ",k," second",1!==k?"s":""]})]}):u("div",{className:"react-ai-agent-thinking-header text-theme-tertiary text-sm mb-2 flex items-center gap-2",children:[h("span",{className:"react-ai-agent-thinking-icon animate-pulse",children:te("brain-11-1663755045.png",20,"currentColor")}),h("span",{className:"react-ai-agent-thinking-label",children:"Thinking..."})]}),h("div",{style:{maxHeight:d?"150px":"0px",opacity:d?1:0,overflow:"hidden",transition:"max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s ease-out"},children:x&&h("div",{ref:s,className:"react-ai-agent-thinking-content-scroll overflow-y-auto scrollbar-thin scrollbar-track-transparent",style:{maxHeight:"150px",scrollBehavior:"smooth",WebkitMaskImage:"linear-gradient(to top, transparent 0%, black 60%, transparent 98%)",maskImage:"linear-gradient(to top, transparent 0%, black 60%, transparent 98%)"},children:h("div",{className:"react-ai-agent-thinking-content text-theme-primary prose prose-invert max-w-none whitespace-pre-wrap text-sm pt-10",style:{wordBreak:"break-word",opacity:b?.8:1,transition:"opacity 0.15s ease"},children:h(y,{components:C,children:x})})})})]})},(e,t)=>e.message.text===t.message.text&&e.message.finalized===t.message.finalized&&e.message.isLive===t.message.isLive&&e.message.duration===t.message.duration&&e.isInCurrentSession===t.isInCurrentSession);ue.displayName="ThinkingMessage";const ge=({text:e,style:t,fontSize:s="1em",paddingRight:n="140px",backgroundSize:a="125px",isDark:r=!1})=>{let i=1;"string"==typeof s?i=parseFloat(s)||3:"number"==typeof s&&(i=s);let o=a;"125px"===a&&"3em"!==s&&(o=i/3*125+"px");const c={fontSize:s,paddingRight:n,WebkitBackgroundSize:o+" 100%",MozBackgroundSize:o+" 100%",backgroundSize:o+" 100%",...t};return h("div",{className:"react-ai-agent-shimmer-text shimmer "+(r?"dark":"light"),style:c,children:e})},me=({message:e,title:t,isProcessing:s,isFinished:n,icon:a,iconComponent:r,isFlat:o=!0,onClick:c,isDark:l=!1,unmountOnExit:d,action:g,data:m,className:p,style:f,metadata:y})=>{const x=g||e?.action,w=m||e?.data,b=void 0!==n?n:e?.isFinished,v=void 0!==s?s:!b,k=y||e?.metadata,S=t||k?.name||e?.title,M=r||e?.iconComponent,C=void 0!==o?o:void 0===e?.isFlat||e.isFlat,I=void 0!==d?d:e?.unmountOnExit,N=c,T=k?.icon||a,A=i(()=>S?v?`Processing ${S}...`:"Finished "+S:x?(({data:e,action:t,isFinished:s})=>{if(!t||"string"!=typeof t)return"Processing...";try{const n=t.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().split(/\s+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ");return s?n:`${n}${e?.tool?" "+e?.tool:""}...`}catch(n){return t}})({data:w,action:x,isFinished:b}):"Processing...",[S,x,b,w]);return h("div",C?{className:"mx-auto mb-1 "+p,style:{cursor:N?"pointer":"default",...f},onClick:N,children:u("div",{className:`flex items-center gap-3 px-0 rounded-[12px] text-${l?"white":"black"} relative overflow-auto`,children:[I?h("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${l?"white":"black"} rounded-full border-t-transparent opacity-50`}):M?M():te(T||"check circle-3-1660219236.png",20,l?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)",{position:"absolute"}),v?h(ge,{isDark:l,text:A,style:{fontSize:"14px",marginLeft:"30px"}}):h("span",{style:{color:l?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)"},className:"text-[14px] ml-[30px] "+(M?"!ml-0":""),children:A})]})}:{className:"mb-[10px] mx-auto "+p,style:{cursor:N?"pointer":"default",...f},onClick:N,children:u("div",{className:`flex items-center p-3 rounded-[12px] text-${l?"white":"black"} relative overflow-hidden`,style:{backgroundColor:l?"rgba(255,255,255,0.02)":"rgba(0,0,0,0.02)"},children:[v?h("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${l?"white":"black"} rounded-full border-t-transparent opacity-50`}):M?M():te(icon||"check circle-3-1660219236.png",20,l?"rgba(255,255,255,0.8)":"rgba(0,0,0,0.8)",{position:"absolute"}),h("div",{className:"flex-1",children:v?h(ge,{isDark:l,text:A,style:{marginLeft:"28px",marginTop:"-2px",color:l?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.2)"}}):h("span",{className:`text-[14px] text-${l?"white":"black"}/50 ml-[30px]`,children:A})})]})})};var pe=c(({item:e,removeMessage:t,allowEditMessage:s,animationConfig:n,isInCurrentSession:a})=>h("div","user"===e.sender?{className:"react-ai-agent-message-item react-ai-agent-message-user",children:h(oe,{message:e,allowEdit:s})}:"status"===e.type&&e.action?{className:"react-ai-agent-message-item react-ai-agent-message-status",children:h(X[e.action]||me,{message:e})}:"thinking"===e.type?{className:"react-ai-agent-message-item react-ai-agent-message-thinking",children:h(ue,{message:e,removeMessage:t,isInCurrentSession:a})}:{className:"react-ai-agent-message-item react-ai-agent-message-ai",children:h(de,{message:e,animationConfig:n,isInCurrentSession:a})}));const fe=({type:e})=>{const t=["w-1.5 h-1.5","w-2.5 h-2.5","w-1.5 h-1.5"],s="text"===e?["L","O","A","D","I","N","G"]:Array.from({length:3}).fill(""),n=.6+.1*(s.length-1);return h("div",{className:"react-ai-agent-loading-response flex",children:h("div",{className:"react-ai-agent-loading-content flex justify-center items-center "+("text"===e?"text-7xl font-extrabold font-[Montserrat]":"gap-1.5"),children:s.map((s,a)=>h(x.span,{className:`react-ai-agent-loading-item react-ai-agent-loading-item-${e} inline-block ${"text"===e?"mx-[-0.05em]":t[a]+" rounded-full bg-inverse"}`,animate:{scale:[.75,1.5,.75],opacity:[.75,1,.75],filter:["blur(4px)","blur(0px)","blur(4px)"]},transition:{repeat:1/0,duration:.6,ease:"easeInOut",repeatDelay:n-.6,delay:.1*a},children:"text"===e?s:""},a))})})},ye=({messages:e,isLoading:t,isResponseStarted:s,showLoadingIndicator:n,showSpacer:a=!1,spacerKey:r=0,onSpacerComplete:o})=>i(()=>{const i=[...e];return a&&i.push({type:"viewport-spacer",messageId:"viewport-spacer-"+r,onComplete:o,isResponseStarted:s}),n&&t&&!s&&i.push({type:"loading-indicator",messageId:"loading-indicator"}),i},[e,n,t,s,a,r,o]),xe=e=>i(()=>{for(let t=e.length-1;t>=0;t--)if("user"===e[t].sender)return t;return-1},[e]),we=({item:e,index:t,lastUserIndex:s,removeMessage:n,allowEditMessage:a,animationConfig:r,isLastItem:i=!1,isFirstItem:o=!1})=>{if(!e)return null;if("viewport-spacer"===e.type)return h(ie,{onComplete:e.onComplete,isResponseStarted:e.isResponseStarted});if("loading-indicator"===e.type)return h(fe,{});if("empty-message"===e.type)return h("div",{style:{paddingTop:"100px"}});const c=h(pe,{item:e,removeMessage:n,allowEditMessage:a,animationConfig:r,isInCurrentSession:t>s});return i?h("div",{style:{paddingBottom:"200px"},children:c}):o?h("div",{style:{paddingTop:"100px"},children:c}):c},be=({messages:e,removeMessage:t,allowEditMessage:s,animationConfig:a,height:r,width:i,shouldAutoScrollRef:c,isLoading:l,isResponseStarted:d,showLoadingIndicator:u,showSpacer:g,spacerKey:p,onSpacerComplete:f})=>{const y=n(!0),x=ye({messages:e,isLoading:l,isResponseStarted:d,showLoadingIndicator:u,showSpacer:g,spacerKey:p,onSpacerComplete:f}),w=xe(e),b=o(e=>{y.current=e,c&&(c.current=e)},[c]);o(()=>"smooth",[]);const v=o(e=>we({item:x[e],index:e,lastUserIndex:w,removeMessage:t,allowEditMessage:s,isLastItem:e===x.length-1,animationConfig:a}),[x,w,t,s,a]);return h(m,{style:{height:r,width:i},data:x,totalCount:x.length,itemContent:v,initialTopMostItemIndex:x.length-1,atBottomStateChange:b,alignToBottom:!0})},ve=({dynamicHeight:e,messages:t,removeMessage:s,allowEditMessage:a,animationConfig:r,height:c,width:l,overscan:d,listRef:u,isLoading:g,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:y,onSpacerComplete:x})=>{const w=ye({messages:t,isLoading:g,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:y,onSpacerComplete:x}),v=xe(t),k=n(new Map),S=i(()=>({itemsData:w,removeMessage:s,allowEditMessage:a,animationConfig:r,dynamicHeight:e,lastUserIndex:v,heightCacheRef:k}),[w,s,a,r,e,v]),M=o(({index:e,style:t,ariaAttributes:s,...n})=>{const{itemsData:a,removeMessage:r,allowEditMessage:i,animationConfig:o,dynamicHeight:c,lastUserIndex:l,heightCacheRef:d}=n;return h("div",{style:t,ref:t=>{if(t){const s=a[e],n=s?.uniqueKey||s?.messageId||e;d.current.has(n)||requestAnimationFrame(()=>{const s=t.getBoundingClientRect().height;s!==c.getRowHeight(e)&&(c.setRowHeight(e,s),d.current.set(n,s))})}},...s,children:we({item:a[e],index:e,lastUserIndex:l,removeMessage:r,isLastItem:e===a.length-1,allowEditMessage:i,animationConfig:o})})},[]);return h("div",{style:{height:c,width:l,overflow:"hidden"},children:h(b,{listRef:u,rowComponent:M,rowCount:w.length,rowHeight:e,rowProps:S,overscanCount:d})})},ke=({itemsData:e,scrollToBottom:t,shouldAutoScrollRef:s,isStreaming:r})=>{const i=n(0),o=n(!1);a(()=>{!o.current&&e.length>0&&(o.current=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{t(!1)})}))},[]),a(()=>{e.length>i.current&&(i.current=e.length,!1!==s?.current&&t(!0))},[e.length,t,s]),a(()=>{if(!r)return;const e=setInterval(()=>{!1!==s?.current&&t(!1)},100);return()=>clearInterval(e)},[r,t,s])},Se=({messages:e,removeMessage:t,allowEditMessage:s,animationConfig:a,height:r,width:i,isStreaming:c,shouldAutoScrollRef:l})=>{const d=n(null),u=[{type:"empty-message",messageId:"empty-message"},...e],g=xe(e),m=o(e=>{const t=u[e];if(!t)return 100;if("empty-message"===t.type)return 100;if("loading-indicator"===t.type)return 80;if("viewport-spacer"===t.type)return 100;let s=80;const n=t.text||t.content||"",a=n.length;if(0===a)return s;s+=24*Math.ceil(a/90),"thinking"===t.type?s+=40:"status"===t.type&&(s+=30);const r=(n.match(/```/g)||[]).length/2;return r>0&&(s+=100*r),0===e&&(s+=100),e===u.length-1&&(s+=200),Math.max(s,60)},[u]),p=v({count:u.length,getScrollElement:()=>d.current,estimateSize:m,overscan:10}),{handleScroll:f}=(e=>{const t=n(!1),s=n(null),a=o(n=>{s.current&&clearTimeout(s.current),t.current=!0,s.current=setTimeout(()=>{t.current=!1},150),n&&e&&(e.current=50>Math.abs(n.scrollHeight-n.scrollTop-n.clientHeight))},[e]);return{isUserScrollingRef:t,handleScroll:a}})(l),y=o((e=!0)=>{const t=d.current;t&&t.scrollTo({top:t.scrollHeight,behavior:e?"smooth":"auto"})},[]);ke({itemsData:u,scrollToBottom:y,shouldAutoScrollRef:l,isStreaming:c});const x=p.getVirtualItems();return h("div",{ref:d,onScroll:()=>f(d.current),className:"tanstack-virtual-container",style:{height:r,width:i,overflowY:"auto",contain:"strict"},children:h("div",{style:{height:p.getTotalSize()+"px",width:"100%",position:"relative"},children:x.map(e=>h("div",{"data-index":e.index,ref:p.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${e.start}px)`},children:we({item:u[e.index],index:e.index,lastUserIndex:g,removeMessage:t,allowEditMessage:s,animationConfig:a,isLastItem:e.index===u.length-1,isFirstItem:0===e.index})},e.key))})})},Me=({messages:e,removeMessage:t,allowEditMessage:s,animationConfig:n,scrollToBottom:a,shouldAutoScrollRef:r,isStreaming:i,scrollContainerRef:o,height:c,width:l,isLoading:d,isResponseStarted:u,showLoadingIndicator:g,showSpacer:m,spacerKey:p,onSpacerComplete:f})=>{const y=ye({messages:e,isLoading:d,isResponseStarted:u,showLoadingIndicator:g,showSpacer:m,spacerKey:p,onSpacerComplete:f}),x=xe(e);return ke({itemsData:y,scrollToBottom:e=>a(),shouldAutoScrollRef:r,isStreaming:i}),h("div",{ref:o,className:"react-chat-core-simple-container overflow-y-auto scrollbar-hide",style:{height:c,width:l,overflowY:"auto"},children:y.map((e,a)=>e?h("div",{children:we({item:e,index:a,lastUserIndex:x,removeMessage:t,allowEditMessage:s,animationConfig:n})},e.uniqueKey||e.messageId||a):null)})},Ce=l(({virtualization:e="tanstack",estimateSize:t=150,overscan:s=10,isDark:i=!1,className:c="",containerStyle:l={},useGradientMask:g=!0,gradientMaskStyle:m="linear-gradient(to bottom, transparent 6.5%, black 18%)",allowEditMessage:p=!1,showWelcome:f=!0,showLoadMore:y=!0,showLoadingIndicator:x=!0,keepUserMessageInView:b=!0,welcomeComponent:v,loadingComponent:k,initialAnimation:S=null,height:M="100%",width:C="100%"},I)=>{const[N,T]=r(!1),[A,F]=r(!1),E=n(null),{sendMsg:R,messages:z,messageManager:H,isLoading:_,isStreaming:L,isPanelOpen:D,error:q,isInitialLoading:O,isResponseStarted:P,abort:j,loadMoreMessages:B,isLoadingMore:U,hasMoreMessages:$,enableHistory:W,animationConfig:Y,loadingComponent:J}=K(),X=k||J,{showSpacer:G,spacerKey:Q,triggerSpacer:V,handleSpacerComplete:Z}=(()=>{const[e,t]=r(!1),[s,n]=r(0);return{showSpacer:e,spacerKey:s,triggerSpacer:()=>{t(!0),n(e=>e+1)},handleSpacerComplete:()=>{t(!1)}}})(),{scrollContainerRef:ee,shouldAutoScrollRef:te,scrollToBottom:ne,isAtBottom:ie}=(({onGradientChange:e,isStreaming:t})=>{const s=n(null),r=n(!0),i=n(!1),c=o(()=>{const e=s.current;e&&(e.scrollTop=e.scrollHeight)},[]),l=o(()=>{const e=s.current;return!!e&&50>e.scrollHeight-e.scrollTop-e.clientHeight},[]),d=o(()=>{const t=s.current;if(!t)return;const n=t.scrollTop>20;n!==i.current&&(i.current=n,e&&e(n)),r.current=l()},[l,e]),h=o((e=>{let t=0;return function(...s){const n=Date.now();100>n-t||(t=n,e(...s))}})(d),[d]);return a(()=>{const e=s.current;if(e)return e.addEventListener("scroll",h),()=>e.removeEventListener("scroll",h)},[h]),a(()=>{if(!t)return;const e=setInterval(()=>{r.current&&c()},100);return()=>clearInterval(e)},[t,c]),{scrollContainerRef:s,shouldAutoScrollRef:r,scrollToBottom:c,isAtBottom:l}})({onGradientChange:T,isStreaming:"none"===e&&L}),oe="react-window"===e?(({estimateSize:e})=>w({defaultRowHeight:e}))({estimateSize:t}):null,ce=o(()=>{"virtuoso"!==e&&"tanstack"!==e&&("react-window"===e&&E.current?.scrollToBottomCustom?E.current.scrollToBottomCustom():"none"===e&&ne())},[e,ne]),le=o(()=>{b&&setTimeout(()=>{V()},200)},[b,V]),{removeMessage:de,handleSendMessage:he}=(({messageManager:e,sendMsg:t,shouldAutoScrollRef:s,onUserMessageSent:n})=>({removeMessage:o(t=>{e?.removeMessage&&e.removeMessage(t)},[e]),handleSendMessage:o(async e=>{s&&(s.current=!0),n&&n(),await t(e)},[t,s,n])}))({messageManager:H,sendMsg:R,scrollToBottom:ce,shouldAutoScrollRef:te,onUserMessageSent:le});return a(()=>{if(O)F(!1);else{if(z&&z.length>0&&!A){const e=setTimeout(()=>{F(!0)},100);return()=>clearTimeout(e)}z&&0!==z.length||F(!0)}},[O,z,A]),d(I,()=>({scrollToBottom:ce,isAtBottom:ie,scrollContainer:ee.current,dynamicHeight:oe,listRef:E.current,sendMessage:he,abort:j,isStreaming:L,isLoading:_,messages:z,messageManager:H}),[ce,ie,oe,he,j,L,_,z,H]),h("div",{className:"react-ai-agent-chat-core "+c,"data-theme":i?"dark":"light",style:{WebkitMaskImage:m,...l},children:O?h(X||re,{}):z&&0!==z.length?u("div",{className:"react-chat-core-messages h-full w-full",style:{opacity:A?1:0,transition:"opacity 0.3s ease-out"},children:[h(se,{showLoadMore:y,enableHistory:W,hasMoreMessages:$,messagesLength:z.length,error:q,isInitialLoading:O,loadMoreMessages:B,isLoadingMore:U}),(()=>{const t={messages:z,removeMessage:de,allowEditMessage:p,animationConfig:Y,isLoading:_,isResponseStarted:P,showLoadingIndicator:x,isStreaming:L,showSpacer:b&&G,spacerKey:Q,onSpacerComplete:Z};switch(e){case"virtuoso":return h(be,{height:M,width:C,listRef:E,shouldAutoScrollRef:te,...t});case"react-window":return h(ve,{dynamicHeight:oe,height:M,width:C,overscan:s,listRef:E,isStreaming:L,shouldAutoScrollRef:te,...t});case"tanstack":return h(Se,{height:M,width:C,isStreaming:L,shouldAutoScrollRef:te,...t});default:return h(Me,{scrollToBottom:ce,shouldAutoScrollRef:te,isStreaming:L,scrollContainerRef:ee,height:M,width:C,...t})}})()]}):f&&h("div",{style:{opacity:A?1:0,height:"100%",width:"100%",transition:"opacity 0.3s ease-out"},children:h(ae,{WelcomeComponent:v,error:q,isPanelOpen:D})})})});Ce.displayName="ChatCore";var Ie=c(Ce);const Ne=({todos:e=[]})=>e&&0!==e?.length?h("div",{className:"react-ai-agent-queue-manager flex w-[calc(100%-50px)] ml-[5px] items-end gap-2 top-0 z-9 absolute h-0",children:u("div",{className:"react-ai-agent-queue-manager-wrapper flex items-center w-full relative bottom-0",children:[h("div",{className:"react-ai-agent-queue-manager-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay border-b-0 rounded-t-[15px] "}),h("div",{className:"react-ai-agent-queue-manager-content flex items-center gap-2 w-full p-1 py-[5px] z-99"})]})}):null,Te=({children:e,content:t,visible:s})=>s?u("div",{className:"react-ai-agent-tooltip-wrapper relative",children:[e,u("div",{className:"react-ai-agent-tooltip absolute bottom-full right-0 mb-2 w-64 p-3 bg-theme-surface rounded-lg shadow-lg z-50 backdrop-blur-sm",children:[h("div",{className:"react-ai-agent-tooltip-content text-theme-secondary text-sm space-y-2",children:t}),h("div",{className:"react-ai-agent-tooltip-arrow absolute top-full right-4 w-2 h-2 bg-theme-surface transform rotate-45 translate-y-[-4px]"})]})]}):e,Ae=()=>{const[e,t]=r(!1),{sessionMetrics:s,usedTokens:n,contextLimit:a}=K(),i=(100*(n/a||0)).toFixed(2),o=e=>e?1e6>e?1e3>e?""+e:(e/1e3).toFixed(1)+"K":(e/1e6).toFixed(1)+"M":"0",c=u("div",{className:"space-y-2",children:[h("div",{className:"font-medium text-theme-primary border-b border-theme-tertiary pb-1",children:"Session Info"}),u("div",{className:"space-y-1 text-xs",children:[u("div",{className:"flex justify-between",children:[h("span",{className:"text-theme-quaternary",children:"Context size:"}),u("span",{children:[o(s?.contextUsed)," / ",o(s?.contextLimit)]})]}),u("div",{className:"flex justify-between",children:[h("span",{className:"text-theme-quaternary",children:"Session Tokens:"}),h("span",{children:o(s?.tokensUsed)})]}),u("div",{className:"flex justify-between",children:[h("span",{className:"text-theme-quaternary",children:"All time tokens:"}),h("span",{children:o(s?.allTimeTokens)})]}),u("div",{className:"flex justify-between",children:[h("span",{className:"text-theme-quaternary",children:"Requests:"}),h("span",{children:o(s?.requests)})]})]})]});return h(Te,{content:c,visible:e,children:u("div",{className:"react-ai-agent-progress-bar flex items-center gap-2 cursor-pointer",onMouseEnter:()=>t(!0),onMouseLeave:()=>t(!1),children:[u("span",{className:"react-ai-agent-progress-percentage text-theme-ghost font-light text-[12px] leading-[18px]",children:[i,"%"]}),u("div",{className:"react-ai-agent-progress-circle-wrapper relative w-4 h-4 flex items-center justify-center",children:[h("div",{className:"react-ai-agent-progress-circle-bg absolute inset-0 rounded-full bg-theme-muted"}),h("div",{className:"react-ai-agent-progress-circle-fill absolute inset-0 rounded-full",style:{background:`conic-gradient(var(--rca-text-faint) ${i}%, transparent 0)`}}),h("div",{className:"react-ai-agent-progress-circle-inner absolute inset-0.5 rounded-full bg-secondary"})]})]})})},Fe=({attachedFiles:e=[],removeFile:t})=>{const{currentSelectedFile:s,setIsHoldEnabled:n,setCurrentSelectedFile:a,manuallyAddedFiles:r=[],setManuallyAddedFiles:i=()=>{}}=K(),o=[...s?[s]:[],...r,...e];return u("div",{className:"react-ai-agent-chat-bar flex items-center w-full mb-2 justify-between",children:[u("div",{className:"react-ai-agent-chat-bar-left flex items-center",children:[o.length>0&&h(Re,{files:o,handleRemoveFile:e=>{"object"==typeof e&&e.id?t&&t(e.id):e===s?(a(null),n(!1)):i(t=>t.filter(t=>t!==e))}}),u("button",{className:"react-ai-agent-context-button text-theme-primary hover:opacity-100 opacity-25 mr-2 flex items-center gap-1 whitespace-nowrap right-0 z-9 text-[12px] leading-relaxed ",children:[h("span",{className:"react-ai-agent-context-button-icon",children:te("add",20,"currentColor",{marginLeft:"-5px"})}),0===o.length&&h("span",{className:"react-ai-agent-context-button-label",children:"Context"})]})]}),h("div",{className:"react-ai-agent-chat-bar-right",children:h(Ae,{})})]})},Ee=({file:e,handleRemoveFile:t})=>{const[s,n]=r(!1),a="object"==typeof e&&e.id,i=a?e.name:e.split("/").pop(),o=a?e.id:e;return u("div",{className:"react-ai-agent-file-item flex items-center gap-2 px-2 py-[2px] bg-theme-subtle rounded-full cursor-pointer relative border border-theme-subtle",onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:[s?h("button",{className:"react-ai-agent-file-item-remove w-[16px] opacity-50 hover:opacity-100 -ml-[2px] -mr-[2px] h-[16px]",onClick:s=>{s.stopPropagation(),t(e)},children:h("span",{className:"react-ai-agent-file-item-remove-icon",children:te("close",16,"currentColor")})}):h("div",{className:"react-ai-agent-file-item-icon-wrapper",children:a&&e.preview?h("img",{src:e.preview,alt:i,className:"react-ai-agent-file-item-preview w-3 h-4 object-cover rounded",style:{marginRight:0,width:"12px",height:"16px"}}):h(FileIcon,{fileName:i,style:{marginRight:0,width:"12px",height:"16px"}})}),h("div",{className:"react-ai-agent-file-item-name text-theme-quaternary hover:text-theme-primary text-[12px] leading-relaxed whitespace-nowrap truncate max-w-[100px]",children:i})]},o)},Re=({files:e,handleRemoveFile:t})=>h("div",{className:"react-ai-agent-file-items flex items-center gap-2 mr-2",children:e.map(e=>h(Ee,{file:e,handleRemoveFile:t},"object"==typeof e&&e.id?e.id:e))}),ze=()=>{const[e,t]=r(0),s=n(),i=n(0),o=n(0),c=n(null),l=n(1);return a(()=>{const e=()=>{if(c.current){const{width:e,height:t}=c.current.getBoundingClientRect();l.current=e/t}};e();const t=new ResizeObserver(e);return c.current&&t.observe(c.current),()=>{t.disconnect()}},[]),a(()=>{o.current=performance.now(),i.current=e;const n=a=>{const r=a-o.current;o.current=a,i.current+=r/1e3*360,360>i.current||(i.current-=360);const c=i.current*(Math.PI/180),d=l.current,h=Math.round((Math.atan2(Math.sin(c),Math.cos(c)/d)*(180/Math.PI)+360)%360);3>Math.abs(h-e)||t(h),s.current=requestAnimationFrame(n)};return s.current=requestAnimationFrame(n),()=>{s.current&&(cancelAnimationFrame(s.current),s.current=null)}},[]),h("div",{ref:c,className:"react-ai-agent-loader-animation w-full h-full absolute inset-0 rounded-[inherit]",children:h("div",{className:"glowing pointer-events-none absolute inset-0 rounded-[inherit] opacity-100 transition-opacity safari:!hidden style_glowingEffect__yGXeX",style:{"--blur":"1px","--spread":"30","--active":"1","--start":e,display:"flex"},children:h("div",{className:"style_glow__i4Qpo"})})})},He="image/*,video/*,audio/*,.pdf,.doc,.docx,.txt,.md,.json,.js,.ts,.jsx,.tsx,.py,.html,.css,.xml,.csv";function _e(){const[e,t]=r([]),s=n(null),a=o(async e=>{const t=await e.arrayBuffer(),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(e=>e.toString(16).padStart(2,"0")).join("")},[]),i=o(async s=>{const n=[];for(const t of s){if(e.some(e=>e.name===t.name&&e.size===t.size&&e.type===t.type))continue;let s=!1;if(5242880>t.size)try{const r=await a(t);e.some(e=>e.hash===r)||(n.push({file:t,id:Date.now()+Math.random(),name:t.name,size:t.size,type:t.type,hash:r,preview:t.type.startsWith("image/")?URL.createObjectURL(t):null}),s=!0)}catch(r){}s||n.push({file:t,id:Date.now()+Math.random(),name:t.name,size:t.size,type:t.type,preview:t.type.startsWith("image/")?URL.createObjectURL(t):null})}n.length>0&&t(e=>[...e,...n])},[e,a]),c=o(e=>{const t=Array.from(e.target.files||[]);t.length>0&&i(t),e.target.value=""},[i]),l=o(e=>{const t=Array.from(e.clipboardData?.items||[]).filter(e=>"file"===e.kind).map(e=>e.getAsFile()).filter(Boolean);t.length>0&&(e.preventDefault(),i(t))},[i]),d=o(e=>{t(t=>{const s=t.filter(t=>t.id!==e),n=t.find(t=>t.id===e);return n?.preview&&URL.revokeObjectURL(n.preview),s})},[]),h=o(()=>{t(e=>(e.forEach(e=>{e.preview&&URL.revokeObjectURL(e.preview)}),[]))},[]);return{attachedFiles:e,fileInputRef:s,onFileSelect:c,onPaste:l,removeFile:d,clearFiles:h}}const Le=()=>{const{streamError:e,clearStreamError:t,retryLastMessage:s,sendRequestCallback:n,triggerLoadingStates:a}=K(),[i]=r(e?.choices||[{id:"retry",label:"Retry"},{id:"cancel",label:"Cancel"}]);return e?h("div",{className:"react-ai-agent-stream-error w-full mb-3",children:u("div",{className:"react-ai-agent-error-content flex w-full justify-between items-center gap-3 px-3 py-2 bg-theme-faint rounded-lg border-l-2 border-[#ef4444]",children:[h("div",{className:"react-ai-agent-error-message-wrapper",children:h("div",{className:"react-ai-agent-error-message text-[12px] text-theme-primary font-medium",children:e.message||"An error occurred during streaming"})}),h("div",{className:"react-ai-agent-error-actions flex gap-2 items-center",children:i&&i.length>0&&i.map(r=>h("button",{onClick:()=>(async r=>{"retry"===r?"connection_error"===e.errorType?await s():(a(),n({type:"stream_error",callback:"retry",requestId:e.requestId})):"cancel"===r&&(e.requestId&&n({type:"stream_error",callback:"cancel",requestId:e.requestId}),t())})(r.id),className:`react-ai-agent-error-action react-ai-agent-error-action-${r.id} text-[11px] font-medium px-3 py-1 rounded-md transition-all duration-200\n ${"retry"===r.id?"text-theme-primary hover:text-theme-secondary underline underline-offset-2":"cancel"===r.id?"text-theme-subtle hover:text-theme-tertiary":"text-theme-tertiary hover:text-theme-primary"}\n `,children:r.label},r.id))})]})}):null},De=({agents:e=[],selectedAgentId:t,onAgentChange:s,disabled:i=!1})=>{const[o,c]=r(!1),l=n(null),d=e.find(e=>e.id===t)||e[0],[g,m]=r(d?.id||e[0]?.id);a(()=>{const e=e=>{l.current&&!l.current.contains(e.target)&&c(!1)};return o&&document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[o]);const p=e.find(e=>e.id===g)||d||e[0];return p?u("div",{className:"react-ai-agent-switch relative",ref:l,children:[u("button",{type:"button",onClick:()=>!i&&c(!o),disabled:i,className:"react-ai-agent-switch-button flex justify-center p-1 px-3 mr-2 items-center cursor-pointer text-theme-primary rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap hover:bg-theme-muted border border-transparent hover:border-theme-border",style:{background:o?"var(--rca-bg-muted)":"transparent"},children:[h("span",{className:"mr-2",children:te("brain",18,"currentColor")}),h("span",{className:"react-ai-agent-switch-label text-[13px] mr-2 text-theme-primary font-[400]",children:p.name||p.model||"Agent"}),h("span",{style:{transform:o?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease",display:"inline-flex",opacity:.6},children:te("arrowDown",14,"currentColor")})]}),o&&e.length>0&&h("div",{className:"react-ai-agent-switch-dropdown absolute bottom-full mb-2 right-0 max-w-[220px] min-w-[150px] rounded-xl overflow-hidden z-50 shadow-2xl",style:{background:"var(--rca-bg-surface)",border:"1px solid var(--border-tertiary)",backdropFilter:"blur(20px)"},children:h("div",{className:"react-ai-agent-switch-dropdown-content max-h-[320px] overflow-y-auto py-1",children:e.map(e=>{const t=e.id===g;return u("button",{type:"button",onClick:()=>(e=>{i||e.id===g||(m(e.id),s?.(e)),c(!1)})(e),className:"react-ai-agent-switch-option w-full flex items-center gap-3 px-4 py-2 text-left transition-all",style:{background:t?"var(--rca-bg-subtle)":"transparent",color:t?"var(--rca-text-primary)":"var(--rca-text-secondary)"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--rca-bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="transparent")},children:[h("span",{className:"flex-shrink-0",style:{opacity:.8},children:te("brain",18,"currentColor")}),u("div",{className:"flex-1 min-w-0",children:[h("div",{className:"flex items-center gap-2",children:h("div",{className:"react-ai-agent-switch-option-name text-[13px] font-medium",children:e.name})}),e.description&&h("div",{className:"react-ai-agent-switch-option-description text-[11px] mt-0.5 truncate",style:{color:"var(--text-quaternary)"},children:e.description})]}),t&&h("span",{className:"react-ai-agent-switch-option-check flex-shrink-0",style:{color:"var(--rca-text-accent)"},children:te("check",16,"currentColor")})]},e.id)})})})]}):null},qe=l(({onSendMessage:e,isStreaming:t,abort:s,mode:i="advanced",todos:o=[],agents:c=[],selectedAgentId:l,onAgentChange:m},p)=>{const[f,y]=r(""),x=n(null),{attachedFiles:w,fileInputRef:b,onFileSelect:v,onPaste:k,removeFile:S,clearFiles:M}=_e();a(()=>{x.current&&(x.current.style.height="auto",x.current.style.height=Math.min(x.current.scrollHeight,150)+"px")},[f]),d(p,()=>({focus:()=>{x.current?.focus()}}),[]);const C=t=>{t.preventDefault(),(f.trim()||w.length>0)&&(e({message:f,attachedFiles:w}),y(""),M(),x.current&&(x.current.style.height="auto"))},I="advanced"===i,N=c&&c.length>0;return h("div",{className:"react-ai-agent-input absolute mx-auto bottom-0 w-full p-[15px] right-0 left-0 max-w-[600px] z-2",children:u("div",{className:"react-ai-agent-input-wrapper mx-auto relative "+("advanced"===i?"min-h-[120px]":"min-h-[100px]"),children:[t&&h("div",{className:"absolute inset-0 pointer-events-none rounded-[15px]",style:{zIndex:1},children:h(ze,{})}),h("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay rounded-[15px]"}),u("div",{className:"react-ai-agent-input-content pt-[15px] px-[20px] mx-auto relative z-99 "+("advanced"===i?"min-h-[120px]":"min-h-[100px]"),style:{zIndex:2},children:[I&&u(g,{children:[h(Ne,{todos:o}),h(Le,{}),h(Fe,{attachedFiles:w,removeFile:S})]}),h("div",{className:`react-ai-agent-input-textarea-wrapper relative pb-[${"advanced"===i?"50px":"0px"}]`,children:h("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:x,value:f,onChange:e=>y(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),C(e))},onPaste:k,placeholder:"Type a message...",className:"react-ai-agent-textarea w-full text-[14px] text-theme-primary pr-12 min-h-[40px] max-h-[150px] resize-none outline-none bg-transparent",rows:1})}),u("div",{className:"react-ai-agent-input-actions flex items-center justify-between mt-auto bottom-[15px] absolute w-[calc(100%-40px)]",children:[h("input",{ref:b,type:"file",multiple:!0,accept:He,onChange:v,className:"react-ai-agent-file-input hidden"}),h("div",{className:"react-ai-agent-input-actions-left flex items-center gap-2",children:"default"===i&&w.length>0?u("div",{className:"flex items-center gap-2",children:[h(Re,{files:w,handleRemoveFile:e=>S(e.id)}),h("button",{type:"button",onClick:()=>b.current?.click(),className:"react-ai-agent-attach-button-add flex justify-center items-center cursor-pointer text-theme-primary rounded-full transition-colors hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed w-[24px] h-[24px]",children:te("add",20,"currentColor")})]}):u("button",{type:"button",onClick:()=>b.current?.click(),className:"react-ai-agent-attach-button flex justify-center items-center cursor-pointer text-theme-primary rounded-full transition-colors hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed",children:[te("attach",18,"currentColor"),h("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})}),u("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[N&&h(De,{agents:c,selectedAgentId:l,onAgentChange:m,disabled:t}),h("button",{type:"button",onClick:e=>{t?s():C(e)},className:"react-ai-agent-send-button w-[30px] h-[30px] flex justify-center items-center cursor-pointer bg-inverse text-inverse rounded-full hover:scale-110 transition-transform disabled:opacity-50 disabled:cursor-not-allowed",disabled:!f.trim()&&!t,children:te(t?"square":"send",t?15:20,"currentColor")})]})]})]})]})})});qe.displayName="ChatInputDefault";var Oe=c(qe),Pe=c(({isDark:e=!1,onCreateSession:t,onClose:s,showCloseButton:n=!1})=>{const[a,i]=r(!1),[o,c]=r(!1),{headerComponent:l}=K();return l?l():u("div",{className:"react-ai-agent-header flex justify-between items-center py-2 px-5 absolute top-0 left-0 right-0 z-10",children:[u("div",{className:"react-ai-agent-header-left flex items-center gap-4 opacity-50",children:[h("button",{className:"react-ai-agent-header-new-chat flex items-center cursor-pointer hover:opacity-80",style:{opacity:a?.5:1,cursor:a?"progress":"pointer"},disabled:a,onClick:async({replace:e=!1}={})=>{if(i(!0),t)try{await t({replace:e})}catch(s){}finally{i(!1)}else setTimeout(()=>{i(!1)},1e3)},children:te("add",25,e?"#fff":"#000")}),h("div",{className:"react-ai-agent-header-history flex items-center cursor-pointer hover:opacity-80",onClick:o?()=>c(!1):()=>c(!0),children:te(o?"close":"history",18,e?"#fff":"#000")})]}),n&&s?h("button",{className:"react-ai-agent-header-close flex items-center cursor-pointer hover:opacity-80 opacity-50 transition-opacity",onClick:s,"aria-label":"Close panel",children:te("close",24,e?"#fff":"#000")}):h("div",{className:"react-ai-agent-header-right w-[80px]"})]})});const je=c(({coreRef:e,isDark:t,allowEditMessage:s,onCreateSession:n,handleSendMessage:a,isStreaming:r,abort:i,coreProps:o,inputProps:c,children:l,onClose:d,showCloseButton:g=!1,className:m=""})=>u("div",{className:"react-ai-agent flex flex-col h-full relative chat-panel "+m,"data-theme":t?"dark":"light",children:[h(Pe,{isDark:t,onCreateSession:n,onClose:d,showCloseButton:g}),u("div",{className:"relative flex-grow w-full max-w-[600px] mx-auto h-full min-w-[300px]",children:[h(Ie,{ref:e,isDark:t,allowEditMessage:s,className:"px-[15px]",...o}),h(Oe,{onSendMessage:a,isStreaming:r,abort:i,...c})]}),l]}));je.displayName="ChatPanelContent";const Be=({isOpen:e,isDragging:t,isDark:s=!0})=>h("div",{className:`\n w-16 h-16 rounded-full flex items-center justify-center\n transition-all duration-300 ease-out\n ${t?"scale-95":"hover:scale-105 active:scale-95"}\n text-black z-99 bg-white\n `,style:{boxShadow:e?"0 10px 25px -5px rgba(0, 0, 0, 0.15), 0 8px 10px -6px rgba(0, 0, 0, 0.1)":"0 20px 40px -10px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.05)"},children:te(e?"close%20remove-8-1662452248.png":"chat%20intelligence-48-1686045820.png",32,"currentColor")}),Ue=c(({onClick:t,isDark:s=!1,isOpen:i=!1,onPositionChange:c,livePositionUpdate:l=!0,edgeOffset:d=20,ContentComponent:u=Be,onOpen:g,onClose:m,onDrag:p})=>{const f="react-ai-agent-floating-button-position",y=n(null),[x,w]=r({width:64,height:64}),b="number"==typeof d?d:d?.x??20,v="number"==typeof d?d:d?.y??20,k=o(()=>"undefined"==typeof window?{minX:b,minY:v,maxX:1024-x.width-b,maxY:768-x.height-v,width:1024,height:768}:{minX:b,minY:v,maxX:window.innerWidth-x.width-b,maxY:window.innerHeight-x.height-v,width:window.innerWidth,height:window.innerHeight},[x,b,v]),S=o((e,t)=>{const s=k();return{x:Math.max(s.minX,Math.min(e,s.maxX)),y:Math.max(s.minY,Math.min(t,s.maxY))}},[k]),M=o(e=>{const t=k();return!(t.minX>e.x||t.minY>e.y||e.x>t.maxX||e.y>t.maxY)},[k]),C=o(()=>{const e=k(),{width:t,minX:s,minY:n,maxX:a,maxY:r}=e;return[{x:s,y:n,name:"top-left"},{x:(t-x.width)/2,y:n,name:"top-center"},{x:a,y:n,name:"top-right"},{x:s,y:r,name:"bottom-left"},{x:(t-x.width)/2,y:r,name:"bottom-center"},{x:a,y:r,name:"bottom-right"}]},[x,k]),I=o(()=>{if("undefined"==typeof window)return C()[5];try{const e=localStorage.getItem(f);if(e){const t=JSON.parse(e);if(M(t))return t}}catch(e){}return C()[5]},[C,M]),[N,T]=r(()=>I()),[A,F]=r(!1),[E,R]=r(!1),[z,H]=r({x:0,y:0}),[_,L]=r({x:0,y:0}),D=o((e,t)=>{const s=C();let n=s[0],a=1/0;return s.forEach(s=>{const r=Math.sqrt(Math.pow(s.x-e,2)+Math.pow(s.y-t,2));a>r&&(a=r,n=s)}),n},[C]),q=o(e=>{if(0!==e.button)return;const t=y.current.getBoundingClientRect(),s=e.clientX-t.left,n=e.clientY-t.top;H({x:e.clientX,y:e.clientY}),L({x:s,y:n}),F(!0),R(!1),p?.(!0),e.preventDefault()},[p]),O=o(e=>{if(!A)return;Math.sqrt(Math.pow(e.clientX-z.x,2)+Math.pow(e.clientY-z.y,2))>5&&R(!0);const t=S(e.clientX-_.x,e.clientY-_.y);T(t),l&&c&&c(t,!0,x)},[A,_,z,S,c,l]),P=o(e=>{if("undefined"!=typeof window)try{localStorage.setItem(f,JSON.stringify(e))}catch(t){}},[]),j=o(e=>{if(A)if(F(!1),p?.(!1),E){const e=D(N.x,N.y);T(e),P(e),c?.(e,!1,x)}else t?.()},[A,E,N,D,t,P,c,p]);return a(()=>{if(A)return document.addEventListener("mousemove",O),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",O),document.removeEventListener("mouseup",j)}},[A,O,j]),a(()=>{if("undefined"==typeof window)return;const e=()=>{if(M(N)){const e=D(N.x,N.y);T(e),P(e),c?.(e,!1,x)}else{const e=S(N.x,N.y),t=D(e.x,e.y);T(t),P(t),c?.(t,!1,x)}};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[N,D,P,M,S,c]),a(()=>{if("undefined"==typeof window||!y.current)return;const e=()=>{if(y.current){const e=y.current.getBoundingClientRect();w({width:e.width,height:e.height})}};e();const t=new ResizeObserver(()=>{e()});return t.observe(y.current),()=>{t.disconnect()}},[]),a(()=>{if("undefined"==typeof window||!N)return;const e=S(N.x,N.y);e.x===N.x&&e.y===N.y||(T(e),P(e),c?.(e,!1,x))},[x,S,c,N,P]),a(()=>{N&&c&&requestAnimationFrame(()=>{c(N,!1,x)})},[]),h("div",{ref:y,className:"fixed z-[9999] select-none",style:{left:N.x+"px",top:N.y+"px",transition:A?"none":"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",cursor:A?"grabbing":"grab",willChange:A?"transform":"auto",transform:"translate3d(0, 0, 0)"},onMouseDown:q,children:e.isValidElement(u)?e.cloneElement(u,{isOpen:i,isDragging:A,isDark:s,onOpen:g,onClose:m,onDrag:p}):u?h(u,{isOpen:i,isDragging:A,isDark:s,onOpen:g,onClose:m,onDrag:p}):h(Be,{isOpen:i,isDragging:A,isDark:s})})},(e,t)=>{const s="number"==typeof e.edgeOffset&&"number"==typeof t.edgeOffset?e.edgeOffset===t.edgeOffset:JSON.stringify(e.edgeOffset)===JSON.stringify(t.edgeOffset);return e.isDark===t.isDark&&e.isOpen===t.isOpen&&e.livePositionUpdate===t.livePositionUpdate&&s&&e.onClick===t.onClick&&e.onPositionChange===t.onPositionChange&&e.ContentComponent===t.ContentComponent&&e.onOpen===t.onOpen&&e.onClose===t.onClose&&e.onDrag===t.onDrag});Ue.displayName="FloatingAIButton";var $e=c(({isDark:e=!1,allowEditMessage:t=!1,children:s,onCreateSession:c,className:l="h-full w-full",coreProps:d={},inputProps:m={},mode:p="popup",livePositionUpdate:f=!0,popupOptions:y={},popupContainerClassName:x="",popupContainerStyle:w={},floatingButtonEdgeOffset:b=25,ContentComponent:v,onOpen:k,onClose:S,onDrag:M})=>{const C=i(()=>({width:y.width??400,height:y.height??600,gap:y.gap??16,verticalPadding:y.verticalPadding??24}),[y.width,y.height,y.gap,y.verticalPadding]),I=n(null),N=n(null),[T,A]=r("default"===p),[F,E]=r(!1),[R,z]=r(null),[H,_]=r({width:64,height:64}),[L,D]=r(!1),[q,O]=r("right"),[P,j]=r("bottom"),{sendMsg:B,isStreaming:U,abort:$}=K(),W=o(async e=>{I.current?.sendMessage?await I.current.sendMessage(e):(await B(e),setTimeout(()=>{I.current?.scrollToBottom()},100))},[B]),Y=o(()=>{N.current&&clearTimeout(N.current),E(!0),A(!0),k?.(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{E(!1)})})},[k]),J=o(()=>{N.current&&clearTimeout(N.current),A(!1),S?.(),E(!0),N.current=setTimeout(()=>{E(!1),N.current=null},450)},[S]),X=o(()=>{T?J():Y()},[T,Y,J]),G=o((e,t=!1,s={width:64,height:64})=>{if(D(t),z(e),_(s),!t&&"undefined"!=typeof window){const t=window.innerWidth,n=window.innerHeight,a=e.x+s.width/2;let r,i;r=t/3>a?"left":a>2*t/3?"right":"center",i=n/2>e.y+s.height/2?"top":"bottom",O(r),j(i)}},[]);a(()=>()=>{N.current&&clearTimeout(N.current)},[]);const Q=i(()=>{if(!R||"undefined"==typeof window)return{bottom:"96px",left:"50%"};const e=window.innerHeight;let t;return t="bottom"===P?e-R.y+C.gap:e-(R.y+H.height)-C.height-C.gap,{bottom:t+"px",left:R.x+H.width/2+"px"}},[R,H,P,C.gap,C.height]),V=i(()=>{if("undefined"==typeof window||!R)return"translateX(-50%) translateY(0)";const e=window.innerWidth,t=window.innerHeight,s=R.x+H.width/2,n=H.width/2;let a,r;r="left"===q?s-n:"right"===q?s+n-C.width:s-C.width/2,a=0>r?-s+"px":r+C.width>e?e-s-C.width+"px":"left"===q?-n+"px":"right"===q?`calc(-100% + ${n}px)`:"-50%";let i=0;if(!L)if("bottom"===P){const e=R.y-C.gap-C.height;C.verticalPadding>e&&(i=C.verticalPadding-e)}else{const e=R.y+H.height+C.gap+C.height;e>t-C.verticalPadding&&(i=t-C.verticalPadding-e)}return`translateX(${a}) translateY(${i}px)`},[q,P,R,H,L,C.width,C.gap,C.height,C.verticalPadding]);a(()=>{if("default"!==p&&"undefined"!=typeof window){const e=e=>{"Escape"===e.key&&T&&J()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)}},[p,T,J]);const Z=i(()=>({coreRef:I,isDark:e,allowEditMessage:t,onCreateSession:c,handleSendMessage:W,isStreaming:U,abort:$,coreProps:d,inputProps:m,children:s}),[e,t,c,W,U,$,d,m,s]);return"default"===p?h(je,{...Z,className:l}):u(g,"sliding"===p?{children:[T&&h("div",{className:"fixed inset-0 bg-black/50 z-[9990]",style:{backdropFilter:"blur(4px)",opacity:F?0:1,transition:"opacity 400ms cubic-bezier(0.4, 0, 0.2, 1)"},onClick:J}),h("div",{className:"fixed top-0 right-0 h-full z-[9995] shadow-2xl",style:{width:"min(600px, 100vw)",maxWidth:"100vw",backgroundColor:e?"#1a1a1a":"#ffffff",transform:T?"translateX(0)":"translateX(100%)",transition:"transform 400ms cubic-bezier(0.4, 0, 0.2, 1)"},children:h(je,{...Z,className:l,onClose:J,showCloseButton:!0})}),!T&&h(Ue,{onClick:Y,isDark:e,onPositionChange:G,livePositionUpdate:f,edgeOffset:b,ContentComponent:v,onOpen:k,onClose:S,onDrag:M})]}:{children:[(T||F)&&h("div",{className:"fixed z-[9995]",style:{bottom:Q.bottom,left:Q.left,transition:L?"none":"bottom 200ms cubic-bezier(0.4, 0, 0.2, 1), left 200ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:L?"bottom, left":"auto",pointerEvents:T?"auto":"none"},children:h("div",{className:("rounded-2xl shadow-2xl overflow-hidden "+x).trim(),style:{width:`min(${C.width}px, calc(100vw - 48px))`,height:`min(${C.height}px, calc(100vh - 160px))`,backgroundColor:e?"#1a1a1a":"#ffffff",transform:F?V+" translateY(30px) rotateX(15deg)":V+" rotateX(0deg)",transformOrigin:"bottom center",transformStyle:"preserve-3d",opacity:F?0:1,transition:"opacity 450ms cubic-bezier(0.4, 0, 0.2, 1), transform 450ms cubic-bezier(0.4, 0, 0.2, 1)",perspective:"1200px",...w},children:h(je,{...Z,className:l,onClose:J,showCloseButton:!0})})}),h(Ue,{onClick:X,isDark:e,isOpen:T,onPositionChange:G,livePositionUpdate:f,edgeOffset:b,ContentComponent:v,onOpen:k,onClose:S,onDrag:M})]})});const We={collapsed:{width:"280px",height:"60px",borderRadius:"50px",padding:"px-5 py-3",gap:"gap-2",showAttach:!1,showAgent:!1,showTopContent:!0,sendButtonSize:34,compact:!1},expanded:{width:"500px",height:"auto",minHeight:"120px",borderRadius:"20px",padding:"pt-[15px] px-[20px] pb-0",gap:"",showAttach:!0,showAgent:!0,showTopContent:!0,sendButtonSize:30,compact:!1},collapsedCompact:{width:"280px",height:"60px",borderRadius:"50px",padding:"px-3 py-3",gap:"gap-2",showAttach:!1,showAgent:!1,showTopContent:!1,sendButtonSize:34,compact:!0},expandedCompact:{width:"600px",height:"60px",minHeight:"60px",borderRadius:"50px",padding:"px-3 py-3",gap:"gap-2",showAttach:!0,showAgent:!1,showTopContent:!1,sendButtonSize:34,compact:!0}},Ye=l(({onSendMessage:e,miniMode:t=!1,isStreaming:s,abort:i,todos:o,variant:c="default",placeholder:l="Type a message...",collapsed:g=!1,onExpand:m,position:p="bottom-center",compact:f},y)=>{const[x,w]=r(""),[b,v]=r(!1),k=n(null),{attachedFiles:S,fileInputRef:M,onFileSelect:C,onPaste:I,removeFile:N,clearFiles:T}=_e();a(()=>{!g&&k.current&&(k.current.style.height="auto",k.current.style.height=Math.min(k.current.scrollHeight,150)+"px")},[x,g]),d(y,()=>({focus:()=>{k.current?.focus()}}),[]);const A=t=>{t.preventDefault(),(x.trim()||S.length>0)&&(e({message:x,attachedFiles:S}),w(""),T(),!g&&k.current&&(k.current.style.height="auto"))},F=f?g?We.collapsedCompact:We.expandedCompact:g?We.collapsed:We.expanded;return u("div",{className:"react-ai-agent-input-morph",style:{width:F.width,transition:"width 0.4s cubic-bezier(0.4, 0, 0.2, 1)"},"data-theme":"dark",children:[s&&!g&&h("div",{className:"absolute inset-0 pointer-events-none",style:{height:F.height,minHeight:F.minHeight||F.height,borderRadius:F.borderRadius,zIndex:1,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, border-radius "+(g?"0.15s cubic-bezier(0.4, 0, 0.2, 1) 0.3s":"0.15s cubic-bezier(0.4, 0, 0.2, 1)")},children:h(ze,{})}),u("div",{className:"react-ai-agent-input-wrapper relative",style:{height:F.height,minHeight:F.minHeight||F.height,zIndex:2,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s",overflow:"hidden"},children:[h("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay",style:{borderRadius:F.borderRadius,transition:g?"border-radius 0.15s cubic-bezier(0.4, 0, 0.2, 1) 0.3s":"border-radius 0.15s cubic-bezier(0.4, 0, 0.2, 1)"}}),u("div",{className:"relative z-10 h-full "+F.padding,style:{transition:"padding 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},children:[F.showTopContent&&u("div",{style:{opacity:g?0:1,height:g?0:"auto",overflow:"hidden",pointerEvents:g?"none":"auto",transition:g?"opacity 0.12s ease-out, height 0.15s ease-out":"opacity 0.3s ease-out 0.4s, height 0.3s ease-out 0.15s"},children:[h(Ne,{todos:o}),h(Le,{}),h(Fe,{attachedFiles:S,removeFile:N})]}),u("div",{className:"flex items-center w-full "+(F.compact||g?F.gap:""),style:{position:F.compact||g?"relative":"static"},children:[h("input",{ref:M,type:"file",multiple:!0,accept:He,onChange:C,className:"react-ai-agent-file-input hidden"}),F.compact&&F.showAttach&&h("div",{className:"flex-shrink-0",style:{opacity:g?0:1,width:g?0:"auto",overflow:"hidden",pointerEvents:g?"none":"auto",transition:g?"opacity 0.12s ease-out, width 0.12s ease-out":"opacity 0.3s ease-out 0.45s, width 0.3s ease-out 0.45s"},children:h("button",{type:"button",onClick:()=>M.current?.click(),className:(F.compact?"-mr-2":"")+" react-ai-agent-attach-button flex justify-center items-center cursor-pointer text-theme-primary rounded-full transition-colors hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed w-[30px] h-[30px]",children:te("attach",F.compact?20:18,"currentColor")})}),h("div",{className:F.compact||g?"flex-1":"relative pb-[50px] w-full",style:{transition:"padding 0.3s ease-out 0.15s",marginTop:g&&!F.compact?"2px":void 0},children:h("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:k,value:x,onChange:e=>w(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),A(e))},onPaste:I,onFocus:()=>{v(!0),g&&m&&m()},onBlur:()=>{v(!1)},placeholder:l,className:"text-[14px] text-theme-primary resize-none outline-none bg-transparent "+(F.compact||g?"w-full pr-0 pl-3":"w-full min-h-[40px] max-h-[150px] pr-12"),style:{overflow:"auto",height:F.compact||g?"30px":void 0,maxHeight:F.compact||g?"30px":void 0,paddingTop:F.compact||g?"7px":void 0,paddingBottom:F.compact||g?"3px":void 0,lineHeight:F.compact||g?"16px":void 0,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},rows:1})}),u("div",{className:"flex items-center "+(F.compact||g?"flex-shrink-0":"justify-between"),style:{position:F.compact||g?"static":"absolute",bottom:F.compact||g?"auto":"15px",left:F.compact||g?"auto":"20px",right:F.compact||g?"auto":"20px",width:F.compact||g?"auto":"calc(100% - 40px)"},children:[!F.compact&&h("div",{className:"react-ai-agent-input-actions-left flex items-center",style:{opacity:g||!F.showAttach?0:1,width:g||!F.showAttach?0:"auto",overflow:"hidden",pointerEvents:g||!F.showAttach?"none":"auto",transition:g?"opacity 0.12s ease-out, width 0.12s ease-out":"opacity 0.3s ease-out 0.45s, width 0.3s ease-out 0.45s"},children:u("button",{type:"button",onClick:()=>M.current?.click(),className:"react-ai-agent-attach-button flex justify-center items-center cursor-pointer text-theme-primary rounded-full transition-colors hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed",children:[te("attach",18,"currentColor"),h("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})}),u("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[h("div",{style:{opacity:g||!F.showAgent?0:1,width:g||!F.showAgent?0:"auto",overflow:"hidden",transition:g?"opacity 0.12s ease-out, width 0.12s ease-out":"opacity 0.3s ease-out 0.45s, width 0.3s ease-out 0.45s"},children:F.showAgent&&u("button",{type:"button",className:"react-ai-agent-agent-button flex justify-center p-1 px-2 mr-2 items-center cursor-pointer text-theme-primary rounded-full transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap",children:[te("brain",18,"currentColor"),h("span",{className:"react-ai-agent-agent-label text-[12px] mx-2 text-theme-quaternary font-[300] -mt-[2px]",children:"Agent"}),te("arrowDown",16,"currentColor",{transform:"rotate(180deg)"})]})}),h("button",{type:"button",onClick:e=>{s?i():A(e)},className:"react-ai-agent-send-button flex justify-center items-center cursor-pointer bg-inverse text-inverse rounded-full hover:scale-110",disabled:!x.trim()&&!s,style:{width:F.sendButtonSize+"px",height:F.sendButtonSize+"px",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, transform 0.2s ease-out"},children:te(s?"square":"send",s?15:g?18:20,"currentColor")})]})]})]})]})]})]})});Ye.displayName="ChatInput";var Je=c(Ye),Ke=c(({allowEditMessage:e=!1,children:t,placeholder:s="Ask me anything...",position:i="bottom-center",isDark:c,compact:l,coreProps:d={},inputProps:g={},onExpand:m,onClose:p,bottomBlur:f})=>{const[y,x]=r(!1),[w,b]=r(!1),[v,k]=r(!1),[S,M]=r(!1),C=n(null),I=n(null),N=n([]),[T,A]=r(c),{isStreaming:F,abort:E}=K(),R=o(()=>{N.current.forEach(e=>clearTimeout(e)),N.current=[]},[]),z=o(async e=>{C.current?.sendMessage?await C.current.sendMessage(e):setTimeout(()=>{C.current?.scrollToBottom()},100)},[]),H=o(()=>{R(),b(!1),k(!1),x(!0),M(!1),m?.(),A(!0);const e=setTimeout(()=>{M(!0)},350);N.current.push(e);const t=setTimeout(()=>{I.current?.focus()},400);N.current.push(t)},[R]),_=o(()=>{R(),b(!0),x(!1),setTimeout(()=>{p?.(),A(c)},500);const e=setTimeout(()=>{k(!0)},250);N.current.push(e);const t=setTimeout(()=>{M(!1),b(!1),k(!1)},500);N.current.push(t)},[R]);a(()=>{const e=e=>{"Escape"===e.key&&y&&_()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[y,_]),a(()=>()=>{R()},[R]);const L=y||w;return u("div",{className:"container",children:[L&&h("div",{className:"fixed inset-0 bg-black/80 z-40 transition-opacity duration-300 ease-in-out "+(v?"opacity-0":"opacity-100"),style:{backdropFilter:"blur(20px)"},onClick:_}),L&&h("div",{className:"fixed inset-0 z-45 flex items-center justify-center p-8 react-ai-agent",style:{pointerEvents:"none"},"data-theme":"dark",children:u("div",{className:"relative w-full max-w-3xl rounded-3xl floating-panel",style:{height:"100vh",pointerEvents:"auto"},children:[h("div",{className:"mt-2 absolute",children:h(Pe,{isDark:!0})}),S&&h("div",{className:"absolute inset-0 px-4 py-4 rounded-3xl",style:{opacity:w?0:1,transition:"opacity 0.25s ease-out"},children:h(Ie,{ref:C,isDark:c,allowEditMessage:e,className:"h-full w-full",...d})}),t]})}),L&&f&&u("div",{className:"shader-blur absolute bottom-0 left-0 w-full",style:{height:"150px",transform:"scaleY(-1)",zIndex:99},children:[h("div",{}),h("div",{}),h("div",{}),h("div",{}),h("div",{}),h("div",{})]}),h("div",{className:`fixed bottom-8 z-999 ${(()=>{switch(i){case"bottom-right":return"right-8";case"bottom-left":return"left-8";default:return"left-1/2 -translate-x-1/2"}})()} react-ai-agent`,"data-theme":T?"dark":"light",children:h(Je,{ref:I,collapsed:!y,onExpand:H,onSendMessage:z,isStreaming:F,abort:E,variant:y?"pill":"collapsed",placeholder:s,position:i,compact:l,...g})})]})});class Xe{constructor(e){this.tokenManager=e||new T,this.createSessionCallback=null,this.onSessionCreated=null}setCreateSessionCallback(e){this.createSessionCallback=e}setOnSessionCreated(e){this.onSessionCreated=e}async createSession(e={}){if(!this.createSessionCallback)throw Error("No session creation callback provided. Use SessionManager.setCreateSessionCallback()");try{const t=await this.createSessionCallback(e);if(!t||!t.sessionId)throw Error("Invalid session data: missing sessionId");if(!t.accessToken)throw Error("Invalid session data: missing accessToken");return tokenManager.setAuth(t),this.onSessionCreated&&this.onSessionCreated(t),t}catch(t){throw t}}getSessionId(){return tokenManager.getSessionId()}clearSession(){tokenManager.clear()}}function Ge(e,t){return JSON.stringify({event:e,data:t})}function Qe(e,t,s=!0){return Ge("ai_response",{messageId:e,content:t,isLive:s})}function Ve(e,t,s,n=null){return Ge("status_update",{messageId:e,action:t,status:s,data:n})}function Ze(e,t,s=!0){return Ge("ai_thinking",{messageId:e,content:t,isLive:s})}function et(e,t,s){return Ge("tool_call",{messageId:e,toolName:t,args:s})}function tt(){return Ge("ai_response_end",{status:"end"})}function st(e,t=""){return Ge("stream_error",{errorType:"error",error:e,message:t})}function nt(e,t){try{if(e.startsWith("data: ")){const s=e.slice(6);if("[DONE]"===s)return tt();const n=JSON.parse(s),a=n.choices[0]?.delta?.content;if(a)return Qe(t,a,!0)}}catch(s){}return null}function at(e,t=null){return Array.isArray(e)?e.map(e=>t?t(e):{messageId:e.id||e.messageId||e.uuid||Date.now()+"",type:"assistant"===e.role||"agent"===e.type||"bot"===e.sender?"agent":"user",content:e.content||e.text||e.message||e.body||"",timestamp:e.timestamp||e.created_at||e.createdAt||Date.now()}):[]}function rt(e){try{const t=e.startsWith("data:")?e.slice(5).trim():e.trim();return t?JSON.parse(t):null}catch(t){return null}}function it(e,t,s={}){const r=B(),i=n(new Map),c=!("string"!=typeof e||t||s&&0!==Object.keys(s).length),l=c?e:s.instanceId||null,d=n(t),h=n(s);a(()=>{d.current=t,h.current=s}),a(()=>{if(c)return;const s=[];if("object"!=typeof e||t){if("string"==typeof e&&t){const t=r.register(e,(...e)=>d.current(...e),{mode:h.current.mode||"dual",animated:!1!==h.current.animated,subscriptionMode:h.current.subscriptionMode||"delta",instanceId:h.current.instanceId||l});s.push(t)}}else Object.entries(e).forEach(([e,t])=>{const n=r.register(e,(...e)=>t.handler(...e),{mode:t.mode||"dual",animated:!1!==t.animated,subscriptionMode:t.subscriptionMode||"delta",instanceId:t.instanceId||l});s.push(n)});return()=>{s.forEach(e=>e())}},[e,r,l]);const u=o((e,t,s={})=>{const n={...s,instanceId:s.instanceId||l},a=r.register(e,t,n);return i.current.set(e,a),a},[r,l]),g=o(e=>{const t=i.current.get(e);t&&(t(),i.current.delete(e))},[]),m=o(()=>r.getActiveSessions(),[r]),p=o(e=>r.handlers[e],[r]),f=o(()=>Object.entries(r.handlers).map(([e,t])=>({action:e,...t})),[r]);return{register:u,unregister:g,getActiveSessions:m,getHandler:p,getAllHandlers:f}}const ot=({modes:e=[],activeMode:t,onModeChange:s,isDark:n=!1})=>e&&e.length>1?h("div",{className:"react-ai-agent-mode-toggle toggle-container flex items-center bg-theme-faint rounded-full !ml-5 flex-shrink-0 h-[35px]",style:{padding:"4px"},children:e.map(e=>h("button",{onClick:()=>s(e.id),className:`react-ai-agent-mode-button ${t===e.id?"react-ai-agent-mode-button-active":"react-ai-agent-mode-button-inactive"} relative px-3 py-1 text-[12px] font-medium rounded-full transition-all duration-200\n ${t===e.id?"bg-background text-theme-primary":"text-theme-subtle hover:text-theme-tertiary hover:bg-theme-subtle"}\n `,children:u("div",{className:"react-ai-agent-mode-button-content flex items-center gap-1.5",children:[h("span",{className:"react-ai-agent-mode-button-icon",children:e.icon}),h("span",{className:"react-ai-agent-mode-button-label",children:e.label})]})},e.id))}):null;export{k as BaseApiHandler,Ie as ChatCore,Pe as ChatHeader,Je as ChatInput,W as ChatInstanceContext,re as ChatLoadingMock,V as ChatProvider,S as DefaultApiHandler,$e as DefaultPanel,Ke as FloatingPanel,j as ForwardingManager,fe as LoadingResponse,pe as MessageItem,A as MessageManager,ot as ModeToggle,Xe as SessionManager,ge as ShimmerText,ne as StartChat,me as StatusBlock,E as StatusHandlerRegistry,N as StreamService,T as TokenManager,M as WebSocketService,at as adaptHistoryMessages,nt as adaptOpenAIStream,Qe as createAIResponse,tt as createEndEvent,st as createErrorEvent,Ge as createSSEEvent,Ve as createStatusUpdate,Ze as createThinkingEvent,et as createToolCallEvent,B as getGlobalForwardingManager,z as getGlobalStatusRegistry,rt as parseSSEChunk,$ as resetGlobalForwardingManager,U as setGlobalForwardingManager,K as useChatContext,it as useForwarding,Y as useStatusSubscription};
|