react-ai-agent 1.6.8 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import e,{createContext as t,useContext as s,useRef as n,useEffect as a,forwardRef as r,useState as i,useMemo as o,useCallback as c,useImperativeHandle as l,memo 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 w}from"framer-motion";import{useDynamicRowHeight as x,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,V=r((t,s)=>{const{children:r,initialWelcome:d={title:"Welcome to AI Chat Agent",description:"A perfect agent library for your needs, for docs visit oblien.com/docs/chat-agent"},refreshTokenCallback:h,markdownComponents:u,typingAnimation:g={mode:"chars",speed:400},statusComponents:m,forwardingHandlers:p={},authConfig:f,enableHistory:y=!0,loadHistory:w=!1,loadingComponent:x,allowThinking:b=!0,headerComponent:v,config:k,apiHandler:M,agentId:C,className:I="h-full w-full",onError:E}=t,R=n(C||"chat-"+Math.random().toString(36).substring(2,9)).current,_=void 0!==w?w:y,[L,D]=i(!0),[q,P]=i(f?.sessionId),[j,U]=i(!1),[$,Y]=i(!1),[K,Q]=i(!1),[V,Z]=i(null),[ee,te]=i(null),[se,ne]=i(!1),[ae,re]=i(!1),[ie,oe]=i(null),ce=n(d).current,[le,de]=i([]),he=n(!1),ue=n(!1),ge=n(!1),me=n(new A),pe=n(null),fe=n(!1),ye=n(!1),we=o(()=>z(),[]),xe=n(h?new T:null),be=n(M||new S({...k,...xe.current&&{tokenManager:xe.current},token:f?.accessToken,sessionId:f?.sessionId})),ve=n(new N(be.current)),ke=n(B(p)),Se=n(new F(me.current,we)),Me=n(new O(Se.current,ke.current,Object.keys(p).length>0,R)),Ce=c(()=>{const e=he.current||ue.current;Y(e),e||U(!1)},[]),Ie=c(()=>{if(fe.current&&ye.current){const t=ke.current.handlers._loading_end;if(t?.handler)try{t.handler({messageId:pe.current||null,instanceId:R,timestamp:Date.now()})}catch(e){}}},[R]);a(()=>{Me.current.onQueueComplete=()=>{ue.current=!1,ye.current=!0,Ce(),Ie()}},[Ce,Ie]);const Ne=n(u).current;a(()=>{G=Ne},[Ne]);const Te=n(x),Ae=n(m),Fe=n(v);a(()=>{var e;x!==Te.current&&(Te.current=x),m!==Ae.current&&(Ae.current=m,e=m||{},X={...e}),v!==Fe.current&&(Fe.current=v),h&&xe.current&&xe.current.setRefreshCallback(h)},[x,m,v,h]);const Ee=n(!1),Re=n(q),ze=n(null);H.current=g;const He=n(new Set);a(()=>{const e=me.current.subscribe(e=>{de(e)});return()=>{e()}},[]),a(()=>{Re.current=q},[q]);const _e=n(!1);a(()=>{(async()=>{if(f&&f.sessionId&&xe.current)try{await xe.current.setAuth(f)}catch(V){let t="Authentication failed. Please refresh the page.";V?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":V?.message&&(t=V.message),Z({type:"auth_error",message:t,error:V}),D(!1)}else _||D(!1)})()},[!1,f,_]);const Le=c(e=>{Z(e.error)},[]),De=c(async()=>{try{if(He.current.has(q))return void D(!1);He.current.add(q),D(!0);const e=await be.current.getHistory();if(e.error)return Le(e),void D(!1);e.history&&e.history.length>0&&me.current.insertMessages(e.history,"end"),re(!!e.has_more),D(!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),Z({type:"history_error",message:t,error:e}),D(!1)}},[q,Le]);a(()=>{(async()=>{_?q&&!_e.current?(_e.current=!0,await De()):q||_e.current||(_e.current=!0,await De()):D(!1)})()},[q,De,_]);const qe=c(async()=>{ge.current=!0,he.current=!1,ue.current=!1,Y(!1),U(!1),Q(!1),fe.current=!1,ye.current=!1;const e=Se.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 Me.current.finishThinking({messageId:t})}));for(const n of s)Se.current.messageManager.updateMessage(n.messageId,{isFinished:!0,statusType:"finished"});Me.current.clear(),pe.current=null,be.current.abort(),ve.current.abort(),Re.current&&be.current.abortRequest&&await be.current.abortRequest(Re.current),setTimeout(()=>{ge.current=!1},100)},[]),Oe=c(e=>{if(ge.current)return;const t={...e,id:e?.id||Math.random().toString(36).substring(2,9),timestamp:Date.now(),instanceId:R};te(t),E&&E(t);const s=ke.current.handlers._error;if(s?.handler)try{s.handler(t)}catch(n){}},[E,R]),Pe=c(()=>{te(null)},[]),je=c(()=>{he.current=!1;const e=pe.current;if(e){Me.current.endResponse(),pe.current=null,fe.current=!0;const s=ke.current.handlers._response_end;if(s?.handler)try{s.handler({messageId:e,instanceId:R,timestamp:Date.now()})}catch(t){}}else fe.current=!0;Ce(),Ie()},[Ce,R,Ie]),Be=c(()=>{Ee.current=!1,he.current=!1,Ce()},[Ce]),Ue=c(e=>{const t=e?.data?.messageId||e?.messageId;if(t&&(pe.current=t),!K){Q(!0),fe.current=!1,ye.current=!1;const e=ke.current.handlers._response_start;if(e?.handler)try{e.handler({messageId:t,instanceId:R,timestamp:Date.now()})}catch(s){}}ue.current=!0,Me.current.addToQueue(e),Ce()},[K,Ce,R]);a(()=>(ve.current.on("stream_error",Oe),ve.current.on("response",Ue),ve.current.on("response_end",je),ve.current.on("disconnect",Be),()=>{ve.current.off("stream_error",Oe),ve.current.off("response",Ue),ve.current.off("response_end",je),ve.current.off("disconnect",Be)}),[Oe,Ue,je,Be]);const $e=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{ze.current&&ze.current?.messageId===a||Se.current.handleUserMessage({messageId:a,text:t,attachedFiles:s}),ze.current={messageId:a,message:t,attachedFiles:s,uploadId:n},U(!0),Q(!1),fe.current=!1,ye.current=!1,ge.current=!1,he.current=!0,Ce();const e=ke.current.handlers._stream_feedback,r=e?.handler,i="raw"===e?.mode,o=await ve.current.startStream({message:t,attachedFiles:s,uploadId:n,sessionId:Re.current,context:null,allowThinking:b},r,i);o.status||(he.current=!1,Ce(),Oe({errorType:"connection_error",error:o.error||"Error occurred while connecting to server",message:o.message||"Failed to send message"}))}catch(r){he.current=!1,Ce(),Oe({errorType:"send_error",error:r.message||"Unknown error",message:"Failed to send message"})}finally{U(!1)}},We=c(async()=>{ze.current&&await $e(ze.current)},[]);c(e=>{void 0!==e.sessionId&&P(e.sessionId),e.accessToken&&be.current&&"function"==typeof be.current.updateConfig&&be.current.updateConfig({token:e.accessToken})},[]);const Ye=o(()=>({addMessage:e=>me.current.addMessage(e),updateMessage:(e,t)=>me.current.updateMessage(e,t),removeMessage:e=>me.current.removeMessage(e),getMessage:e=>me.current.getMessage(e),clear:()=>me.current.clear()}),[]),Je=o(()=>({register:(e,t)=>we.register(e,t,{instanceId:R}),registerGlobal:e=>we.registerGlobal(e,{instanceId:R})}),[R,we]),Ke={sendMsg:$e,messages:le,messageManager:Ye,isLoading:j,isStreaming:$,isResponseStarted:K,isInitialLoading:L,isLoadingMore:se,error:V,streamError:ee,clearStreamError:Pe,loadHistory:De,getHistory:De,loadMoreMessages:async()=>{if(!se&&ae){ne(!0);try{const e=me.current.count,t=await be.current.getHistory({offset:e,limit:20});if(t.error)return Le(t),void ne(!1);t.history&&t.history.length>0?(me.current.insertMessages(t.history,"start"),re(t.has_more)):re(!1)}catch(e){Z({type:"load_more_error",message:"Failed to load more messages",error:e})}finally{ne(!1)}}},hasMoreMessages:ae,enableHistory:y,shouldAutoLoadHistory:_,retryLastMessage:We,abort:qe,sessionId:q,setSessionId:P,instanceId:R,currentSelectedFile:ie,setCurrentSelectedFile:oe,welcome:ce,statusRegistry:Je,markdownComponents:Ne,statusComponents:Ae.current,loadingComponent:Te.current,headerComponent:Fe.current,typingAnimation:g};return l(s,()=>Ke,[]),e.createElement("div",{className:"react-ai-agent-root "+I},e.createElement(J.Provider,{value:Ke},e.createElement(W.Provider,{value:R},r)))}),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,r]=i(0),[o,c]=i(!1),l=n(0);return a(()=>{l.current=300,requestAnimationFrame(()=>{r(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=d(({message:e})=>{const t=Q(),[s,n]=i("");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=d(({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=d(({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=d(({message:e,isInCurrentSession:t})=>{const s=n(null),r=n(e.finalized),l=n(null),[d,g]=i(!e.finalized),[m,p]=i(!1),[w,x]=i(""),b=e.isLive||!e.finalized,v=e.finalized||!t,k=e.duration||0,S=o(()=>e.text||"",[e.text]);a(()=>{requestAnimationFrame(()=>{p(!0)})},[]),a(()=>{if(!b||!d)return void x(S);const e=w.length,t=S.length;if(e>=t)return;const s=Math.min(5,t-e),n=setTimeout(()=>{x(S.slice(0,e+s))},20);return()=>clearTimeout(n)},[S,w,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)}},[w,d,b]),a(()=>{if(v&&!r.current&&d){const e=setTimeout(()=>{g(!1)},800);return()=>clearTimeout(e)}},[v,d]);const M=c(()=>{g(e=>!e)},[]),C=o(()=>({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:w&&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:w})})})})]})},(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:i=!0,onClick:c,isDark:l=!1,unmountOnExit:d,action:g,data:m,className:p,style:f,metadata:y})=>{const w=g||e?.action,x=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!==i?i:void 0===e?.isFlat||e.isFlat,I=void 0!==d?d:e?.unmountOnExit,N=c,T=k?.icon||a,A=o(()=>S?v?`Processing ${S}...`:"Finished "+S:w?(({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:x,action:w,isFinished:b}):"Processing...",[S,w,b,x]);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=d(({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(w.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:i})=>o(()=>{const o=[...e];return a&&o.push({type:"viewport-spacer",messageId:"viewport-spacer-"+r,onComplete:i,isResponseStarted:s}),n&&t&&!s&&o.push({type:"loading-indicator",messageId:"loading-indicator"}),o},[e,n,t,s,a,r,i]),we=e=>o(()=>{for(let t=e.length-1;t>=0;t--)if("user"===e[t].sender)return t;return-1},[e]),xe=({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:o,isLoading:l,isResponseStarted:d,showLoadingIndicator:u,showSpacer:g,spacerKey:p,onSpacerComplete:f})=>{const y=n(!0),w=ye({messages:e,isLoading:l,isResponseStarted:d,showLoadingIndicator:u,showSpacer:g,spacerKey:p,onSpacerComplete:f}),x=we(e),b=c(e=>{y.current=e,o&&(o.current=e)},[o]);c(()=>"smooth",[]);const v=c(e=>xe({item:w[e],index:e,lastUserIndex:x,removeMessage:t,allowEditMessage:s,isLastItem:e===w.length-1,animationConfig:a}),[w,x,t,s,a]);return h(m,{style:{height:r,width:i},data:w,totalCount:w.length,itemContent:v,initialTopMostItemIndex:w.length-1,atBottomStateChange:b,alignToBottom:!0})},ve=({dynamicHeight:e,messages:t,removeMessage:s,allowEditMessage:a,animationConfig:r,height:i,width:l,overscan:d,listRef:u,isLoading:g,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:y,onSpacerComplete:w})=>{const x=ye({messages:t,isLoading:g,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:y,onSpacerComplete:w}),v=we(t),k=n(new Map),S=o(()=>({itemsData:x,removeMessage:s,allowEditMessage:a,animationConfig:r,dynamicHeight:e,lastUserIndex:v,heightCacheRef:k}),[x,s,a,r,e,v]),M=c(({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:xe({item:a[e],index:e,lastUserIndex:l,removeMessage:r,isLastItem:e===a.length-1,allowEditMessage:i,animationConfig:o})})},[]);return h("div",{style:{height:i,width:l,overflow:"hidden"},children:h(b,{listRef:u,rowComponent:M,rowCount:x.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:o,shouldAutoScrollRef:l})=>{const d=n(null),u=[{type:"empty-message",messageId:"empty-message"},...e],g=we(e),m=c(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=c(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=c((e=!0)=>{const t=d.current;t&&t.scrollTo({top:t.scrollHeight,behavior:e?"smooth":"auto"})},[]);ke({itemsData:u,scrollToBottom:y,shouldAutoScrollRef:l,isStreaming:o});const w=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:w.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:xe({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}),w=we(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:xe({item:e,index:a,lastUserIndex:w,removeMessage:t,allowEditMessage:s,animationConfig:n})},e.uniqueKey||e.messageId||a):null)})},Ce=r(({virtualization:e="tanstack",estimateSize:t=150,overscan:s=10,isDark:r=!1,className:o="",containerStyle:d={},useGradientMask:g=!0,gradientMaskStyle:m="linear-gradient(to bottom, transparent 6.5%, black 18%)",allowEditMessage:p=!1,showWelcome:f=!0,showLoadMore:y=!0,showLoadingIndicator:w=!0,keepUserMessageInView:b=!0,welcomeComponent:v,loadingComponent:k,initialAnimation:S=null,height:M="100%",width:C="100%"},I)=>{const[N,T]=i(!1),[A,F]=i(!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]=i(!1),[s,n]=i(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),o=c(()=>{const e=s.current;e&&(e.scrollTop=e.scrollHeight)},[]),l=c(()=>{const e=s.current;return!!e&&50>e.scrollHeight-e.scrollTop-e.clientHeight},[]),d=c(()=>{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=c((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&&o()},100);return()=>clearInterval(e)},[t,o]),{scrollContainerRef:s,shouldAutoScrollRef:r,scrollToBottom:o,isAtBottom:l}})({onGradientChange:T,isStreaming:"none"===e&&L}),oe="react-window"===e?(({estimateSize:e})=>x({defaultRowHeight:e}))({estimateSize:t}):null,ce=c(()=>{"virtuoso"!==e&&"tanstack"!==e&&("react-window"===e&&E.current?.scrollToBottomCustom?E.current.scrollToBottomCustom():"none"===e&&ne())},[e,ne]),le=c(()=>{b&&setTimeout(()=>{V()},200)},[b,V]),{removeMessage:de,handleSendMessage:he}=(({messageManager:e,sendMsg:t,shouldAutoScrollRef:s,onUserMessageSent:n})=>({removeMessage:c(t=>{e?.removeMessage&&e.removeMessage(t)},[e]),handleSendMessage:c(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]),l(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 "+o,"data-theme":r?"dark":"light",style:{WebkitMaskImage:m,...d},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:w,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=d(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]=i(!1),{sessionMetrics:s,usedTokens:n,contextLimit:a}=K(),r=(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:[r,"%"]}),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) ${r}%, 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]=i(!1),a="object"==typeof e&&e.id,r=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:r,className:"react-ai-agent-file-item-preview w-3 h-4 object-cover rounded",style:{marginRight:0,width:"12px",height:"16px"}}):h(FileIcon,{fileName:r,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:r})]},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]=i(0),s=n(),r=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(),r.current=e;const n=a=>{const i=a-o.current;o.current=a,r.current+=i/1e3*360,360>r.current||(r.current-=360);const c=r.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]=i([]),s=n(null),a=c(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("")},[]),r=c(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]),o=c(e=>{const t=Array.from(e.target.files||[]);t.length>0&&r(t),e.target.value=""},[r]),l=c(e=>{const t=Array.from(e.clipboardData?.items||[]).filter(e=>"file"===e.kind).map(e=>e.getAsFile()).filter(Boolean);t.length>0&&(e.preventDefault(),r(t))},[r]),d=c(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=c(()=>{t(e=>(e.forEach(e=>{e.preview&&URL.revokeObjectURL(e.preview)}),[]))},[]);return{attachedFiles:e,fileInputRef:s,onFileSelect:o,onPaste:l,removeFile:d,clearFiles:h}}const Le=()=>{const{streamError:e,clearStreamError:t,retryLastMessage:s,sendRequestCallback:n,triggerLoadingStates:a}=K(),[r]=i(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:r&&r.length>0&&r.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:r=!1})=>{const[o,c]=i(!1),l=n(null),d=e.find(e=>e.id===t)||e[0],[g,m]=i(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:()=>!r&&c(!o),disabled:r,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=>{r||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=r(({onSendMessage:e,isStreaming:t,abort:s,mode:r="advanced",todos:o=[],agents:c=[],selectedAgentId:d,onAgentChange:m},p)=>{const[f,y]=i(""),w=n(null),{attachedFiles:x,fileInputRef:b,onFileSelect:v,onPaste:k,removeFile:S,clearFiles:M}=_e();a(()=>{w.current&&(w.current.style.height="auto",w.current.style.height=Math.min(w.current.scrollHeight,150)+"px")},[f]),l(p,()=>({focus:()=>{w.current?.focus()}}),[]);const C=t=>{t.preventDefault(),(f.trim()||x.length>0)&&(e({message:f,attachedFiles:x}),y(""),M(),w.current&&(w.current.style.height="auto"))},I="advanced"===r,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"===r?"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"===r?"min-h-[120px]":"min-h-[100px]"),style:{zIndex:2},children:[I&&u(g,{children:[h(Ne,{todos:o}),h(Le,{}),h(Fe,{attachedFiles:x,removeFile:S})]}),h("div",{className:`react-ai-agent-input-textarea-wrapper relative pb-[${"advanced"===r?"50px":"0px"}]`,children:h("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:w,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"===r&&x.length>0?u("div",{className:"flex items-center gap-2",children:[h(Re,{files:x,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:d,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=d(qe),Pe=d(({isDark:e=!1,onCreateSession:t,onClose:s,showCloseButton:n=!1})=>{const[a,r]=i(!1),[o,c]=i(!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(r(!0),t)try{await t({replace:e})}catch(s){}finally{r(!1)}else setTimeout(()=>{r(!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=d(({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=d(({onClick:t,isDark:s=!1,isOpen:r=!1,onPositionChange:o,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),[w,x]=i({width:64,height:64}),b="number"==typeof d?d:d?.x??20,v="number"==typeof d?d:d?.y??20,k=c(()=>"undefined"==typeof window?{minX:b,minY:v,maxX:1024-w.width-b,maxY:768-w.height-v,width:1024,height:768}:{minX:b,minY:v,maxX:window.innerWidth-w.width-b,maxY:window.innerHeight-w.height-v,width:window.innerWidth,height:window.innerHeight},[w,b,v]),S=c((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=c(e=>{const t=k();return!(t.minX>e.x||t.minY>e.y||e.x>t.maxX||e.y>t.maxY)},[k]),C=c(()=>{const e=k(),{width:t,minX:s,minY:n,maxX:a,maxY:r}=e;return[{x:s,y:n,name:"top-left"},{x:(t-w.width)/2,y:n,name:"top-center"},{x:a,y:n,name:"top-right"},{x:s,y:r,name:"bottom-left"},{x:(t-w.width)/2,y:r,name:"bottom-center"},{x:a,y:r,name:"bottom-right"}]},[w,k]),I=c(()=>{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]=i(()=>"undefined"==typeof window?{x:0,y:0,name:"bottom-right"}:I()),[A,F]=i(!1),[E,R]=i(!1),[z,H]=i({x:0,y:0}),[_,L]=i({x:0,y:0}),[D,q]=i(!1);a(()=>{if("undefined"!=typeof window&&!D){q(!0);const e=I();e&&void 0!==e.x&&void 0!==e.y&&T(e)}},[D,I]);const O=c((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]),P=c(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]),j=c(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&&o&&o(t,!0,w)},[A,_,z,S,o,l,w]),B=c(e=>{if("undefined"!=typeof window)try{localStorage.setItem(f,JSON.stringify(e))}catch(t){}},[]),U=c(e=>{if(A)if(F(!1),p?.(!1),E){const e=O(N.x,N.y);T(e),setTimeout(()=>{B(e)},0),o?.(e,!1,w)}else t?.()},[A,E,N,O,t,B,o,p]);return a(()=>{if(A)return document.addEventListener("mousemove",j),document.addEventListener("mouseup",U),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",U)}},[A,j,U]),a(()=>{if("undefined"==typeof window)return;const e=()=>{if(M(N)){const e=O(N.x,N.y);T(e),setTimeout(()=>{B(e)},0),o?.(e,!1,w)}else{const e=S(N.x,N.y),t=O(e.x,e.y);T(t),setTimeout(()=>{B(t)},0),o?.(t,!1,w)}};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[N,O,B,M,S,o]),a(()=>{if("undefined"==typeof window||!y.current||!D)return;const e=()=>{if(y.current){const e=y.current.getBoundingClientRect(),t={width:e.width,height:e.height};x(e=>e.width===t.width&&e.height===t.height?e:t)}},t=setTimeout(()=>{e()},0),s=new ResizeObserver(()=>{e()});return s.observe(y.current),()=>{clearTimeout(t),s.disconnect()}},[D]),a(()=>{if("undefined"==typeof window||!N)return;const e=S(N.x,N.y);e.x===N.x&&e.y===N.y||(T(e),setTimeout(()=>{B(e)},0),o?.(e,!1,w))},[w,S,o,N,B]),a(()=>{N&&o&&requestAnimationFrame(()=>{o(N,!1,w)})},[]),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:P,children:e.isValidElement(u)?e.cloneElement(u,{isOpen:r,isDragging:A,isDark:s,onOpen:g,onClose:m,onDrag:p}):u?h(u,{isOpen:r,isDragging:A,isDark:s,onOpen:g,onClose:m,onDrag:p}):h(Be,{isOpen:r,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=d(({isDark:e=!1,allowEditMessage:t=!1,children:s,onCreateSession:r,className:l="h-full w-full",coreProps:d={},inputProps:m={},mode:p="popup",livePositionUpdate:f=!0,popupOptions:y={},popupContainerClassName:w="",popupContainerStyle:x={},floatingButtonEdgeOffset:b=25,ContentComponent:v,onOpen:k,onClose:S,onDrag:M})=>{const C=o(()=>({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]=i("default"===p),[F,E]=i(!1),[R,z]=i(null),[H,_]=i({width:64,height:64}),[L,D]=i(!1),[q,O]=i("right"),[P,j]=i("bottom"),{sendMsg:B,isStreaming:U,abort:$}=K(),W=c(async e=>{I.current?.sendMessage?await I.current.sendMessage(e):(await B(e),setTimeout(()=>{I.current?.scrollToBottom()},100))},[B]),Y=c(()=>{N.current&&clearTimeout(N.current),E(!0),A(!0),k?.(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{E(!1)})})},[k]),J=c(()=>{N.current&&clearTimeout(N.current),A(!1),S?.(),E(!0),N.current=setTimeout(()=>{E(!1),N.current=null},450)},[S]),X=c(()=>{T?J():Y()},[T,Y,J]),G=c((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=o(()=>{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=o(()=>{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=o(()=>({coreRef:I,isDark:e,allowEditMessage:t,onCreateSession:r,handleSendMessage:W,isStreaming:U,abort:$,coreProps:d,inputProps:m,children:s}),[e,t,r,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 "+w).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",...x},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=r(({onSendMessage:e,miniMode:t=!1,isStreaming:s,abort:r,todos:o,variant:c="default",placeholder:d="Type a message...",collapsed:g=!1,onExpand:m,position:p="bottom-center",compact:f},y)=>{const[w,x]=i(""),[b,v]=i(!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")},[w,g]),l(y,()=>({focus:()=>{k.current?.focus()}}),[]);const A=t=>{t.preventDefault(),(w.trim()||S.length>0)&&(e({message:w,attachedFiles:S}),x(""),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:w,onChange:e=>x(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:d,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?r():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:!w.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=d(Ye),Ke=d(({allowEditMessage:e=!1,children:t,placeholder:s="Ask me anything...",position:r="bottom-center",isDark:o,compact:l,coreProps:d={},inputProps:g={},onExpand:m,onClose:p,bottomBlur:f})=>{const[y,w]=i(!1),[x,b]=i(!1),[v,k]=i(!1),[S,M]=i(!1),C=n(null),I=n(null),N=n([]),[T,A]=i(o),{isStreaming:F,abort:E}=K(),R=c(()=>{N.current.forEach(e=>clearTimeout(e)),N.current=[]},[]),z=c(async e=>{C.current?.sendMessage?await C.current.sendMessage(e):setTimeout(()=>{C.current?.scrollToBottom()},100)},[]),H=c(()=>{R(),b(!1),k(!1),w(!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]),_=c(()=>{R(),b(!0),w(!1),setTimeout(()=>{p?.(),A(o)},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||x;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:x?0:1,transition:"opacity 0.25s ease-out"},children:h(Ie,{ref:C,isDark:o,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(r){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:r,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),o=!("string"!=typeof e||t||s&&0!==Object.keys(s).length),l=o?e:s.instanceId||null,d=n(t),h=n(s);a(()=>{d.current=t,h.current=s}),a(()=>{if(o)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=c((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=c(e=>{const t=i.current.get(e);t&&(t(),i.current.delete(e))},[]),m=c(()=>r.getActiveSessions(),[r]),p=c(e=>r.handlers[e],[r]),f=c(()=>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};
1
+ import e,{createContext as t,useContext as s,useRef as n,useEffect as a,forwardRef as r,useState as i,useMemo as o,useCallback as c,useImperativeHandle as l,memo 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 w}from"framer-motion";import{useDynamicRowHeight as x,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 I=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 M{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 C{constructor(){this.jsonStreamParser=new M}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 C,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&&I&&I.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 H(){return R}const z={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=z.current.mode,this.speed=z.current.speed,this.batchSize=z.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 O{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 q extends O{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=H(),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),X=new Map,G=(e,t,s)=>{e&&(X.has(e)||X.set(e,{}),X.get(e)[t]=s)},Q=(e,t)=>{if(!e||!t)return null;const s=X.get(e);if(!s)return null;const n=t.split(".");let a=s;for(const r of n){if(!a||"object"!=typeof a)return null;a=a[r]}return a||null},V=r((t,s)=>{const[r,d]=i(t.authConfig),[h,u]=i(void 0!==t.loadHistory?t.loadHistory:t.enableHistory),[g,m]=i(t.loadingComponent),[p,f]=i(t.welcomeComponent),[y,w]=i(t.allowThinking??!0),[x,b]=i(t.headerComponent),[v,k]=i(t.config),[I,M]=i(t.className??"h-full w-full"),[C,E]=i(t.onError),[R,_]=i(t.typingAnimation??{mode:"chars",speed:400}),[L,D]=i(t.forwardingHandlers??{}),[O,P]=i(t.agentId),[j,U]=i(t.refreshTokenCallback),[$]=i(t.enableHistory??!0),[Y,K]=i(t.apiHandler),X=n(O||"chat-"+Math.random().toString(36).substring(2,9)).current,[Q,V]=i(!1),[Z,ee]=i(r?.sessionId),[te,se]=i(!1),[ne,ae]=i(!1),[re,ie]=i(!1),[oe,ce]=i(null),[le,de]=i(null),[he,ue]=i(!1),[ge,me]=i(!1),[pe,fe]=i(null),[ye,we]=i(t.initialWelcome||{title:"Welcome to AI Chat Agent",description:"A perfect agent library for your needs, for docs visit oblien.com/docs/chat-agent"}),[xe,be]=i([]),ve=n(!1),ke=n(!1),Se=n(!1),Ie=n(new A),Me=n(null),Ce=n(!1),Ne=n(!1),Te=o(()=>H(),[]),Ae=n(j?new T:null),Fe=n(Y||new S({...v,...Ae.current&&{tokenManager:Ae.current},token:r?.accessToken,sessionId:r?.sessionId})),Ee=n(new N(Fe.current)),Re=n(B(L)),He=n(new F(Ie.current,Te)),ze=n(new q(He.current,Re.current,Object.keys(L).length>0,X)),_e=c(()=>{const e=ve.current||ke.current;ae(e),e||se(!1)},[]),Le=c(()=>{if(Ce.current&&Ne.current){const t=Re.current.handlers._loading_end;if(t?.handler)try{t.handler({messageId:Me.current||null,instanceId:X,timestamp:Date.now()})}catch(e){}}},[X]);a(()=>{ze.current.onQueueComplete=()=>{ke.current=!1,Ne.current=!0,_e(),Le()}},[_e,Le]),a(()=>{t.markdownComponents&&G(X,"markdown",t.markdownComponents),t.statusComponents&&Object.keys(t.statusComponents).forEach(e=>{G(X,"status."+e,t.statusComponents[e])}),g&&G(X,"loading",g),x&&G(X,"header",x),p&&G(X,"welcome",p),G(X,"welcomeData",ye)},[X,t.markdownComponents,t.statusComponents,p,ye,g,x]),a(()=>{j&&Ae.current&&Ae.current.setRefreshCallback(j)},[j]);const De=n(!1),Oe=n(Z),qe=n(null);z.current=R;const Pe=n(new Set);a(()=>{const e=Ie.current.subscribe(e=>{be(e)});return()=>{e()}},[]),a(()=>{Oe.current=Z},[Z]),n(!1),a(()=>{(async()=>{if(r&&r.sessionId&&Ae.current)try{await Ae.current.setAuth(r)}catch(oe){let t="Authentication failed. Please refresh the page.";oe?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":oe?.message&&(t=oe.message),ce({type:"auth_error",message:t,error:oe}),V(!1)}})()},[!1,r]);const je=c(e=>{ce(e.error)},[]),Be=c(async()=>{try{if(Pe.current.has(Z))return void V(!1);Pe.current.add(Z),V(!0);const e=await Fe.current.getHistory();if(e.error)return je(e),void V(!1);e.history&&e.history.length>0&&Ie.current.insertMessages(e.history,"end"),me(!!e.has_more),V(!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),ce({type:"history_error",message:t,error:e}),V(!1)}},[Z,je]),Ue=c(async()=>{Se.current=!0,ve.current=!1,ke.current=!1,ae(!1),se(!1),ie(!1),Ce.current=!1,Ne.current=!1;const e=He.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 ze.current.finishThinking({messageId:t})}));for(const n of s)He.current.messageManager.updateMessage(n.messageId,{isFinished:!0,statusType:"finished"});ze.current.clear(),Me.current=null,Fe.current.abort(),Ee.current.abort(),Oe.current&&Fe.current.abortRequest&&await Fe.current.abortRequest(Oe.current),setTimeout(()=>{Se.current=!1},100)},[]),$e=c(e=>{if(Se.current)return;const t={...e,id:e?.id||Math.random().toString(36).substring(2,9),timestamp:Date.now(),instanceId:X};de(t),C&&C(t);const s=Re.current.handlers._error;if(s?.handler)try{s.handler(t)}catch(n){}},[C,X]),We=c(()=>{de(null)},[]),Ye=c(()=>{ve.current=!1;const e=Me.current;if(e){ze.current.endResponse(),Me.current=null,Ce.current=!0;const s=Re.current.handlers._response_end;if(s?.handler)try{s.handler({messageId:e,instanceId:X,timestamp:Date.now()})}catch(t){}}else Ce.current=!0;_e(),Le()},[_e,X,Le]),Je=c(()=>{De.current=!1,ve.current=!1,_e()},[_e]),Ke=c(e=>{const t=e?.data?.messageId||e?.messageId;if(t&&(Me.current=t),!re){ie(!0),Ce.current=!1,Ne.current=!1;const e=Re.current.handlers._response_start;if(e?.handler)try{e.handler({messageId:t,instanceId:X,timestamp:Date.now()})}catch(s){}}ke.current=!0,ze.current.addToQueue(e),_e()},[re,_e,X]);a(()=>(Ee.current.on("stream_error",$e),Ee.current.on("response",Ke),Ee.current.on("response_end",Ye),Ee.current.on("disconnect",Je),()=>{Ee.current.off("stream_error",$e),Ee.current.off("response",Ke),Ee.current.off("response_end",Ye),Ee.current.off("disconnect",Je)}),[$e,Ke,Ye,Je]);const Xe=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{qe.current&&qe.current?.messageId===a||He.current.handleUserMessage({messageId:a,text:t,attachedFiles:s}),qe.current={messageId:a,message:t,attachedFiles:s,uploadId:n},se(!0),ie(!1),Ce.current=!1,Ne.current=!1,Se.current=!1,ve.current=!0,_e();const e=Re.current.handlers._stream_feedback,r=e?.handler,i="raw"===e?.mode,o=await Ee.current.startStream({message:t,attachedFiles:s,uploadId:n,sessionId:Oe.current,context:null,allowThinking:y},r,i);o.status||(ve.current=!1,_e(),$e({errorType:"connection_error",error:o.error||"Error occurred while connecting to server",message:o.message||"Failed to send message"}))}catch(r){ve.current=!1,_e(),$e({errorType:"send_error",error:r.message||"Unknown error",message:"Failed to send message"})}finally{se(!1)}},Ge=c(async()=>{qe.current&&await Xe(qe.current)},[]),Qe=c(e=>{m(e),e&&G(X,"loading",e)},[X]),Ve=c(e=>{b(e),e&&G(X,"header",e)},[X]),Ze=c(e=>{f(e),e&&G(X,"welcome",e)},[X]),et=c(e=>{we(e),e&&G(X,"welcomeData",e)},[X]),tt=o(()=>({addMessage:e=>Ie.current.addMessage(e),updateMessage:(e,t)=>Ie.current.updateMessage(e,t),removeMessage:e=>Ie.current.removeMessage(e),getMessage:e=>Ie.current.getMessage(e),clear:()=>Ie.current.clear()}),[]),st=o(()=>({register:(e,t)=>Te.register(e,t,{instanceId:X}),registerGlobal:e=>Te.registerGlobal(e,{instanceId:X})}),[X,Te]),nt={sendMsg:Xe,messages:xe,messageManager:tt,isLoading:te,isStreaming:ne,isResponseStarted:re,isInitialLoading:Q,isLoadingMore:he,error:oe,streamError:le,clearStreamError:We,getHistory:Be,loadMoreMessages:async()=>{if(!he&&ge){ue(!0);try{const e=Ie.current.count,t=await Fe.current.getHistory({offset:e,limit:20});if(t.error)return je(t),void ue(!1);t.history&&t.history.length>0?(Ie.current.insertMessages(t.history,"start"),me(t.has_more)):me(!1)}catch(e){ce({type:"load_more_error",message:"Failed to load more messages",error:e})}finally{ue(!1)}}},hasMoreMessages:ge,enableHistory:$,retryLastMessage:Ge,abort:Ue,sessionId:Z,setSessionId:ee,instanceId:X,currentSelectedFile:pe,setCurrentSelectedFile:fe,statusRegistry:st,typingAnimation:R,setAuthConfig:e=>{d(e),void 0!==e.sessionId&&ee(e.sessionId),e.accessToken&&Fe.current&&"function"==typeof Fe.current.updateConfig&&Fe.current.updateConfig({token:e.accessToken})},setLoadHistory:u,setLoadingComponent:Qe,setAllowThinking:w,setHeaderComponent:Ve,setWelcomeComponent:Ze,setWelcome:et,setConfig:k,setClassName:M,setOnError:E,setMarkdownComponents:e=>G(X,"markdown",e),registerComponent:G,setStatusComponents:e=>{Object.keys(e).forEach(t=>{G(X,"status."+t,e[t])})},setTypingAnimation:_,setForwardingHandlers:D,authConfig:r,loadHistory:h,allowThinking:y,config:v,className:I,onError:C,forwardingHandlers:L,setAgentId:P,setRefreshTokenCallback:U,setApiHandler:K};return l(s,()=>nt,[]),e.createElement("div",{className:"react-ai-agent-root "+I},e.createElement(J.Provider,{value:nt},e.createElement(W.Provider,{value:X},t.children)))}),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,instanceId:t})=>{const s=Q(t,"welcomeData"),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 h("div",{className:"react-ai-agent-start-chat flex flex-col items-center justify-center h-full",children:"object"!=typeof s||s?.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":s?.title}),h("p",{className:"react-ai-agent-start-chat-description text-theme-muted mb-6 max-w-md text-base leading-relaxed",children:e?n:s?.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("_"," ")})]}):s})},ae=({error:e,isPanelOpen:t,instanceId:s})=>{const n=Q(s,"welcome");return n?h(n,{error:e}):h(ne,{error:e,miniMode:t,instanceId: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,r]=i(0),[o,c]=i(!1),l=n(0);return a(()=>{l.current=300,requestAnimationFrame(()=>{r(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=d(({message:e,instanceId:t})=>{const s=Q(t,"markdown"),[n,r]=i("");return a(()=>{const t=D(e.messageId);if(t)return t.subscribe(e=>{r(e)});r(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:s,children:n})})})}),le=d(({text:e,instanceId:t})=>{const s=Q(t,"markdown"),n=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:n?h(p,{parseIncompleteMarkdown:!0,mode:"static",components:s,children:n}):h("span",{style:{opacity:.5},children:"..."})})})}),de=d(({message:e,animationConfig:t,instanceId:s})=>e.isLive&&!e.finalized?h(ce,{message:e,animationConfig:t,instanceId:s}):h(le,{text:e.text,instanceId:s}));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=d(({message:e,isInCurrentSession:t})=>{const s=n(null),r=n(e.finalized),l=n(null),[d,g]=i(!e.finalized),[m,p]=i(!1),[w,x]=i(""),b=e.isLive||!e.finalized,v=e.finalized||!t,k=e.duration||0,S=o(()=>e.text||"",[e.text]);a(()=>{requestAnimationFrame(()=>{p(!0)})},[]),a(()=>{if(!b||!d)return void x(S);const e=w.length,t=S.length;if(e>=t)return;const s=Math.min(5,t-e),n=setTimeout(()=>{x(S.slice(0,e+s))},20);return()=>clearTimeout(n)},[S,w,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)}},[w,d,b]),a(()=>{if(v&&!r.current&&d){const e=setTimeout(()=>{g(!1)},800);return()=>clearTimeout(e)}},[v,d]);const I=c(()=>{g(e=>!e)},[]),M=o(()=>({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:I,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:w&&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:M,children:w})})})})]})},(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:i=!0,onClick:c,isDark:l=!1,unmountOnExit:d,action:g,data:m,className:p,style:f,metadata:y})=>{const w=g||e?.action,x=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,I=r||e?.iconComponent,M=void 0!==i?i:void 0===e?.isFlat||e.isFlat,C=void 0!==d?d:e?.unmountOnExit,N=c,T=k?.icon||a,A=o(()=>S?v?`Processing ${S}...`:"Finished "+S:w?(({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:x,action:w,isFinished:b}):"Processing...",[S,w,b,x]);return h("div",M?{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:[C?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`}):I?I():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] "+(I?"!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`}):I?I():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=d(({item:e,removeMessage:t,allowEditMessage:s,animationConfig:n,isInCurrentSession:a,instanceId:r})=>{if("user"===e.sender)return h("div",{className:"react-ai-agent-message-item react-ai-agent-message-user",children:h(oe,{message:e,allowEdit:s})});if("status"===e.type&&e.action){const t=Q(r,"status."+e.action);return h("div",{className:"react-ai-agent-message-item react-ai-agent-message-status",children:h(t||me,{message:e})})}return h("div","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,instanceId:r})})});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(w.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:i})=>o(()=>{const o=[...e];return a&&o.push({type:"viewport-spacer",messageId:"viewport-spacer-"+r,onComplete:i,isResponseStarted:s}),n&&t&&!s&&o.push({type:"loading-indicator",messageId:"loading-indicator"}),o},[e,n,t,s,a,r,i]),we=e=>o(()=>{for(let t=e.length-1;t>=0;t--)if("user"===e[t].sender)return t;return-1},[e]),xe=({item:e,index:t,lastUserIndex:s,removeMessage:n,allowEditMessage:a,animationConfig:r,isLastItem:i=!1,isFirstItem:o=!1,instanceId:c})=>{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 l=h(pe,{item:e,removeMessage:n,allowEditMessage:a,animationConfig:r,isInCurrentSession:t>s,instanceId:c});return i?h("div",{style:{paddingBottom:"200px"},children:l}):o?h("div",{style:{paddingTop:"100px"},children:l}):l},be=({messages:e,removeMessage:t,allowEditMessage:s,animationConfig:a,height:r,width:i,shouldAutoScrollRef:o,isLoading:l,isResponseStarted:d,showLoadingIndicator:u,showSpacer:g,spacerKey:p,onSpacerComplete:f,instanceId:y})=>{const w=n(!0),x=ye({messages:e,isLoading:l,isResponseStarted:d,showLoadingIndicator:u,showSpacer:g,spacerKey:p,onSpacerComplete:f}),b=we(e),v=c(e=>{w.current=e,o&&(o.current=e)},[o]);c(()=>"smooth",[]);const k=c(e=>xe({item:x[e],index:e,lastUserIndex:b,removeMessage:t,allowEditMessage:s,instanceId:y,isLastItem:e===x.length-1,animationConfig:a}),[x,b,t,s,a]);return h(m,{style:{height:r,width:i},data:x,totalCount:x.length,itemContent:k,initialTopMostItemIndex:x.length-1,atBottomStateChange:v,alignToBottom:!0})},ve=({dynamicHeight:e,messages:t,removeMessage:s,allowEditMessage:a,animationConfig:r,height:i,width:l,overscan:d,listRef:u,isLoading:g,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:y,onSpacerComplete:w,instanceId:x})=>{const v=ye({messages:t,isLoading:g,isResponseStarted:m,showLoadingIndicator:p,showSpacer:f,spacerKey:y,onSpacerComplete:w}),k=we(t),S=n(new Map),I=o(()=>({itemsData:v,removeMessage:s,allowEditMessage:a,animationConfig:r,dynamicHeight:e,lastUserIndex:k,heightCacheRef:S}),[v,s,a,r,e,k]),M=c(({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:xe({item:a[e],index:e,lastUserIndex:l,removeMessage:r,isLastItem:e===a.length-1,allowEditMessage:i,animationConfig:o,instanceId:x})})},[]);return h("div",{style:{height:i,width:l,overflow:"hidden"},children:h(b,{listRef:u,rowComponent:M,rowCount:v.length,rowHeight:e,rowProps:I,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:o,shouldAutoScrollRef:l,instanceId:d})=>{const u=n(null),g=[{type:"empty-message",messageId:"empty-message"},...e],m=we(e),p=c(e=>{const t=g[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===g.length-1&&(s+=200),Math.max(s,60)},[g]),f=v({count:g.length,getScrollElement:()=>u.current,estimateSize:p,overscan:10}),{handleScroll:y}=(e=>{const t=n(!1),s=n(null),a=c(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),w=c((e=!0)=>{const t=u.current;t&&t.scrollTo({top:t.scrollHeight,behavior:e?"smooth":"auto"})},[]);ke({itemsData:g,scrollToBottom:w,shouldAutoScrollRef:l,isStreaming:o});const x=f.getVirtualItems();return h("div",{ref:u,onScroll:()=>y(u.current),className:"tanstack-virtual-container",style:{height:r,width:i,overflowY:"auto",contain:"strict"},children:h("div",{style:{height:f.getTotalSize()+"px",width:"100%",position:"relative"},children:x.map(e=>h("div",{"data-index":e.index,ref:f.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${e.start}px)`},children:xe({item:g[e.index],index:e.index,lastUserIndex:m,removeMessage:t,allowEditMessage:s,animationConfig:a,isLastItem:e.index===g.length-1,instanceId:d,isFirstItem:0===e.index})},e.key))})})},Ie=({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,instanceId:y})=>{const w=ye({messages:e,isLoading:d,isResponseStarted:u,showLoadingIndicator:g,showSpacer:m,spacerKey:p,onSpacerComplete:f}),x=we(e);return ke({itemsData:w,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:w.map((e,a)=>e?h("div",{children:xe({item:e,index:a,lastUserIndex:x,removeMessage:t,allowEditMessage:s,animationConfig:n,instanceId:y})},e.uniqueKey||e.messageId||a):null)})},Me=r(({virtualization:e="tanstack",estimateSize:t=150,overscan:s=10,isDark:r=!1,className:o="",containerStyle:d={},useGradientMask:g=!0,gradientMaskStyle:m="linear-gradient(to bottom, transparent 6.5%, black 18%)",allowEditMessage:p=!1,showWelcome:f=!0,showLoadMore:y=!0,showLoadingIndicator:w=!0,keepUserMessageInView:b=!0,initialAnimation:v=null,height:k="100%",width:S="100%"},I)=>{const[M,C]=i(!1),[N,T]=i(!1),A=n(null),{sendMsg:F,messages:E,messageManager:R,isLoading:H,isStreaming:z,isPanelOpen:_,error:L,isInitialLoading:D,isResponseStarted:O,abort:q,loadMoreMessages:P,isLoadingMore:j,hasMoreMessages:B,enableHistory:U,animationConfig:$,instanceId:W}=K(),Y=Q(W,"loading"),{showSpacer:J,spacerKey:X,triggerSpacer:G,handleSpacerComplete:V}=(()=>{const[e,t]=i(!1),[s,n]=i(0);return{showSpacer:e,spacerKey:s,triggerSpacer:()=>{t(!0),n(e=>e+1)},handleSpacerComplete:()=>{t(!1)}}})(),{scrollContainerRef:Z,shouldAutoScrollRef:ee,scrollToBottom:te,isAtBottom:ne}=(({onGradientChange:e,isStreaming:t})=>{const s=n(null),r=n(!0),i=n(!1),o=c(()=>{const e=s.current;e&&(e.scrollTop=e.scrollHeight)},[]),l=c(()=>{const e=s.current;return!!e&&50>e.scrollHeight-e.scrollTop-e.clientHeight},[]),d=c(()=>{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=c((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&&o()},100);return()=>clearInterval(e)},[t,o]),{scrollContainerRef:s,shouldAutoScrollRef:r,scrollToBottom:o,isAtBottom:l}})({onGradientChange:C,isStreaming:"none"===e&&z}),ie="react-window"===e?(({estimateSize:e})=>x({defaultRowHeight:e}))({estimateSize:t}):null,oe=c(()=>{"virtuoso"!==e&&"tanstack"!==e&&("react-window"===e&&A.current?.scrollToBottomCustom?A.current.scrollToBottomCustom():"none"===e&&te())},[e,te]),ce=c(()=>{b&&setTimeout(()=>{G()},200)},[b,G]),{removeMessage:le,handleSendMessage:de}=(({messageManager:e,sendMsg:t,shouldAutoScrollRef:s,onUserMessageSent:n})=>({removeMessage:c(t=>{e?.removeMessage&&e.removeMessage(t)},[e]),handleSendMessage:c(async e=>{s&&(s.current=!0),n&&n(),await t(e)},[t,s,n])}))({messageManager:R,sendMsg:F,scrollToBottom:oe,shouldAutoScrollRef:ee,onUserMessageSent:ce});return a(()=>{if(D)T(!1);else{if(E&&E.length>0&&!N){const e=setTimeout(()=>{T(!0)},100);return()=>clearTimeout(e)}E&&0!==E.length||T(!0)}},[D,E,N]),l(I,()=>({scrollToBottom:oe,isAtBottom:ne,scrollContainer:Z.current,dynamicHeight:ie,listRef:A.current,sendMessage:de,abort:q,isStreaming:z,isLoading:H,messages:E,messageManager:R}),[oe,ne,ie,de,q,z,H,E,R]),h("div",{className:"react-ai-agent-chat-core "+o,"data-theme":r?"dark":"light",style:{WebkitMaskImage:m,...d},children:D?h(Y||re,{}):E&&0!==E.length?u("div",{className:"react-chat-core-messages h-full w-full",style:{opacity:N?1:0,transition:"opacity 0.3s ease-out"},children:[h(se,{showLoadMore:y,enableHistory:U,hasMoreMessages:B,messagesLength:E.length,error:L,isInitialLoading:D,loadMoreMessages:P,isLoadingMore:j}),(()=>{const t={messages:E,removeMessage:le,allowEditMessage:p,animationConfig:$,isLoading:H,isResponseStarted:O,showLoadingIndicator:w,isStreaming:z,showSpacer:b&&J,spacerKey:X,onSpacerComplete:V};switch(e){case"virtuoso":return h(be,{height:k,width:S,listRef:A,shouldAutoScrollRef:ee,...t});case"react-window":return h(ve,{dynamicHeight:ie,height:k,width:S,overscan:s,listRef:A,isStreaming:z,shouldAutoScrollRef:ee,...t});case"tanstack":return h(Se,{height:k,width:S,isStreaming:z,shouldAutoScrollRef:ee,...t});default:return h(Ie,{scrollToBottom:oe,shouldAutoScrollRef:ee,isStreaming:z,scrollContainerRef:Z,height:k,width:S,...t})}})()]}):f&&h("div",{style:{opacity:N?1:0,height:"100%",width:"100%",transition:"opacity 0.3s ease-out"},children:h(ae,{error:L,isPanelOpen:_,instanceId:W})})})});Me.displayName="ChatCore";var Ce=d(Me);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]=i(!1),{sessionMetrics:s,usedTokens:n,contextLimit:a}=K(),r=(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:[r,"%"]}),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) ${r}%, 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]=i(!1),a="object"==typeof e&&e.id,r=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:r,className:"react-ai-agent-file-item-preview w-3 h-4 object-cover rounded",style:{marginRight:0,width:"12px",height:"16px"}}):h(FileIcon,{fileName:r,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:r})]},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))}),He=()=>{const[e,t]=i(0),s=n(),r=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(),r.current=e;const n=a=>{const i=a-o.current;o.current=a,r.current+=i/1e3*360,360>r.current||(r.current-=360);const c=r.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"})})})},ze="image/*,video/*,audio/*,.pdf,.doc,.docx,.txt,.md,.json,.js,.ts,.jsx,.tsx,.py,.html,.css,.xml,.csv";function _e(){const[e,t]=i([]),s=n(null),a=c(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("")},[]),r=c(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]),o=c(e=>{const t=Array.from(e.target.files||[]);t.length>0&&r(t),e.target.value=""},[r]),l=c(e=>{const t=Array.from(e.clipboardData?.items||[]).filter(e=>"file"===e.kind).map(e=>e.getAsFile()).filter(Boolean);t.length>0&&(e.preventDefault(),r(t))},[r]),d=c(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=c(()=>{t(e=>(e.forEach(e=>{e.preview&&URL.revokeObjectURL(e.preview)}),[]))},[]);return{attachedFiles:e,fileInputRef:s,onFileSelect:o,onPaste:l,removeFile:d,clearFiles:h}}const Le=()=>{const{streamError:e,clearStreamError:t,retryLastMessage:s,sendRequestCallback:n,triggerLoadingStates:a}=K(),[r]=i(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:r&&r.length>0&&r.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:r=!1})=>{const[o,c]=i(!1),l=n(null),d=e.find(e=>e.id===t)||e[0],[g,m]=i(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:()=>!r&&c(!o),disabled:r,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=>{r||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},Oe=r(({onSendMessage:e,isStreaming:t,abort:s,mode:r="advanced",todos:o=[],agents:c=[],selectedAgentId:d,onAgentChange:m},p)=>{const[f,y]=i(""),w=n(null),{attachedFiles:x,fileInputRef:b,onFileSelect:v,onPaste:k,removeFile:S,clearFiles:I}=_e();a(()=>{w.current&&(w.current.style.height="auto",w.current.style.height=Math.min(w.current.scrollHeight,150)+"px")},[f]),l(p,()=>({focus:()=>{w.current?.focus()}}),[]);const M=t=>{t.preventDefault(),(f.trim()||x.length>0)&&(e({message:f,attachedFiles:x}),y(""),I(),w.current&&(w.current.style.height="auto"))},C="advanced"===r,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"===r?"min-h-[120px]":"min-h-[100px]"),children:[t&&h("div",{className:"absolute inset-0 pointer-events-none rounded-[15px]",style:{zIndex:1},children:h(He,{})}),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"===r?"min-h-[120px]":"min-h-[100px]"),style:{zIndex:2},children:[C&&u(g,{children:[h(Ne,{todos:o}),h(Le,{}),h(Fe,{attachedFiles:x,removeFile:S})]}),h("div",{className:`react-ai-agent-input-textarea-wrapper relative pb-[${"advanced"===r?"50px":"0px"}]`,children:h("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:w,value:f,onChange:e=>y(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),M(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:ze,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"===r&&x.length>0?u("div",{className:"flex items-center gap-2",children:[h(Re,{files:x,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:d,onAgentChange:m,disabled:t}),h("button",{type:"button",onClick:e=>{t?s():M(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")})]})]})]})]})})});Oe.displayName="ChatInputDefault";var qe=d(Oe),Pe=d(({isDark:e=!1,onCreateSession:t,onClose:s,showCloseButton:n=!1})=>{const[a,r]=i(!1),[o,c]=i(!1),{instanceId:l}=K(),d=Q(l,"header");return d?d():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(r(!0),t)try{await t({replace:e})}catch(s){}finally{r(!1)}else setTimeout(()=>{r(!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=d(({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(Ce,{ref:e,isDark:t,allowEditMessage:s,className:"px-[15px]",...o}),h(qe,{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=d(({onClick:t,isDark:s=!1,isOpen:r=!1,onPositionChange:o,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),[w,x]=i({width:64,height:64}),b="number"==typeof d?d:d?.x??20,v="number"==typeof d?d:d?.y??20,k=c(()=>"undefined"==typeof window?{minX:b,minY:v,maxX:1024-w.width-b,maxY:768-w.height-v,width:1024,height:768}:{minX:b,minY:v,maxX:window.innerWidth-w.width-b,maxY:window.innerHeight-w.height-v,width:window.innerWidth,height:window.innerHeight},[w,b,v]),S=c((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]),I=c(e=>{const t=k();return!(t.minX>e.x||t.minY>e.y||e.x>t.maxX||e.y>t.maxY)},[k]),M=c(()=>{const e=k(),{width:t,minX:s,minY:n,maxX:a,maxY:r}=e;return[{x:s,y:n,name:"top-left"},{x:(t-w.width)/2,y:n,name:"top-center"},{x:a,y:n,name:"top-right"},{x:s,y:r,name:"bottom-left"},{x:(t-w.width)/2,y:r,name:"bottom-center"},{x:a,y:r,name:"bottom-right"}]},[w,k]),C=c(()=>{if("undefined"==typeof window)return M()[5];try{const e=localStorage.getItem(f);if(e){const t=JSON.parse(e);if(I(t))return t}}catch(e){}return M()[5]},[M,I]),[N,T]=i(()=>"undefined"==typeof window?{x:0,y:0,name:"bottom-right"}:C()),[A,F]=i(!1),[E,R]=i(!1),[H,z]=i({x:0,y:0}),[_,L]=i({x:0,y:0}),[D,O]=i(!1);a(()=>{if("undefined"!=typeof window&&!D){O(!0);const e=C();e&&void 0!==e.x&&void 0!==e.y&&T(e)}},[D,C]);const q=c((e,t)=>{const s=M();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},[M]),P=c(e=>{if(0!==e.button)return;const t=y.current.getBoundingClientRect(),s=e.clientX-t.left,n=e.clientY-t.top;z({x:e.clientX,y:e.clientY}),L({x:s,y:n}),F(!0),R(!1),p?.(!0),e.preventDefault()},[p]),j=c(e=>{if(!A)return;Math.sqrt(Math.pow(e.clientX-H.x,2)+Math.pow(e.clientY-H.y,2))>5&&R(!0);const t=S(e.clientX-_.x,e.clientY-_.y);T(t),l&&o&&o(t,!0,w)},[A,_,H,S,o,l,w]),B=c(e=>{if("undefined"!=typeof window)try{localStorage.setItem(f,JSON.stringify(e))}catch(t){}},[]),U=c(e=>{if(A)if(F(!1),p?.(!1),E){const e=q(N.x,N.y);T(e),setTimeout(()=>{B(e)},0),o?.(e,!1,w)}else t?.()},[A,E,N,q,t,B,o,p]);return a(()=>{if(A)return document.addEventListener("mousemove",j),document.addEventListener("mouseup",U),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",U)}},[A,j,U]),a(()=>{if("undefined"==typeof window)return;const e=()=>{if(I(N)){const e=q(N.x,N.y);T(e),setTimeout(()=>{B(e)},0),o?.(e,!1,w)}else{const e=S(N.x,N.y),t=q(e.x,e.y);T(t),setTimeout(()=>{B(t)},0),o?.(t,!1,w)}};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[N,q,B,I,S,o]),a(()=>{if("undefined"==typeof window||!y.current||!D)return;const e=()=>{if(y.current){const e=y.current.getBoundingClientRect(),t={width:e.width,height:e.height};x(e=>e.width===t.width&&e.height===t.height?e:t)}},t=setTimeout(()=>{e()},0),s=new ResizeObserver(()=>{e()});return s.observe(y.current),()=>{clearTimeout(t),s.disconnect()}},[D]),a(()=>{if("undefined"==typeof window||!N)return;const e=S(N.x,N.y);e.x===N.x&&e.y===N.y||(T(e),setTimeout(()=>{B(e)},0),o?.(e,!1,w))},[w,S,o,N,B]),a(()=>{N&&o&&requestAnimationFrame(()=>{o(N,!1,w)})},[]),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:P,children:e.isValidElement(u)?e.cloneElement(u,{isOpen:r,isDragging:A,isDark:s,onOpen:g,onClose:m,onDrag:p}):u?h(u,{isOpen:r,isDragging:A,isDark:s,onOpen:g,onClose:m,onDrag:p}):h(Be,{isOpen:r,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=d(({isDark:e=!1,allowEditMessage:t=!1,children:s,onCreateSession:r,className:l="h-full w-full",coreProps:d={},inputProps:m={},mode:p="popup",livePositionUpdate:f=!0,popupOptions:y={},popupContainerClassName:w="",popupContainerStyle:x={},floatingButtonEdgeOffset:b=25,ContentComponent:v,onOpen:k,onClose:S,onDrag:I})=>{const M=o(()=>({width:y.width??400,height:y.height??600,gap:y.gap??16,verticalPadding:y.verticalPadding??24}),[y.width,y.height,y.gap,y.verticalPadding]),C=n(null),N=n(null),[T,A]=i("default"===p),[F,E]=i(!1),[R,H]=i(null),[z,_]=i({width:64,height:64}),[L,D]=i(!1),[O,q]=i("right"),[P,j]=i("bottom"),{sendMsg:B,isStreaming:U,abort:$}=K(),W=c(async e=>{C.current?.sendMessage?await C.current.sendMessage(e):(await B(e),setTimeout(()=>{C.current?.scrollToBottom()},100))},[B]),Y=c(()=>{N.current&&clearTimeout(N.current),E(!0),A(!0),k?.(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{E(!1)})})},[k]),J=c(()=>{N.current&&clearTimeout(N.current),A(!1),S?.(),E(!0),N.current=setTimeout(()=>{E(!1),N.current=null},450)},[S]),X=c(()=>{T?J():Y()},[T,Y,J]),G=c((e,t=!1,s={width:64,height:64})=>{if(D(t),H(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",q(r),j(i)}},[]);a(()=>()=>{N.current&&clearTimeout(N.current)},[]);const Q=o(()=>{if(!R||"undefined"==typeof window)return{bottom:"96px",left:"50%"};const e=window.innerHeight;let t;return t="bottom"===P?e-R.y+M.gap:e-(R.y+z.height)-M.height-M.gap,{bottom:t+"px",left:R.x+z.width/2+"px"}},[R,z,P,M.gap,M.height]),V=o(()=>{if("undefined"==typeof window||!R)return"translateX(-50%) translateY(0)";const e=window.innerWidth,t=window.innerHeight,s=R.x+z.width/2,n=z.width/2;let a,r;r="left"===O?s-n:"right"===O?s+n-M.width:s-M.width/2,a=0>r?-s+"px":r+M.width>e?e-s-M.width+"px":"left"===O?-n+"px":"right"===O?`calc(-100% + ${n}px)`:"-50%";let i=0;if(!L)if("bottom"===P){const e=R.y-M.gap-M.height;M.verticalPadding>e&&(i=M.verticalPadding-e)}else{const e=R.y+z.height+M.gap+M.height;e>t-M.verticalPadding&&(i=t-M.verticalPadding-e)}return`translateX(${a}) translateY(${i}px)`},[O,P,R,z,L,M.width,M.gap,M.height,M.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=o(()=>({coreRef:C,isDark:e,allowEditMessage:t,onCreateSession:r,handleSendMessage:W,isStreaming:U,abort:$,coreProps:d,inputProps:m,children:s}),[e,t,r,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:I})]}:{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 "+w).trim(),style:{width:`min(${M.width}px, calc(100vw - 48px))`,height:`min(${M.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",...x},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:I})]})});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=r(({onSendMessage:e,miniMode:t=!1,isStreaming:s,abort:r,todos:o,variant:c="default",placeholder:d="Type a message...",collapsed:g=!1,onExpand:m,position:p="bottom-center",compact:f},y)=>{const[w,x]=i(""),[b,v]=i(!1),k=n(null),{attachedFiles:S,fileInputRef:I,onFileSelect:M,onPaste:C,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")},[w,g]),l(y,()=>({focus:()=>{k.current?.focus()}}),[]);const A=t=>{t.preventDefault(),(w.trim()||S.length>0)&&(e({message:w,attachedFiles:S}),x(""),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(He,{})}),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:I,type:"file",multiple:!0,accept:ze,onChange:M,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:()=>I.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:w,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),A(e))},onPaste:C,onFocus:()=>{v(!0),g&&m&&m()},onBlur:()=>{v(!1)},placeholder:d,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:()=>I.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?r():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:!w.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=d(Ye),Ke=d(({allowEditMessage:e=!1,children:t,placeholder:s="Ask me anything...",position:r="bottom-center",isDark:o,compact:l,coreProps:d={},inputProps:g={},onExpand:m,onClose:p,bottomBlur:f})=>{const[y,w]=i(!1),[x,b]=i(!1),[v,k]=i(!1),[S,I]=i(!1),M=n(null),C=n(null),N=n([]),[T,A]=i(o),{isStreaming:F,abort:E}=K(),R=c(()=>{N.current.forEach(e=>clearTimeout(e)),N.current=[]},[]),H=c(async e=>{M.current?.sendMessage?await M.current.sendMessage(e):setTimeout(()=>{M.current?.scrollToBottom()},100)},[]),z=c(()=>{R(),b(!1),k(!1),w(!0),I(!1),m?.(),A(!0);const e=setTimeout(()=>{I(!0)},350);N.current.push(e);const t=setTimeout(()=>{C.current?.focus()},400);N.current.push(t)},[R]),_=c(()=>{R(),b(!0),w(!1),setTimeout(()=>{p?.(),A(o)},500);const e=setTimeout(()=>{k(!0)},250);N.current.push(e);const t=setTimeout(()=>{I(!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||x;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:x?0:1,transition:"opacity 0.25s ease-out"},children:h(Ce,{ref:M,isDark:o,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(r){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:C,collapsed:!y,onExpand:z,onSendMessage:H,isStreaming:F,abort:E,variant:y?"pill":"collapsed",placeholder:s,position:r,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),o=!("string"!=typeof e||t||s&&0!==Object.keys(s).length),l=o?e:s.instanceId||null,d=n(t),h=n(s);a(()=>{d.current=t,h.current=s}),a(()=>{if(o)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=c((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=c(e=>{const t=i.current.get(e);t&&(t(),i.current.delete(e))},[]),m=c(()=>r.getActiveSessions(),[r]),p=c(e=>r.handlers[e],[r]),f=c(()=>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,Ce 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,I 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,H as getGlobalStatusRegistry,rt as parseSSEChunk,$ as resetGlobalForwardingManager,U as setGlobalForwardingManager,K as useChatContext,it as useForwarding,Y as useStatusSubscription};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-ai-agent",
3
- "version": "1.6.8",
3
+ "version": "1.7.1",
4
4
  "type": "module",
5
5
  "description": "React Chat Agent - A production-ready chat provider with WebSocket support",
6
6
  "main": "dist/index.cjs",